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 <i18n_utility.h>
27#include <kiplatform/io.h>
28#include <wx/dir.h>
29#include <wx/ffile.h>
30#include <wx/filename.h>
31#include <wx/log.h>
32#include <wx/translation.h>
33#include <wx/string.h>
34#include <wx/arrstr.h>
35#include <wx/datetime.h>
37#include <kiway_player.h>
38#include <design_block_io.h>
39#include <design_block.h>
40#include <ki_exception.h>
41#include <trace_helpers.h>
42#include <fstream>
45
47{
48 switch( aFileType )
49 {
50 case KICAD_SEXP: return _( "KiCad" );
52 default: return wxString::Format( _( "UNKNOWN (%d)" ), aFileType );
53 }
54}
55
56
58DESIGN_BLOCK_IO_MGR::EnumFromStr( const wxString& aFileType )
59{
60 if( aFileType == _( "KiCad" ) )
62 else if( aFileType == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
64
66}
67
68
70{
71 switch( aFileType )
72 {
73 case KICAD_SEXP: return new DESIGN_BLOCK_IO();
74 default: return nullptr;
75 }
76}
77
78
80DESIGN_BLOCK_IO_MGR::GuessPluginTypeFromLibPath( const wxString& aLibPath, int aCtl )
81{
83
84 if( parser.Parse( aLibPath.ToStdString() ).has_value() )
85 return NESTED_TABLE;
86
87 if( IO_RELEASER<DESIGN_BLOCK_IO>( FindPlugin( KICAD_SEXP ) )->CanReadLibrary( aLibPath )
88 && aCtl != KICTL_NONKICAD_ONLY )
89 {
90 return KICAD_SEXP;
91 }
92
94}
95
96
97bool DESIGN_BLOCK_IO_MGR::ConvertLibrary( std::map<std::string, UTF8>* aOldFileProps,
98 const wxString& aOldFilePath,
99 const wxString& aNewFilePath )
100{
103
104 if( oldFileType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
105 return false;
106
107
110 wxArrayString dbNames;
111 wxFileName newFileName( aNewFilePath );
112
113 if( newFileName.HasExt() )
114 {
115 wxString extraDir = newFileName.GetFullName();
116 newFileName.ClearExt();
117 newFileName.SetName( "" );
118 newFileName.AppendDir( extraDir );
119 }
120
121 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
122 return false;
123
124 try
125 {
126 bool bestEfforts = false; // throw on first error
127 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
128
129 for( const wxString& dbName : dbNames )
130 {
131 std::unique_ptr<const DESIGN_BLOCK> db( oldFilePI->GetEnumeratedDesignBlock( aOldFilePath, dbName,
132 aOldFileProps ) );
133 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
134 }
135 }
136 catch( ... )
137 {
138 return false;
139 }
140
141 return true;
142}
143
144
146{
147 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
149}
150
151
152long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
153{
154 wxDir libDir( aLibraryPath );
155
156 if( !libDir.IsOpened() )
157 return 0;
158
159 long long ts = 0;
160
161 wxString filename;
162 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
163
164 while( hasMoreFiles )
165 {
166 wxFileName blockDir( aLibraryPath, filename );
167
168 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
169 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
170 ts += KIPLATFORM::IO::TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
171
172 hasMoreFiles = libDir.GetNext( &filename );
173 }
174
175 return ts;
176}
177
178
179void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
180 const std::map<std::string, UTF8>* aProperties )
181{
182 if( wxDir::Exists( aLibraryPath ) )
183 {
184 THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path '%s'." ),
185 aLibraryPath.GetData() ) );
186 }
187
188 wxFileName dir;
189 dir.SetPath( aLibraryPath );
190
191 if( !dir.Mkdir() )
192 {
194 wxString::Format( _( "Library path '%s' could not be created.\n\n"
195 "Make sure you have write permissions and try again." ),
196 dir.GetPath() ) );
197 }
198}
199
200
201bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
202 const std::map<std::string, UTF8>* aProperties )
203{
204 wxFileName fn;
205 fn.SetPath( aLibraryPath );
206
207 // Return if there is no library path to delete.
208 if( !fn.DirExists() )
209 return false;
210
211 if( !fn.IsDirWritable() )
212 {
213 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete folder '%s'." ),
214 aLibraryPath.GetData() ) );
215 }
216
217 wxDir dir( aLibraryPath );
218
219 // Design block folders should only contain sub-folders for each design block
220 if( dir.HasFiles() )
221 {
222 THROW_IO_ERROR( wxString::Format( _( "Library folder '%s' has unexpected files." ),
223 aLibraryPath.GetData() ) );
224 }
225
226 // Must delete all sub-directories before deleting the library directory
227 if( dir.HasSubDirs() )
228 {
229 wxArrayString dirs;
230
231 // Get all sub-directories in the library path
232 dir.GetAllFiles( aLibraryPath, &dirs, wxEmptyString, wxDIR_DIRS );
233
234 for( size_t i = 0; i < dirs.GetCount(); i++ )
235 {
236 wxFileName tmp = dirs[i];
237
239 {
240 THROW_IO_ERROR( wxString::Format( _( "Unexpected folder '%s' found in library path '%s'." ),
241 dirs[i].GetData(), aLibraryPath.GetData() ) );
242 }
243 }
244
245 for( size_t i = 0; i < dirs.GetCount(); i++ )
246 wxRemoveFile( dirs[i] );
247 }
248
249 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ),
250 aLibraryPath.GetData() );
251
252 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
253 // we don't want that. we want bare metal portability with no UI here.
254 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
255 {
256 THROW_IO_ERROR( wxString::Format( _( "Design block library '%s' cannot be deleted." ),
257 aLibraryPath.GetData() ) );
258 }
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 {
280 THROW_IO_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), aLibraryPath ) );
281 }
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.Before( 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_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), dbPath ) );
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"] );
333
334 if( dbMetadata.contains( "keywords" ) )
335 newDB->SetKeywords( dbMetadata["keywords"] );
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_ERROR( wxString::Format( _( "Design block metadata file '%s' could not be read." ),
353 dbMetadataPath ) );
354 }
355 }
356
357 return newDB;
358}
359
360
361bool DESIGN_BLOCK_IO::DesignBlockExists( const wxString& aLibraryPath,
362 const wxString& aDesignBlockName,
363 const std::map<std::string, UTF8>* aProperties )
364{
365 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
366 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
367
368 return wxDir::Exists( dbPath );
369}
370
371
372void DESIGN_BLOCK_IO::DesignBlockSave( const wxString& aLibraryPath,
373 const DESIGN_BLOCK* aDesignBlock,
374 const std::map<std::string, UTF8>* aProperties )
375{
376 // Make sure we have a valid LIB_ID or we can't save the design block
377 if( !aDesignBlock->GetLibId().IsValid() )
378 {
379 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
380 }
381
382 if( aDesignBlock->GetSchematicFile().IsEmpty() && aDesignBlock->GetBoardFile().IsEmpty() )
383 {
384 THROW_IO_ERROR( _( "Design block does not have a schematic or board file." ) );
385 }
386
387 wxFileName schematicFile( aDesignBlock->GetSchematicFile() );
388 wxFileName boardFile( aDesignBlock->GetBoardFile() );
389
390 if( !aDesignBlock->GetSchematicFile().IsEmpty() && !schematicFile.FileExists() )
391 {
393 wxString::Format( _( "Schematic source file '%s' does not exist." ), schematicFile.GetFullPath() ) );
394 }
395
396 if( !aDesignBlock->GetBoardFile().IsEmpty() && !boardFile.FileExists() )
397 {
398 THROW_IO_ERROR( wxString::Format( _( "Board source file '%s' does not exist." ), boardFile.GetFullPath() ) );
399 }
400
401 // Create the design block folder
402 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
403 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
405 + wxFileName::GetPathSeparator() );
406
407 if( !dbFolder.DirExists() )
408 {
409 if( !dbFolder.Mkdir() )
410 {
411 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be created." ),
412 dbFolder.GetFullPath().GetData() ) );
413 }
414 }
415
416 if( !aDesignBlock->GetSchematicFile().IsEmpty() )
417 {
418 // The new schematic file name is based on the design block name, not the source sheet name
419 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
421
422 // If the source and destination files are the same, then we don't need to copy the file
423 // as we are just updating the metadata
424 if( schematicFile.GetFullPath() != dbSchematicFile )
425 {
426 // Copy the source sheet file to the design block folder, under the design block name
427 if( !wxCopyFile( schematicFile.GetFullPath(), dbSchematicFile ) )
428 {
430 wxString::Format( _( "Schematic file '%s' could not be saved as design block at '%s'." ),
431 schematicFile.GetFullPath(), dbSchematicFile ) );
432 }
433 }
434 }
435
436 if( !aDesignBlock->GetBoardFile().IsEmpty() )
437 {
438 // The new Board file name is based on the design block name, not the source sheet name
439 wxString dbBoardFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
441
442 // If the source and destination files are the same, then we don't need to copy the file
443 // as we are just updating the metadata
444 if( boardFile.GetFullPath() != dbBoardFile )
445 {
446 // Copy the source sheet file to the design block folder, under the design block name
447 if( !wxCopyFile( boardFile.GetFullPath(), dbBoardFile ) )
448 {
449 THROW_IO_ERROR( wxString::Format( _( "Board file '%s' could not be saved as design block at '%s'." ),
450 boardFile.GetFullPath(), dbBoardFile ) );
451 }
452 }
453 }
454
455 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
456 + wxT( "." ) + FILEEXT::JsonFileExtension;
457
458 // Write the metadata file
459 nlohmann::ordered_json dbMetadata;
460 dbMetadata["description"] = aDesignBlock->GetLibDescription();
461 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
462 dbMetadata["fields"] = aDesignBlock->GetFields();
463
464 bool success = false;
465
466 try
467 {
468 wxFFile mdFile( dbMetadataFile, wxT( "wb" ) );
469
470 if( mdFile.IsOpened() )
471 success = mdFile.Write( dbMetadata.dump( 0 ) );
472
473 // wxFFile dtor will close the file
474 }
475 catch( ... )
476 {
477 success = false;
478 }
479
480 if( !success )
481 {
482 THROW_IO_ERROR( wxString::Format(
483 _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile ) );
484 }
485}
486
487
488void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
489 const std::map<std::string, UTF8>* aProperties )
490{
491 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
493
494 if( !dbDir.DirExists() )
495 {
497 wxString::Format( _( "Design block '%s' does not exist." ), dbDir.GetFullName() ) );
498 }
499
500 // Delete the whole design block folder
501 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
502 {
503 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be deleted." ),
504 dbDir.GetFullPath().GetData() ) );
505 }
506}
507
508
509bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
510{
511 wxFileName path( aLibraryPath );
512 return path.IsOk() && path.IsDirWritable();
513}
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)
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
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:103
#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.