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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <common.h>
22#include <gestfich.h>
23#include <json_common.h>
24#include <i18n_utility.h>
25#include <kiplatform/io.h>
26#include <wx/dir.h>
27#include <wx/ffile.h>
28#include <wx/filename.h>
29#include <wx/log.h>
30#include <wx/translation.h>
31#include <wx/string.h>
32#include <wx/arrstr.h>
33#include <wx/datetime.h>
35#include <kiway_player.h>
36#include <design_block_io.h>
37#include <design_block.h>
38#include <ki_exception.h>
39#include <trace_helpers.h>
40#include <fstream>
43
45{
46 // This token is serialized into the design-block-lib-table file, so it must stay
47 // locale-independent. "KiCad" is a product name and is never translated.
48 switch( aFileType )
49 {
50 case KICAD_SEXP: return wxT( "KiCad" );
52 default: return wxString::Format( wxT( "UNKNOWN (%d)" ), aFileType );
53 }
54}
55
56
58DESIGN_BLOCK_IO_MGR::EnumFromStr( const wxString& aFileType )
59{
60 if( aFileType.CmpNoCase( wxT( "KiCad" ) ) == 0 )
62 else if( aFileType == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
64 else if( aFileType == _( "KiCad" ) )
65 {
66 // Accept the legacy translated token so tables written by older releases under a
67 // locale that translated "KiCad" still load.
69 }
70
72}
73
74
76{
77 switch( aFileType )
78 {
79 case KICAD_SEXP: return new DESIGN_BLOCK_IO();
80 default: return nullptr;
81 }
82}
83
84
86DESIGN_BLOCK_IO_MGR::GuessPluginTypeFromLibPath( const wxString& aLibPath, int aCtl )
87{
89
90 if( parser.Parse( aLibPath.ToStdString() ).has_value() )
91 return NESTED_TABLE;
92
93 if( IO_RELEASER<DESIGN_BLOCK_IO>( FindPlugin( KICAD_SEXP ) )->CanReadLibrary( aLibPath )
94 && aCtl != KICTL_NONKICAD_ONLY )
95 {
96 return KICAD_SEXP;
97 }
98
100}
101
102
103bool DESIGN_BLOCK_IO_MGR::ConvertLibrary( std::map<std::string, UTF8>* aOldFileProps,
104 const wxString& aOldFilePath,
105 const wxString& aNewFilePath )
106{
109
110 if( oldFileType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
111 return false;
112
113 // A nested library table has no plugin to enumerate it; reject it before dereferencing
114 // the null plugin below.
115 if( oldFileType == DESIGN_BLOCK_IO_MGR::NESTED_TABLE )
116 return false;
117
120
121 if( !oldFilePI || !kicadPI )
122 return false;
123
124 wxArrayString dbNames;
125 wxFileName newFileName( aNewFilePath );
126 wxString newLibName = LIB_ID::FixIllegalChars( newFileName.GetName(), true ).wx_str();
127
128 if( newFileName.HasExt() )
129 {
130 wxString extraDir = newFileName.GetFullName();
131 newFileName.ClearExt();
132 newFileName.SetName( "" );
133 newFileName.AppendDir( extraDir );
134 }
135
136 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
137 return false;
138
139 try
140 {
141 bool bestEfforts = false; // throw on first error
142 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
143
144 for( const wxString& dbName : dbNames )
145 {
146 std::unique_ptr<DESIGN_BLOCK> db(
147 oldFilePI->DesignBlockLoad( aOldFilePath, dbName, false, aOldFileProps ) );
148 db->SetLibId( LIB_ID( newLibName, dbName ) );
149 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
150 }
151 }
152 catch( ... )
153 {
154 return false;
155 }
156
157 return true;
158}
159
160
162{
163 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
165}
166
167
168long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
169{
170 wxDir libDir( aLibraryPath );
171
172 if( !libDir.IsOpened() )
173 return 0;
174
175 long long ts = 0;
176
177 wxString filename;
178 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
179
180 while( hasMoreFiles )
181 {
182 wxFileName blockDir( aLibraryPath, filename );
183
184 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
185 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
186 ts += KIPLATFORM::IO::TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
187
188 hasMoreFiles = libDir.GetNext( &filename );
189 }
190
191 return ts;
192}
193
194
195void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
196 const std::map<std::string, UTF8>* aProperties )
197{
198 if( wxDir::Exists( aLibraryPath ) )
199 THROW_IO_ERRORF( _( "Cannot overwrite library path '%s'." ), aLibraryPath.GetData() );
200
201 wxFileName dir;
202 dir.SetPath( aLibraryPath );
203
204 if( !dir.Mkdir() )
205 {
206 THROW_IO_ERRORF( _( "Library path '%s' could not be created.\n\n"
207 "Make sure you have write permissions and try again." ), dir.GetPath() );
208 }
209}
210
211
212bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
213 const std::map<std::string, UTF8>* aProperties )
214{
215 wxFileName fn;
216 fn.SetPath( aLibraryPath );
217
218 // Return if there is no library path to delete.
219 if( !fn.DirExists() )
220 return false;
221
222 if( !fn.IsDirWritable() )
223 THROW_IO_ERRORF( _( "Insufficient permissions to delete folder '%s'." ), aLibraryPath.GetData() );
224
225 wxDir dir( aLibraryPath );
226
227 // Design block folders should only contain sub-folders for each design block
228 if( dir.HasFiles() )
229 THROW_IO_ERRORF( _( "Library folder '%s' has unexpected files." ), aLibraryPath.GetData() );
230
231 // Must delete all sub-directories before deleting the library directory
232 if( dir.HasSubDirs() )
233 {
234 wxArrayString dirs;
235
236 // Get all sub-directories in the library path
237 CollectSubdirsLoopSafe( aLibraryPath, dirs );
238
239 for( size_t i = 0; i < dirs.GetCount(); i++ )
240 {
241 wxFileName tmp = dirs[i];
242
243 if( tmp.GetExt() != FILEEXT::KiCadDesignBlockPathExtension )
244 {
245 THROW_IO_ERRORF( _( "Unexpected folder '%s' found in library path '%s'." ),
246 dirs[i].GetData(),
247 aLibraryPath.GetData() );
248 }
249 }
250
251 for( size_t i = 0; i < dirs.GetCount(); i++ )
252 wxRemoveFile( dirs[i] );
253 }
254
255 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ), aLibraryPath.GetData() );
256
257 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
258 // we don't want that. we want bare metal portability with no UI here.
259 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
260 THROW_IO_ERRORF( _( "Design block library '%s' cannot be deleted." ), aLibraryPath.GetData() );
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 THROW_IO_ERRORF( _( "Design block library folder '%s' could not be opened." ), aLibraryPath );
282
283 wxString dirname;
284 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadDesignBlockPathExtension );
285 bool cont = dir.GetFirst( &dirname, fileSpec, wxDIR_DIRS );
286
287 while( cont )
288 {
289 aDesignBlockNames.Add( dirname.BeforeLast( wxT( '.' ) ) );
290 cont = dir.GetNext( &dirname );
291 }
292}
293
294
295DESIGN_BLOCK* DESIGN_BLOCK_IO::DesignBlockLoad( const wxString& aLibraryPath,
296 const wxString& aDesignBlockName, bool aKeepUUID,
297 const std::map<std::string, UTF8>* aProperties )
298{
299 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
300 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
301 wxString dbSchPath = dbPath + aDesignBlockName + wxT( "." )
303 wxString dbPcbPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::KiCadPcbFileExtension;
304 wxString dbMetadataPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::JsonFileExtension;
305
306 if( !wxDir::Exists( dbPath ) )
307 THROW_IO_ERRORF( _( "Design block '%s' does not exist in library '%s'." ), aDesignBlockName, aLibraryPath );
308
309 DESIGN_BLOCK* newDB = new DESIGN_BLOCK();
310
311 // Library name needs to be empty for when we fill it in with the correct library nickname
312 // one layer above
313 newDB->SetLibId( LIB_ID( wxEmptyString, aDesignBlockName ) );
314
315 if( wxFileExists( dbSchPath ) )
316 newDB->SetSchematicFile( dbSchPath );
317
318 if( wxFileExists( dbPcbPath ) )
319 newDB->SetBoardFile( dbPcbPath );
320
321 // Parse the JSON file if it exists
322 if( wxFileExists( dbMetadataPath ) )
323 {
324 try
325 {
326 nlohmann::ordered_json dbMetadata;
327 std::ifstream dbMetadataFile( dbMetadataPath.fn_str() );
328
329 dbMetadataFile >> dbMetadata;
330
331 if( dbMetadata.contains( "description" ) )
332 newDB->SetLibDescription( dbMetadata["description"].get<std::string>() );
333
334 if( dbMetadata.contains( "keywords" ) )
335 newDB->SetKeywords( dbMetadata["keywords"].get<std::string>() );
336
337 // Read the "fields" object from the JSON
338 if( dbMetadata.contains( "fields" ) )
339 {
340 for( auto& item : dbMetadata["fields"].items() )
341 {
342 wxString name = wxString::FromUTF8( item.key() );
343 wxString value = wxString::FromUTF8( item.value().get<std::string>() );
344
345 newDB->GetFields()[name] = value;
346 }
347 }
348 }
349 catch( ... )
350 {
351 delete newDB;
352 THROW_IO_ERRORF( _( "Design block metadata file '%s' could not be read." ), dbMetadataPath );
353 }
354 }
355
356 return newDB;
357}
358
359
360bool DESIGN_BLOCK_IO::DesignBlockExists( const wxString& aLibraryPath,
361 const wxString& aDesignBlockName,
362 const std::map<std::string, UTF8>* aProperties )
363{
364 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
365 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
366
367 return wxDir::Exists( dbPath );
368}
369
370
371void DESIGN_BLOCK_IO::DesignBlockSave( const wxString& aLibraryPath,
372 const DESIGN_BLOCK* aDesignBlock,
373 const std::map<std::string, UTF8>* aProperties )
374{
375 // Make sure we have a valid LIB_ID or we can't save the design block
376 if( !aDesignBlock->GetLibId().IsValid() )
377 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
378
379 if( aDesignBlock->GetSchematicFile().IsEmpty() && aDesignBlock->GetBoardFile().IsEmpty() )
380 THROW_IO_ERROR( _( "Design block does not have a schematic or board file." ) );
381
382 wxFileName schematicFile( aDesignBlock->GetSchematicFile() );
383 wxFileName boardFile( aDesignBlock->GetBoardFile() );
384
385 if( !aDesignBlock->GetSchematicFile().IsEmpty() && !schematicFile.FileExists() )
386 THROW_IO_ERRORF( _( "Schematic source file '%s' does not exist." ), schematicFile.GetFullPath() );
387
388 if( !aDesignBlock->GetBoardFile().IsEmpty() && !boardFile.FileExists() )
389 THROW_IO_ERRORF( _( "Board source file '%s' does not exist." ), boardFile.GetFullPath() );
390
391 // Create the design block folder
392 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
393 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
395 + wxFileName::GetPathSeparator() );
396
397 if( !dbFolder.DirExists() )
398 {
399 if( !dbFolder.Mkdir() )
400 THROW_IO_ERRORF( _( "Design block folder '%s' could not be created." ), dbFolder.GetFullPath().GetData() );
401 }
402
403 if( !aDesignBlock->GetSchematicFile().IsEmpty() )
404 {
405 // The new schematic file name is based on the design block name, not the source sheet name
406 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
408
409 // If the source and destination files are the same, then we don't need to copy the file
410 // as we are just updating the metadata
411 if( schematicFile.GetFullPath() != dbSchematicFile )
412 {
413 // Copy the source sheet file to the design block folder, under the design block name
414 if( !wxCopyFile( schematicFile.GetFullPath(), dbSchematicFile ) )
415 {
416 THROW_IO_ERRORF( _( "Schematic file '%s' could not be saved as design block at '%s'." ),
417 schematicFile.GetFullPath(),
418 dbSchematicFile );
419 }
420 }
421 }
422
423 if( !aDesignBlock->GetBoardFile().IsEmpty() )
424 {
425 // The new Board file name is based on the design block name, not the source sheet name
426 wxString dbBoardFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
428
429 // If the source and destination files are the same, then we don't need to copy the file
430 // as we are just updating the metadata
431 if( boardFile.GetFullPath() != dbBoardFile )
432 {
433 // Copy the source sheet file to the design block folder, under the design block name
434 if( !wxCopyFile( boardFile.GetFullPath(), dbBoardFile ) )
435 {
436 THROW_IO_ERRORF( _( "Board file '%s' could not be saved as design block at '%s'." ),
437 boardFile.GetFullPath(),
438 dbBoardFile );
439 }
440 }
441 }
442
443 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
444 + wxT( "." ) + FILEEXT::JsonFileExtension;
445
446 // Write the metadata file
447 nlohmann::ordered_json dbMetadata;
448 dbMetadata["description"] = aDesignBlock->GetLibDescription();
449 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
450 dbMetadata["fields"] = aDesignBlock->GetFields();
451
452 bool success = false;
453
454 try
455 {
456 std::string payload = dbMetadata.dump( 0 );
457 wxString writeError;
458 success = KIPLATFORM::IO::AtomicWriteFile( dbMetadataFile, payload.data(), payload.size(), &writeError );
459
460 if( !success )
461 wxLogError( _( "Cannot save design block metadata '%s': %s" ), dbMetadataFile, writeError );
462 }
463 catch( ... )
464 {
465 success = false;
466 }
467
468 if( !success )
469 THROW_IO_ERRORF( _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile );
470}
471
472
473void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
474 const std::map<std::string, UTF8>* aProperties )
475{
476 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
478
479 if( !dbDir.DirExists() )
480 THROW_IO_ERRORF( _( "Design block '%s' does not exist." ), dbDir.GetFullName() );
481
482 // Delete the whole design block folder
483 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
484 THROW_IO_ERRORF( _( "Design block folder '%s' could not be deleted." ), dbDir.GetFullPath().GetData() );
485}
486
487
488bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
489{
490 wxFileName path( aLibraryPath );
491 return path.IsOk() && path.IsDirWritable();
492}
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:45
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
wxString wx_str() const
Definition utf8.cpp:41
#define _(s)
void CollectSubdirsLoopSafe(const wxString &aRoot, wxArrayString &aDirs, int aFlags)
Recursively collect every subdirectory under aRoot using the same loop detection as CollectFilesLoopS...
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
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 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:40
Container that describes file type info.
Definition io_base.h:43
std::string path
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.