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>
42
44{
45 switch( aFileType )
46 {
47 case KICAD_SEXP: return _( "KiCad" );
48 default: return wxString::Format( _( "UNKNOWN (%d)" ), aFileType );
49 }
50}
51
52
54DESIGN_BLOCK_IO_MGR::EnumFromStr( const wxString& aFileType )
55{
56 if( aFileType == _( "KiCad" ) )
58
60}
61
62
64{
65 switch( aFileType )
66 {
67 case KICAD_SEXP: return new DESIGN_BLOCK_IO();
68 default: return nullptr;
69 }
70}
71
72
74DESIGN_BLOCK_IO_MGR::GuessPluginTypeFromLibPath( const wxString& aLibPath, int aCtl )
75{
76 if( IO_RELEASER<DESIGN_BLOCK_IO>( FindPlugin( KICAD_SEXP ) )->CanReadLibrary( aLibPath )
77 && aCtl != KICTL_NONKICAD_ONLY )
78 return KICAD_SEXP;
79
81}
82
83
84bool DESIGN_BLOCK_IO_MGR::ConvertLibrary( std::map<std::string, UTF8>* aOldFileProps,
85 const wxString& aOldFilePath,
86 const wxString& aNewFilePath )
87{
90
91 if( oldFileType == DESIGN_BLOCK_IO_MGR::FILE_TYPE_NONE )
92 return false;
93
94
98 wxArrayString dbNames;
99 wxFileName newFileName( aNewFilePath );
100
101 if( newFileName.HasExt() )
102 {
103 wxString extraDir = newFileName.GetFullName();
104 newFileName.ClearExt();
105 newFileName.SetName( "" );
106 newFileName.AppendDir( extraDir );
107 }
108
109 if( !newFileName.DirExists() && !wxFileName::Mkdir( aNewFilePath, wxS_DIR_DEFAULT ) )
110 return false;
111
112 try
113 {
114 bool bestEfforts = false; // throw on first error
115 oldFilePI->DesignBlockEnumerate( dbNames, aOldFilePath, bestEfforts, aOldFileProps );
116
117 for( const wxString& dbName : dbNames )
118 {
119 std::unique_ptr<const DESIGN_BLOCK> db(
120 oldFilePI->GetEnumeratedDesignBlock( aOldFilePath, dbName, aOldFileProps ) );
121 kicadPI->DesignBlockSave( aNewFilePath, db.get() );
122 }
123 }
124 catch( ... )
125 {
126 return false;
127 }
128
129 return true;
130}
131
132
134{
135 return IO_BASE::IO_FILE_DESC( _HKI( "KiCad Design Block folders" ), {},
137}
138
139
140long long DESIGN_BLOCK_IO::GetLibraryTimestamp( const wxString& aLibraryPath ) const
141{
142 wxDir libDir( aLibraryPath );
143
144 if( !libDir.IsOpened() )
145 return 0;
146
147 long long ts = 0;
148
149 wxString filename;
150 bool hasMoreFiles = libDir.GetFirst( &filename, wxEmptyString, wxDIR_DIRS );
151
152 while( hasMoreFiles )
153 {
154 wxFileName blockDir( aLibraryPath, filename );
155
156 // Check if the directory ends with ".kicad_block", if so hash all the files in it.
157 if( blockDir.GetFullName().EndsWith( FILEEXT::KiCadDesignBlockPathExtension ) )
158 ts += TimestampDir( blockDir.GetFullPath(), wxT( "*" ) );
159
160 hasMoreFiles = libDir.GetNext( &filename );
161 }
162
163 return ts;
164}
165
166
167void DESIGN_BLOCK_IO::CreateLibrary( const wxString& aLibraryPath,
168 const std::map<std::string, UTF8>* aProperties )
169{
170 if( wxDir::Exists( aLibraryPath ) )
171 {
172 THROW_IO_ERROR( wxString::Format( _( "Cannot overwrite library path '%s'." ),
173 aLibraryPath.GetData() ) );
174 }
175
176 wxFileName dir;
177 dir.SetPath( aLibraryPath );
178
179 if( !dir.Mkdir() )
180 {
182 wxString::Format( _( "Library path '%s' could not be created.\n\n"
183 "Make sure you have write permissions and try again." ),
184 dir.GetPath() ) );
185 }
186}
187
188
189bool DESIGN_BLOCK_IO::DeleteLibrary( const wxString& aLibraryPath,
190 const std::map<std::string, UTF8>* aProperties )
191{
192 wxFileName fn;
193 fn.SetPath( aLibraryPath );
194
195 // Return if there is no library path to delete.
196 if( !fn.DirExists() )
197 return false;
198
199 if( !fn.IsDirWritable() )
200 {
201 THROW_IO_ERROR( wxString::Format( _( "Insufficient permissions to delete folder '%s'." ),
202 aLibraryPath.GetData() ) );
203 }
204
205 wxDir dir( aLibraryPath );
206
207 // Design block folders should only contain sub-folders for each design block
208 if( dir.HasFiles() )
209 {
210 THROW_IO_ERROR( wxString::Format( _( "Library folder '%s' has unexpected files." ),
211 aLibraryPath.GetData() ) );
212 }
213
214 // Must delete all sub-directories before deleting the library directory
215 if( dir.HasSubDirs() )
216 {
217 wxArrayString dirs;
218
219 // Get all sub-directories in the library path
220 dir.GetAllFiles( aLibraryPath, &dirs, wxEmptyString, wxDIR_DIRS );
221
222 for( size_t i = 0; i < dirs.GetCount(); i++ )
223 {
224 wxFileName tmp = dirs[i];
225
227 {
228 THROW_IO_ERROR( wxString::Format( _( "Unexpected folder '%s' found in library "
229 "path '%s'." ),
230 dirs[i].GetData(), aLibraryPath.GetData() ) );
231 }
232 }
233
234 for( size_t i = 0; i < dirs.GetCount(); i++ )
235 wxRemoveFile( dirs[i] );
236 }
237
238 wxLogTrace( traceDesignBlocks, wxT( "Removing design block library '%s'." ),
239 aLibraryPath.GetData() );
240
241 // Some of the more elaborate wxRemoveFile() crap puts up its own wxLog dialog
242 // we don't want that. we want bare metal portability with no UI here.
243 if( !wxFileName::Rmdir( aLibraryPath, wxPATH_RMDIR_RECURSIVE ) )
244 {
245 THROW_IO_ERROR( wxString::Format( _( "Design block library '%s' cannot be deleted." ),
246 aLibraryPath.GetData() ) );
247 }
248
249 // For some reason removing a directory in Windows is not immediately updated. This delay
250 // prevents an error when attempting to immediately recreate the same directory when over
251 // writing an existing library.
252#ifdef __WINDOWS__
253 wxMilliSleep( 250L );
254#endif
255
256 return true;
257}
258
259
260void DESIGN_BLOCK_IO::DesignBlockEnumerate( wxArrayString& aDesignBlockNames,
261 const wxString& aLibraryPath, bool aBestEfforts,
262 const std::map<std::string, UTF8>* aProperties )
263{
264 // From the starting directory, look for all directories ending in the .kicad_block extension
265 wxDir dir( aLibraryPath );
266
267 if( !dir.IsOpened() )
268 return;
269
270 wxString dirname;
271 wxString fileSpec = wxT( "*." ) + wxString( FILEEXT::KiCadDesignBlockPathExtension );
272 bool cont = dir.GetFirst( &dirname, fileSpec, wxDIR_DIRS );
273
274 while( cont )
275 {
276 aDesignBlockNames.Add( dirname.Before( wxT( '.' ) ) );
277 cont = dir.GetNext( &dirname );
278 }
279}
280
281
282DESIGN_BLOCK* DESIGN_BLOCK_IO::DesignBlockLoad( const wxString& aLibraryPath,
283 const wxString& aDesignBlockName, bool aKeepUUID,
284 const std::map<std::string, UTF8>* aProperties )
285{
286 wxString dbPath = aLibraryPath + wxFileName::GetPathSeparator() + aDesignBlockName + wxT( "." )
287 + FILEEXT::KiCadDesignBlockPathExtension + wxFileName::GetPathSeparator();
288 wxString dbSchPath = dbPath + aDesignBlockName + wxT( "." )
290 wxString dbMetadataPath = dbPath + aDesignBlockName + wxT( "." ) + FILEEXT::JsonFileExtension;
291
292 if( !wxFileExists( dbSchPath ) )
293 return nullptr;
294
295 DESIGN_BLOCK* newDB = new DESIGN_BLOCK();
296
297 // Library name needs to be empty for when we fill it in with the correct library nickname
298 // one layer above
299 newDB->SetLibId( LIB_ID( wxEmptyString, aDesignBlockName ) );
300 newDB->SetSchematicFile( dbSchPath );
301
302 // Parse the JSON file if it exists
303 if( wxFileExists( dbMetadataPath ) )
304 {
305 try
306 {
307 nlohmann::ordered_json dbMetadata;
308 std::ifstream dbMetadataFile( dbMetadataPath.fn_str() );
309
310 dbMetadataFile >> dbMetadata;
311
312 if( dbMetadata.contains( "description" ) )
313 newDB->SetLibDescription( dbMetadata["description"] );
314
315 if( dbMetadata.contains( "keywords" ) )
316 newDB->SetKeywords( dbMetadata["keywords"] );
317
318 nlohmann::ordered_map<wxString, wxString> fields;
319
320 // Read the "fields" object from the JSON
321 if( dbMetadata.contains( "fields" ) )
322 {
323 for( auto& item : dbMetadata["fields"].items() )
324 {
325 wxString name = wxString::FromUTF8( item.key() );
326 wxString value = wxString::FromUTF8( item.value().get<std::string>() );
327
328 fields[name] = value;
329 }
330
331 newDB->SetFields( fields );
332 }
333 }
334 catch( ... )
335 {
336 THROW_IO_ERROR( wxString::Format(
337 _( "Design block metadata file '%s' could not be read." ), dbMetadataPath ) );
338 }
339 }
340
341
342 return newDB;
343}
344
345
346void DESIGN_BLOCK_IO::DesignBlockSave( const wxString& aLibraryPath,
347 const DESIGN_BLOCK* aDesignBlock,
348 const std::map<std::string, UTF8>* aProperties )
349{
350 // Make sure we have a valid LIB_ID or we can't save the design block
351 if( !aDesignBlock->GetLibId().IsValid() )
352 {
353 THROW_IO_ERROR( _( "Design block does not have a valid library ID." ) );
354 }
355
356 if( !wxFileExists( aDesignBlock->GetSchematicFile() ) )
357 {
358 THROW_IO_ERROR( wxString::Format( _( "Schematic source file '%s' does not exist." ),
359 aDesignBlock->GetSchematicFile() ) );
360 }
361
362 // Create the design block folder
363 wxFileName dbFolder( aLibraryPath + wxFileName::GetPathSeparator()
364 + aDesignBlock->GetLibId().GetLibItemName() + wxT( "." )
366 + wxFileName::GetPathSeparator() );
367
368 if( !dbFolder.DirExists() )
369 {
370 if( !dbFolder.Mkdir() )
371 {
372 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be created." ),
373 dbFolder.GetFullPath().GetData() ) );
374 }
375 }
376
377 // The new schematic file name is based on the design block name, not the source sheet name
378 wxString dbSchematicFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
380
381 // If the source and destination files are the same, then we don't need to copy the file
382 // as we are just updating the metadata
383 if( aDesignBlock->GetSchematicFile() != dbSchematicFile )
384 {
385 // Copy the source sheet file to the design block folder, under the design block name
386 if( !wxCopyFile( aDesignBlock->GetSchematicFile(), dbSchematicFile ) )
387 {
388 THROW_IO_ERROR( wxString::Format(
389 _( "Schematic file '%s' could not be saved as design block at '%s'." ),
390 aDesignBlock->GetSchematicFile().GetData(), dbSchematicFile ) );
391 }
392 }
393
394
395 wxString dbMetadataFile = dbFolder.GetFullPath() + aDesignBlock->GetLibId().GetLibItemName()
396 + wxT( "." ) + FILEEXT::JsonFileExtension;
397
398 // Write the metadata file
399 nlohmann::ordered_json dbMetadata;
400 dbMetadata["description"] = aDesignBlock->GetLibDescription();
401 dbMetadata["keywords"] = aDesignBlock->GetKeywords();
402 dbMetadata["fields"] = aDesignBlock->GetFields();
403
404 bool success = false;
405
406 try
407 {
408 wxFFile mdFile( dbMetadataFile, wxT( "wb" ) );
409
410 if( mdFile.IsOpened() )
411 success = mdFile.Write( dbMetadata.dump( 0 ) );
412
413 // wxFFile dtor will close the file
414 }
415 catch( ... )
416 {
417 success = false;
418 }
419
420 if( !success )
421 {
422 THROW_IO_ERROR( wxString::Format(
423 _( "Design block metadata file '%s' could not be saved." ), dbMetadataFile ) );
424 }
425}
426
427
428void DESIGN_BLOCK_IO::DesignBlockDelete( const wxString& aLibPath, const wxString& aDesignBlockName,
429 const std::map<std::string, UTF8>* aProperties )
430{
431 wxFileName dbDir = wxFileName( aLibPath + wxFileName::GetPathSeparator() + aDesignBlockName
433
434 if( !dbDir.DirExists() )
435 {
437 wxString::Format( _( "Design block '%s' does not exist." ), dbDir.GetFullName() ) );
438 }
439
440 // Delete the whole design block folder
441 if( !wxFileName::Rmdir( dbDir.GetFullPath(), wxPATH_RMDIR_RECURSIVE ) )
442 {
443 THROW_IO_ERROR( wxString::Format( _( "Design block folder '%s' could not be deleted." ),
444 dbDir.GetFullPath().GetData() ) );
445 }
446}
447
448
449bool DESIGN_BLOCK_IO::IsLibraryWritable( const wxString& aLibraryPath )
450{
451 wxFileName path( aLibraryPath );
452 return path.IsOk() && path.IsDirWritable();
453}
const char * name
Definition: DXF_plotter.cpp:59
@ 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)
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)
Definition: design_block.h:36
void SetKeywords(const wxString &aKeywords)
Definition: design_block.h:39
void SetSchematicFile(const wxString &aFile)
Definition: design_block.h:42
const wxString & GetKeywords() const
Definition: design_block.h:38
const wxString & GetLibDescription() const
Definition: design_block.h:35
void SetLibId(const LIB_ID &aName)
Definition: design_block.h:32
const wxString & GetSchematicFile() const
Definition: design_block.h:41
void SetFields(nlohmann::ordered_map< wxString, wxString > &aFields)
Definition: design_block.h:44
const LIB_ID & GetLibId() const
Definition: design_block.h:33
const nlohmann::ordered_map< wxString, wxString > & GetFields() const
Definition: design_block.h:49
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:600
The common library.
#define _HKI(x)
#define _(s)
static const std::string KiCadDesignBlockLibPathExtension
static const std::string KiCadDesignBlockPathExtension
static const std::string JsonFileExtension
static const std::string KiCadSchematicFileExtension
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)
Definition: ki_exception.h:39
#define KICTL_NONKICAD_ONLY
chosen file is non-KiCad according to user
Definition: kiway_player.h:74
Container that describes file type info.
Definition: io_base.h:43
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.