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 <wx/dir.h>
28#include <wx/ffile.h>
29#include <wx/filename.h>
30#include <wx/log.h>
31#include <wx/translation.h>
32#include <wx/string.h>
33#include <wx/arrstr.h>
34#include <wx/datetime.h>
36#include <kiway_player.h>
37#include <design_block_io.h>
38#include <design_block.h>
39#include <ki_exception.h>
40#include <trace_helpers.h>
41#include <fstream>
44
46{
47 switch( aFileType )
48 {
49 case KICAD_SEXP: return _( "KiCad" );
51 default: return wxString::Format( _( "UNKNOWN (%d)" ), aFileType );
52 }
53}
54
55
57DESIGN_BLOCK_IO_MGR::EnumFromStr( const wxString& aFileType )
58{
59 if( aFileType == _( "KiCad" ) )
61 else if( aFileType == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
63
65}
66
67
69{
70 switch( aFileType )
71 {
72 case KICAD_SEXP: return new DESIGN_BLOCK_IO();
73 default: return nullptr;
74 }
75}
76
77
79DESIGN_BLOCK_IO_MGR::GuessPluginTypeFromLibPath( const wxString& aLibPath, int aCtl )
80{
82
83 if( parser.Parse( aLibPath.ToStdString() ).has_value() )
84 return NESTED_TABLE;
85
86 if( IO_RELEASER<DESIGN_BLOCK_IO>( FindPlugin( KICAD_SEXP ) )->CanReadLibrary( aLibPath )
87 && aCtl != KICTL_NONKICAD_ONLY )
88 {
89 return KICAD_SEXP;
90 }
91
93}
94
95
96bool DESIGN_BLOCK_IO_MGR::ConvertLibrary( std::map<std::string, UTF8>* aOldFileProps,
97 const wxString& aOldFilePath,
98 const wxString& aNewFilePath )
99{
102
103 if( oldFileType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
104 return false;
105
106
109 wxArrayString dbNames;
110 wxFileName newFileName( aNewFilePath );
111
112 if( newFileName.HasExt() )
113 {
114 wxString extraDir = newFileName.GetFullName();
115 newFileName.ClearExt();
116 newFileName.SetName( "" );
117 newFileName.AppendDir( extraDir );
118 }
119
120 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
121 return false;
122
123 try
124 {
125 bool bestEfforts = false; // throw on first error
126 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
127
128 for( const wxString& dbName : dbNames )
129 {
130 std::unique_ptr<const DESIGN_BLOCK> db( oldFilePI->GetEnumeratedDesignBlock( aOldFilePath, dbName,
131 aOldFileProps ) );
132 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
133 }
134 }
135 catch( ... )
136 {
137 return false;
138 }
139
140 return true;
141}
142
143
145{
146 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
148}
149
150
151long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
152{
153 wxDir libDir( aLibraryPath );
154
155 if( !libDir.IsOpened() )
156 return 0;
157
158 long long ts = 0;
159
160 wxString filename;
161 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
162
163 while( hasMoreFiles )
164 {
165 wxFileName blockDir( aLibraryPath, filename );
166
167 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
168 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
169 ts += TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
170
171 hasMoreFiles = libDir.GetNext( &filename );
172 }
173
174 return ts;
175}
176
177
178void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
179 const std::map<std::string, UTF8>* aProperties )
180{
181 if( wxDir::Exists( aLibraryPath ) )
182 {
183 THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path '%s'." ),
184 aLibraryPath.GetData() ) );
185 }
186
187 wxFileName dir;
188 dir.SetPath( aLibraryPath );
189
190 if( !dir.Mkdir() )
191 {
193 wxString::Format( _( "Library path '%s' could not be created.\n\n"
194 "Make sure you have write permissions and try again." ),
195 dir.GetPath() ) );
196 }
197}
198
199
200bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
201 const std::map<std::string, UTF8>* aProperties )
202{
203 wxFileName fn;
204 fn.SetPath( aLibraryPath );
205
206 // Return if there is no library path to delete.
207 if( !fn.DirExists() )
208 return false;
209
210 if( !fn.IsDirWritable() )
211 {
212 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete folder '%s'." ),
213 aLibraryPath.GetData() ) );
214 }
215
216 wxDir dir( aLibraryPath );
217
218 // Design block folders should only contain sub-folders for each design block
219 if( dir.HasFiles() )
220 {
221 THROW_IO_ERROR( wxString::Format( _( "Library folder '%s' has unexpected files." ),
222 aLibraryPath.GetData() ) );
223 }
224
225 // Must delete all sub-directories before deleting the library directory
226 if( dir.HasSubDirs() )
227 {
228 wxArrayString dirs;
229
230 // Get all sub-directories in the library path
231 dir.GetAllFiles( aLibraryPath, &dirs, wxEmptyString, wxDIR_DIRS );
232
233 for( size_t i = 0; i < dirs.GetCount(); i++ )
234 {
235 wxFileName tmp = dirs[i];
236
238 {
239 THROW_IO_ERROR( wxString::Format( _( "Unexpected folder '%s' found in library path '%s'." ),
240 dirs[i].GetData(), aLibraryPath.GetData() ) );
241 }
242 }
243
244 for( size_t i = 0; i < dirs.GetCount(); i++ )
245 wxRemoveFile( dirs[i] );
246 }
247
248 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ),
249 aLibraryPath.GetData() );
250
251 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
252 // we don't want that. we want bare metal portability with no UI here.
253 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
254 {
255 THROW_IO_ERROR( wxString::Format( _( "Design block library '%s' cannot be deleted." ),
256 aLibraryPath.GetData() ) );
257 }
258
259 // For some reason removing a directory in Windows is not immediately updated. This delay
260 // prevents an error when attempting to immediately recreate the same directory when over
261 // writing an existing library.
262#ifdef __WINDOWS__
263 wxMilliSleep( 250L );
264#endif
265
266 return true;
267}
268
269
270void DESIGN_BLOCK_IO::DesignBlockEnumerate( wxArrayString& aDesignBlockNames,
271 const wxString& aLibraryPath, bool aBestEfforts,
272 const std::map<std::string, UTF8>* aProperties )
273{
274 // From the starting directory, look for all directories ending in the .kicad_block extension
275 wxDir dir( aLibraryPath );
276
277 if( !dir.IsOpened() )
278 {
279 THROW_IO_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), aLibraryPath ) );
280 }
281
282 wxString dirname;
283 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadDesignBlockPathExtension );
284 bool cont = dir.GetFirst( &dirname, fileSpec, wxDIR_DIRS );
285
286 while( cont )
287 {
288 aDesignBlockNames.Add( dirname.Before( wxT( '.' ) ) );
289 cont = dir.GetNext( &dirname );
290 }
291}
292
293
294DESIGN_BLOCK* DESIGN_BLOCK_IO::DesignBlockLoad( const wxString& aLibraryPath,
295 const wxString& aDesignBlockName, bool aKeepUUID,
296 const std::map<std::string, UTF8>* aProperties )
297{
298 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
299 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
300 wxString dbSchPath = dbPath + aDesignBlockName + wxT( "." )
302 wxString dbPcbPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::KiCadPcbFileExtension;
303 wxString dbMetadataPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::JsonFileExtension;
304
305 if( !wxDir::Exists( dbPath ) )
306 THROW_IO_ERROR( wxString::Format( _( "Design block '%s' does not exist." ), dbPath ) );
307
308 DESIGN_BLOCK* newDB = new DESIGN_BLOCK();
309
310 // Library name needs to be empty for when we fill it in with the correct library nickname
311 // one layer above
312 newDB->SetLibId( LIB_ID( wxEmptyString, aDesignBlockName ) );
313
314 if( wxFileExists( dbSchPath ) )
315 newDB->SetSchematicFile( dbSchPath );
316
317 if( wxFileExists( dbPcbPath ) )
318 newDB->SetBoardFile( dbPcbPath );
319
320 // Parse the JSON file if it exists
321 if( wxFileExists( dbMetadataPath ) )
322 {
323 try
324 {
325 nlohmann::ordered_json dbMetadata;
326 std::ifstream dbMetadataFile( dbMetadataPath.fn_str() );
327
328 dbMetadataFile >> dbMetadata;
329
330 if( dbMetadata.contains( "description" ) )
331 newDB->SetLibDescription( dbMetadata["description"] );
332
333 if( dbMetadata.contains( "keywords" ) )
334 newDB->SetKeywords( dbMetadata["keywords"] );
335
336 // Read the "fields" object from the JSON
337 if( dbMetadata.contains( "fields" ) )
338 {
339 for( auto& item : dbMetadata["fields"].items() )
340 {
341 wxString name = wxString::FromUTF8( item.key() );
342 wxString value = wxString::FromUTF8( item.value().get<std::string>() );
343
344 newDB->GetFields()[name] = value;
345 }
346 }
347 }
348 catch( ... )
349 {
350 delete newDB;
351 THROW_IO_ERROR( wxString::Format( _( "Design block metadata file '%s' could not be read." ),
352 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 {
378 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
379 }
380
381 if( aDesignBlock->GetSchematicFile().IsEmpty() && aDesignBlock->GetBoardFile().IsEmpty() )
382 {
383 THROW_IO_ERROR( _( "Design block does not have a schematic or board file." ) );
384 }
385
386 wxFileName schematicFile( aDesignBlock->GetSchematicFile() );
387 wxFileName boardFile( aDesignBlock->GetBoardFile() );
388
389 if( !aDesignBlock->GetSchematicFile().IsEmpty() && !schematicFile.FileExists() )
390 {
392 wxString::Format( _( "Schematic source file '%s' does not exist." ), schematicFile.GetFullPath() ) );
393 }
394
395 if( !aDesignBlock->GetBoardFile().IsEmpty() && !boardFile.FileExists() )
396 {
397 THROW_IO_ERROR( wxString::Format( _( "Board source file '%s' does not exist." ), boardFile.GetFullPath() ) );
398 }
399
400 // Create the design block folder
401 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
402 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
404 + wxFileName::GetPathSeparator() );
405
406 if( !dbFolder.DirExists() )
407 {
408 if( !dbFolder.Mkdir() )
409 {
410 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be created." ),
411 dbFolder.GetFullPath().GetData() ) );
412 }
413 }
414
415 if( !aDesignBlock->GetSchematicFile().IsEmpty() )
416 {
417 // The new schematic file name is based on the design block name, not the source sheet name
418 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
420
421 // If the source and destination files are the same, then we don't need to copy the file
422 // as we are just updating the metadata
423 if( schematicFile.GetFullPath() != dbSchematicFile )
424 {
425 // Copy the source sheet file to the design block folder, under the design block name
426 if( !wxCopyFile( schematicFile.GetFullPath(), dbSchematicFile ) )
427 {
429 wxString::Format( _( "Schematic file '%s' could not be saved as design block at '%s'." ),
430 schematicFile.GetFullPath(), dbSchematicFile ) );
431 }
432 }
433 }
434
435 if( !aDesignBlock->GetBoardFile().IsEmpty() )
436 {
437 // The new Board file name is based on the design block name, not the source sheet name
438 wxString dbBoardFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
440
441 // If the source and destination files are the same, then we don't need to copy the file
442 // as we are just updating the metadata
443 if( boardFile.GetFullPath() != dbBoardFile )
444 {
445 // Copy the source sheet file to the design block folder, under the design block name
446 if( !wxCopyFile( boardFile.GetFullPath(), dbBoardFile ) )
447 {
448 THROW_IO_ERROR( wxString::Format( _( "Board file '%s' could not be saved as design block at '%s'." ),
449 boardFile.GetFullPath(), dbBoardFile ) );
450 }
451 }
452 }
453
454 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
455 + wxT( "." ) + FILEEXT::JsonFileExtension;
456
457 // Write the metadata file
458 nlohmann::ordered_json dbMetadata;
459 dbMetadata["description"] = aDesignBlock->GetLibDescription();
460 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
461 dbMetadata["fields"] = aDesignBlock->GetFields();
462
463 bool success = false;
464
465 try
466 {
467 wxFFile mdFile( dbMetadataFile, wxT( "wb" ) );
468
469 if( mdFile.IsOpened() )
470 success = mdFile.Write( dbMetadata.dump( 0 ) );
471
472 // wxFFile dtor will close the file
473 }
474 catch( ... )
475 {
476 success = false;
477 }
478
479 if( !success )
480 {
481 THROW_IO_ERROR( wxString::Format(
482 _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile ) );
483 }
484}
485
486
487void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
488 const std::map<std::string, UTF8>* aProperties )
489{
490 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
492
493 if( !dbDir.DirExists() )
494 {
496 wxString::Format( _( "Design block '%s' does not exist." ), dbDir.GetFullName() ) );
497 }
498
499 // Delete the whole design block folder
500 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
501 {
502 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be deleted." ),
503 dbDir.GetFullPath().GetData() ) );
504 }
505}
506
507
508bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
509{
510 wxFileName path( aLibraryPath );
511 return path.IsOk() && path.IsDirWritable();
512}
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
long long TimestampDir(const wxString &aDirPath, const wxString &aFilespec)
A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function private to src/common/...
Definition common.cpp:630
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
#define _HKI(x)
Definition page_info.cpp:44
Container that describes file type info.
Definition io_base.h:45
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.