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
127 if( newFileName.HasExt() )
128 {
129 wxString extraDir = newFileName.GetFullName();
130 newFileName.ClearExt();
131 newFileName.SetName( "" );
132 newFileName.AppendDir( extraDir );
133 }
134
135 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
136 return false;
137
138 try
139 {
140 bool bestEfforts = false; // throw on first error
141 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
142
143 for( const wxString& dbName : dbNames )
144 {
145 std::unique_ptr<const DESIGN_BLOCK> db( oldFilePI->GetEnumeratedDesignBlock( aOldFilePath, dbName,
146 aOldFileProps ) );
147 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
148 }
149 }
150 catch( ... )
151 {
152 return false;
153 }
154
155 return true;
156}
157
158
160{
161 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
163}
164
165
166long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
167{
168 wxDir libDir( aLibraryPath );
169
170 if( !libDir.IsOpened() )
171 return 0;
172
173 long long ts = 0;
174
175 wxString filename;
176 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
177
178 while( hasMoreFiles )
179 {
180 wxFileName blockDir( aLibraryPath, filename );
181
182 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
183 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
184 ts += KIPLATFORM::IO::TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
185
186 hasMoreFiles = libDir.GetNext( &filename );
187 }
188
189 return ts;
190}
191
192
193void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
194 const std::map<std::string, UTF8>* aProperties )
195{
196 if( wxDir::Exists( aLibraryPath ) )
197 THROW_IO_ERRORF( _( "Cannot overwrite library path '%s'." ), aLibraryPath.GetData() );
198
199 wxFileName dir;
200 dir.SetPath( aLibraryPath );
201
202 if( !dir.Mkdir() )
203 {
204 THROW_IO_ERRORF( _( "Library path '%s' could not be created.\n\n"
205 "Make sure you have write permissions and try again." ), dir.GetPath() );
206 }
207}
208
209
210bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
211 const std::map<std::string, UTF8>* aProperties )
212{
213 wxFileName fn;
214 fn.SetPath( aLibraryPath );
215
216 // Return if there is no library path to delete.
217 if( !fn.DirExists() )
218 return false;
219
220 if( !fn.IsDirWritable() )
221 THROW_IO_ERRORF( _( "Insufficient permissions to delete folder '%s'." ), aLibraryPath.GetData() );
222
223 wxDir dir( aLibraryPath );
224
225 // Design block folders should only contain sub-folders for each design block
226 if( dir.HasFiles() )
227 THROW_IO_ERRORF( _( "Library folder '%s' has unexpected files." ), aLibraryPath.GetData() );
228
229 // Must delete all sub-directories before deleting the library directory
230 if( dir.HasSubDirs() )
231 {
232 wxArrayString dirs;
233
234 // Get all sub-directories in the library path
235 CollectSubdirsLoopSafe( aLibraryPath, dirs );
236
237 for( size_t i = 0; i < dirs.GetCount(); i++ )
238 {
239 wxFileName tmp = dirs[i];
240
242 {
243 THROW_IO_ERRORF( _( "Unexpected folder '%s' found in library path '%s'." ),
244 dirs[i].GetData(),
245 aLibraryPath.GetData() );
246 }
247 }
248
249 for( size_t i = 0; i < dirs.GetCount(); i++ )
250 wxRemoveFile( dirs[i] );
251 }
252
253 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ), aLibraryPath.GetData() );
254
255 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
256 // we don't want that. we want bare metal portability with no UI here.
257 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
258 THROW_IO_ERRORF( _( "Design block library '%s' cannot be deleted." ), aLibraryPath.GetData() );
259
260 // For some reason removing a directory in Windows is not immediately updated. This delay
261 // prevents an error when attempting to immediately recreate the same directory when over
262 // writing an existing library.
263#ifdef __WINDOWS__
264 wxMilliSleep( 250L );
265#endif
266
267 return true;
268}
269
270
271void DESIGN_BLOCK_IO::DesignBlockEnumerate( wxArrayString& aDesignBlockNames,
272 const wxString& aLibraryPath, bool aBestEfforts,
273 const std::map<std::string, UTF8>* aProperties )
274{
275 // From the starting directory, look for all directories ending in the .kicad_block extension
276 wxDir dir( aLibraryPath );
277
278 if( !dir.IsOpened() )
279 THROW_IO_ERRORF( _( "Design block '%s' does not exist." ), aLibraryPath );
280
281 wxString dirname;
282 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadDesignBlockPathExtension );
283 bool cont = dir.GetFirst( &dirname, fileSpec, wxDIR_DIRS );
284
285 while( cont )
286 {
287 aDesignBlockNames.Add( dirname.Before( wxT( '.' ) ) );
288 cont = dir.GetNext( &dirname );
289 }
290}
291
292
293DESIGN_BLOCK* DESIGN_BLOCK_IO::DesignBlockLoad( const wxString& aLibraryPath,
294 const wxString& aDesignBlockName, bool aKeepUUID,
295 const std::map<std::string, UTF8>* aProperties )
296{
297 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
298 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
299 wxString dbSchPath = dbPath + aDesignBlockName + wxT( "." )
301 wxString dbPcbPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::KiCadPcbFileExtension;
302 wxString dbMetadataPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::JsonFileExtension;
303
304 if( !wxDir::Exists( dbPath ) )
305 THROW_IO_ERRORF( _( "Design block '%s' does not exist." ), dbPath );
306
307 DESIGN_BLOCK* newDB = new DESIGN_BLOCK();
308
309 // Library name needs to be empty for when we fill it in with the correct library nickname
310 // one layer above
311 newDB->SetLibId( LIB_ID( wxEmptyString, aDesignBlockName ) );
312
313 if( wxFileExists( dbSchPath ) )
314 newDB->SetSchematicFile( dbSchPath );
315
316 if( wxFileExists( dbPcbPath ) )
317 newDB->SetBoardFile( dbPcbPath );
318
319 // Parse the JSON file if it exists
320 if( wxFileExists( dbMetadataPath ) )
321 {
322 try
323 {
324 nlohmann::ordered_json dbMetadata;
325 std::ifstream dbMetadataFile( dbMetadataPath.fn_str() );
326
327 dbMetadataFile >> dbMetadata;
328
329 if( dbMetadata.contains( "description" ) )
330 newDB->SetLibDescription( dbMetadata["description"].get<std::string>() );
331
332 if( dbMetadata.contains( "keywords" ) )
333 newDB->SetKeywords( dbMetadata["keywords"].get<std::string>() );
334
335 // Read the "fields" object from the JSON
336 if( dbMetadata.contains( "fields" ) )
337 {
338 for( auto& item : dbMetadata["fields"].items() )
339 {
340 wxString name = wxString::FromUTF8( item.key() );
341 wxString value = wxString::FromUTF8( item.value().get<std::string>() );
342
343 newDB->GetFields()[name] = value;
344 }
345 }
346 }
347 catch( ... )
348 {
349 delete newDB;
350 THROW_IO_ERRORF( _( "Design block metadata file '%s' could not be read." ), dbMetadataPath );
351 }
352 }
353
354 return newDB;
355}
356
357
358bool DESIGN_BLOCK_IO::DesignBlockExists( const wxString& aLibraryPath,
359 const wxString& aDesignBlockName,
360 const std::map<std::string, UTF8>* aProperties )
361{
362 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
363 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
364
365 return wxDir::Exists( dbPath );
366}
367
368
369void DESIGN_BLOCK_IO::DesignBlockSave( const wxString& aLibraryPath,
370 const DESIGN_BLOCK* aDesignBlock,
371 const std::map<std::string, UTF8>* aProperties )
372{
373 // Make sure we have a valid LIB_ID or we can't save the design block
374 if( !aDesignBlock->GetLibId().IsValid() )
375 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
376
377 if( aDesignBlock->GetSchematicFile().IsEmpty() && aDesignBlock->GetBoardFile().IsEmpty() )
378 THROW_IO_ERROR( _( "Design block does not have a schematic or board file." ) );
379
380 wxFileName schematicFile( aDesignBlock->GetSchematicFile() );
381 wxFileName boardFile( aDesignBlock->GetBoardFile() );
382
383 if( !aDesignBlock->GetSchematicFile().IsEmpty() && !schematicFile.FileExists() )
384 THROW_IO_ERRORF( _( "Schematic source file '%s' does not exist." ), schematicFile.GetFullPath() );
385
386 if( !aDesignBlock->GetBoardFile().IsEmpty() && !boardFile.FileExists() )
387 THROW_IO_ERRORF( _( "Board source file '%s' does not exist." ), boardFile.GetFullPath() );
388
389 // Create the design block folder
390 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
391 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
393 + wxFileName::GetPathSeparator() );
394
395 if( !dbFolder.DirExists() )
396 {
397 if( !dbFolder.Mkdir() )
398 THROW_IO_ERRORF( _( "Design block folder '%s' could not be created." ), dbFolder.GetFullPath().GetData() );
399 }
400
401 if( !aDesignBlock->GetSchematicFile().IsEmpty() )
402 {
403 // The new schematic file name is based on the design block name, not the source sheet name
404 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
406
407 // If the source and destination files are the same, then we don't need to copy the file
408 // as we are just updating the metadata
409 if( schematicFile.GetFullPath() != dbSchematicFile )
410 {
411 // Copy the source sheet file to the design block folder, under the design block name
412 if( !wxCopyFile( schematicFile.GetFullPath(), dbSchematicFile ) )
413 {
414 THROW_IO_ERRORF( _( "Schematic file '%s' could not be saved as design block at '%s'." ),
415 schematicFile.GetFullPath(),
416 dbSchematicFile );
417 }
418 }
419 }
420
421 if( !aDesignBlock->GetBoardFile().IsEmpty() )
422 {
423 // The new Board file name is based on the design block name, not the source sheet name
424 wxString dbBoardFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
426
427 // If the source and destination files are the same, then we don't need to copy the file
428 // as we are just updating the metadata
429 if( boardFile.GetFullPath() != dbBoardFile )
430 {
431 // Copy the source sheet file to the design block folder, under the design block name
432 if( !wxCopyFile( boardFile.GetFullPath(), dbBoardFile ) )
433 {
434 THROW_IO_ERRORF( _( "Board file '%s' could not be saved as design block at '%s'." ),
435 boardFile.GetFullPath(),
436 dbBoardFile );
437 }
438 }
439 }
440
441 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
442 + wxT( "." ) + FILEEXT::JsonFileExtension;
443
444 // Write the metadata file
445 nlohmann::ordered_json dbMetadata;
446 dbMetadata["description"] = aDesignBlock->GetLibDescription();
447 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
448 dbMetadata["fields"] = aDesignBlock->GetFields();
449
450 bool success = false;
451
452 try
453 {
454 std::string payload = dbMetadata.dump( 0 );
455 wxString writeError;
456 success = KIPLATFORM::IO::AtomicWriteFile( dbMetadataFile, payload.data(), payload.size(), &writeError );
457
458 if( !success )
459 wxLogError( _( "Cannot save design block metadata '%s': %s" ), dbMetadataFile, writeError );
460 }
461 catch( ... )
462 {
463 success = false;
464 }
465
466 if( !success )
467 THROW_IO_ERRORF( _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile );
468}
469
470
471void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
472 const std::map<std::string, UTF8>* aProperties )
473{
474 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
476
477 if( !dbDir.DirExists() )
478 THROW_IO_ERRORF( _( "Design block '%s' does not exist." ), dbDir.GetFullName() );
479
480 // Delete the whole design block folder
481 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
482 THROW_IO_ERRORF( _( "Design block folder '%s' could not be deleted." ), dbDir.GetFullPath().GetData() );
483}
484
485
486bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
487{
488 wxFileName path( aLibraryPath );
489 return path.IsOk() && path.IsDirWritable();
490}
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
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:883
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 THROW_IO_ERRORF(msg,...)
#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.