KiCad PCB EDA Suite
Loading...
Searching...
No Matches
embedded_files.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
14 * Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include "embedded_files.h"
22
23#include <wx/base64.h>
24#include <wx/debug.h>
25#include <wx/filename.h>
26#include <wx/log.h>
27#include <wx/mstream.h>
28#include <wx/wfstream.h>
29
30#include <map>
31#include <memory>
32#include <sstream>
33
34#include <zstd.h>
35
36#include <kiid.h>
37#include <mmh3_hash.h>
38#include <paths.h>
39#include <picosha2.h>
41
42
44{
46 hash.add( decompressedData );
47
48 is_valid = ( hash.digest().ToString() == data_hash );
49 return is_valid;
50}
51
52
54{
55 std::string new_sha;
56 picosha2::hash256_hex_string( decompressedData, new_sha );
57
58 is_valid = ( new_sha == data_hash );
59 return is_valid;
60}
61
62
64{
65 return wxString::Format( "%s://%s", FILEEXT::KiCadUriPrefix, name );
66}
67
68
69EMBEDDED_FILES::EMBEDDED_FILE* EMBEDDED_FILES::AddFile( const wxFileName& aName, bool aOverwrite )
70{
71 if( HasFile( aName.GetFullName() ) )
72 {
73 if( !aOverwrite )
74 return m_files[aName.GetFullName()].get();
75
76 m_files.erase( aName.GetFullName() );
77 }
78
79 wxFFileInputStream file( aName.GetFullPath() );
80 wxMemoryBuffer buffer;
81
82 if( !file.IsOk() )
83 return nullptr;
84
85 wxFileOffset length = file.GetLength();
86
87 std::shared_ptr<EMBEDDED_FILE> efile = std::make_shared<EMBEDDED_FILE>();
88 efile->name = aName.GetFullName();
89 efile->decompressedData.resize( length );
90
91 wxString ext = aName.GetExt().Upper();
92
93 // Handle some common file extensions
94 if( ext == "STP" || ext == "STPZ" || ext == "STEP" || ext == "WRL" || ext == "WRZ" )
95 {
97 }
98 else if( ext == "WOFF" || ext == "WOFF2" || ext == "TTF" || ext == "OTF" )
99 {
100 efile->type = EMBEDDED_FILE::FILE_TYPE::FONT;
101 }
102 else if( ext == "PDF" )
103 {
105 }
106 else if( ext == "KICAD_WKS" )
107 {
109 }
110
111 if( !efile->decompressedData.data() )
112 return nullptr;
113
114 char* data = efile->decompressedData.data();
115 wxFileOffset total_read = 0;
116
117 while( !file.Eof() && total_read < length )
118 {
119 file.Read( data, length - total_read );
120
121 size_t read = file.LastRead();
122 data += read;
123 total_read += read;
124 }
125
126 if( CompressAndEncode( *efile ) != RETURN_CODE::OK )
127 return nullptr;
128
129 efile->is_valid = true;
130
131 EMBEDDED_FILE* result = efile.get();
132 m_files[aName.GetFullName()] = std::move( efile );
133
136
137 return result;
138}
139
140
142{
143 AddFile( std::shared_ptr<EMBEDDED_FILE>( aFile ) );
144}
145
146
147void EMBEDDED_FILES::AddFile( std::shared_ptr<EMBEDDED_FILE> aFile )
148{
149 if( !aFile )
150 return;
151
152 wxString name = aFile->name;
153 auto [it, inserted] = m_files.emplace( std::move( name ), std::move( aFile ) );
154
155 // Fire the callback only when the file was actually inserted; std::map::emplace silently
156 // drops duplicates and we must not announce a stored pointer that no longer matches what
157 // the collection holds.
158 if( inserted && m_fileAddedCallback )
159 m_fileAddedCallback( it->second.get() );
160}
161
162
163// Remove a file from the collection
164void EMBEDDED_FILES::RemoveFile( const wxString& name, bool aErase )
165{
166 // aErase is retained for API compatibility; with shared_ptr ownership the map entry
167 // release will free the underlying file when no other collection still references it.
168 (void) aErase;
169
170 auto it = m_files.find( name );
171
172 if( it != m_files.end() )
173 m_files.erase( it );
174}
175
176
178{
179 for( auto it = m_files.begin(); it != m_files.end(); )
180 {
181 if( it->second->type == EMBEDDED_FILE::FILE_TYPE::FONT )
182 it = m_files.erase( it );
183 else
184 ++it;
185 }
186}
187
188
189// Write the collection of files to a disk file in the specified format
190void EMBEDDED_FILES::WriteEmbeddedFiles( OUTPUTFORMATTER& aOut, bool aWriteData ) const
191{
192 ssize_t MIME_BASE64_LENGTH = 76;
193 aOut.Print( "(embedded_files " );
194
195 for( const auto& [name, entry] : m_files )
196 {
197 const EMBEDDED_FILE& file = *entry;
198
199 // Skip empty files
200 if( file.compressedEncodedData.empty() )
201 {
202 continue;
203 }
204
205 aOut.Print( "(file " );
206 aOut.Print( "(name %s)", aOut.Quotew( file.name ).c_str() );
207
208 const char* type = nullptr;
209
210 switch( file.type )
211 {
212 case EMBEDDED_FILE::FILE_TYPE::DATASHEET: type = "datasheet"; break;
213 case EMBEDDED_FILE::FILE_TYPE::FONT: type = "font"; break;
214 case EMBEDDED_FILE::FILE_TYPE::MODEL: type = "model"; break;
215 case EMBEDDED_FILE::FILE_TYPE::WORKSHEET: type = "worksheet"; break;
216 default: type = "other"; break;
217 }
218
219 aOut.Print( "(type %s)", type );
220
221 if( aWriteData )
222 {
223 aOut.Print( "(data" );
224
225 size_t first = 0;
226
227 while( first < file.compressedEncodedData.length() )
228 {
229 ssize_t remaining = file.compressedEncodedData.length() - first;
230 int length = std::min( remaining, MIME_BASE64_LENGTH );
231
232 std::string_view view( file.compressedEncodedData.data() + first, length );
233
234 aOut.Print( "\n%1s%.*s%s\n", first ? "" : "|", length, view.data(),
235 remaining == length ? "|" : "" );
236 first += MIME_BASE64_LENGTH;
237 }
238
239 aOut.Print( ")" ); // Close data
240 }
241
242 aOut.Print( "(checksum %s)", aOut.Quotew( file.data_hash ).c_str() );
243 aOut.Print( ")" ); // Close file
244 }
245
246 aOut.Print( ")" ); // Close embedded_files
247}
248
249
250// Compress and Base64 encode data
252{
253 std::vector<char> compressedData;
254 size_t estCompressedSize = ZSTD_compressBound( aFile.decompressedData.size() );
255 compressedData.resize( estCompressedSize );
256 size_t compressedSize = ZSTD_compress( compressedData.data(), estCompressedSize,
257 aFile.decompressedData.data(),
258 aFile.decompressedData.size(), 15 );
259
260 if( ZSTD_isError( compressedSize ) )
261 {
262 compressedData.clear();
264 }
265
266 const size_t dstLen = wxBase64EncodedSize( compressedSize );
267 aFile.compressedEncodedData.resize( dstLen );
268 size_t retval = wxBase64Encode( aFile.compressedEncodedData.data(), dstLen,
269 compressedData.data(), compressedSize );
270
271 if( retval != dstLen )
272 {
273 aFile.compressedEncodedData.clear();
275 }
276
278 hash.add( aFile.decompressedData );
279 aFile.data_hash = hash.digest().ToString();
280
281 return RETURN_CODE::OK;
282}
283
284
285// Decompress and Base64 decode data
287{
288 std::vector<char> compressedData;
289 size_t compressedSize = wxBase64DecodedSize( aFile.compressedEncodedData.size() );
290
291 if( compressedSize == 0 )
292 {
293 wxLogTrace( wxT( "KICAD_EMBED" ),
294 wxT( "%s:%s:%d\n * Base64DecodedSize failed for file '%s' with size %zu" ),
295 __FILE__, __FUNCTION__, __LINE__, aFile.name,
296 aFile.compressedEncodedData.size() );
298 }
299
300 compressedData.resize( compressedSize );
301 void* compressed = compressedData.data();
302
303 // The return value from wxBase64Decode is the actual size of the decoded data avoiding
304 // the modulo 4 padding of the base64 encoding
305 compressedSize = wxBase64Decode( compressed, compressedSize, aFile.compressedEncodedData );
306
307 unsigned long long estDecompressedSize = ZSTD_getFrameContentSize( compressed, compressedSize );
308
309 if( estDecompressedSize > 1e9 ) // Limit to 1GB
311
312 if( estDecompressedSize == ZSTD_CONTENTSIZE_ERROR
313 || estDecompressedSize == ZSTD_CONTENTSIZE_UNKNOWN )
314 {
316 }
317
318 aFile.decompressedData.resize( estDecompressedSize );
319 void* decompressed = aFile.decompressedData.data();
320
321 size_t decompressedSize = ZSTD_decompress( decompressed, estDecompressedSize,
322 compressed, compressedSize );
323
324 if( ZSTD_isError( decompressedSize ) )
325 {
326 wxLogTrace( wxT( "KICAD_EMBED" ),
327 wxT( "%s:%s:%d\n * ZSTD_decompress failed with error '%s'" ),
328 __FILE__, __FUNCTION__, __LINE__, ZSTD_getErrorName( decompressedSize ) );
329 aFile.decompressedData.clear();
331 }
332
333 aFile.decompressedData.resize( decompressedSize );
334
336 hash.add( aFile.decompressedData );
337 std::string new_hash = hash.digest().ToString();
338
339 if( aFile.data_hash.length() == 64 )
340 {
341 // SHA-256 hash from older file formats
342 std::string sha_hash;
343 picosha2::hash256_hex_string( aFile.decompressedData, sha_hash );
344
345 if( sha_hash != aFile.data_hash )
346 {
347 wxLogTrace( wxT( "KICAD_EMBED" ),
348 wxT( "%s:%s:%d\n * Checksum error in embedded file '%s'" ),
349 __FILE__, __FUNCTION__, __LINE__, aFile.name );
350 aFile.decompressedData.clear();
352 }
353 }
354 else if( new_hash != aFile.data_hash )
355 {
356 // Current MMH3 hash didn't match. Try the V1 hash algorithm for files
357 // saved before the tail-byte alignment fix.
359 v1hash.addDataV1( reinterpret_cast<const uint8_t*>( aFile.decompressedData.data() ),
360 aFile.decompressedData.size() );
361 std::string v1_hash = v1hash.digest().ToString();
362
363 if( v1_hash != aFile.data_hash )
364 {
365 wxLogTrace( wxT( "KICAD_EMBED" ),
366 wxT( "%s:%s:%d\n * Checksum error in embedded file '%s'" ),
367 __FILE__, __FUNCTION__, __LINE__, aFile.name );
368 aFile.decompressedData.clear();
370 }
371 }
372
373 aFile.data_hash = new_hash;
374
375 return RETURN_CODE::OK;
376}
377
378
380 std::string& aHash )
381{
382 wxFFileInputStream file( aFileName.GetFullPath() );
383
384 if( !file.IsOk() )
386
387 wxFileOffset length = file.GetLength();
388 std::vector<char> data( length );
389
390 if( !data.data() )
392
393 char* dataPtr = data.data();
394 wxFileOffset totalRead = 0;
395
396 while( !file.Eof() && totalRead < length )
397 {
398 file.Read( dataPtr, length - totalRead );
399 size_t bytesRead = file.LastRead();
400 dataPtr += bytesRead;
401 totalRead += bytesRead;
402 }
403
405 hash.add( data );
406 aHash = hash.digest().ToString();
407
408 return RETURN_CODE::OK;
409}
410
411
412// Parsing method
414{
415 // embedded files are version 20240706 and uses also Bars as separator
416 SetKnowsBar( true );
417
418 if( !aFiles )
419 THROW_PARSE_ERROR( "No embedded files object provided", CurSource(), CurLine(),
420 CurLineNumber(), CurOffset() );
421
422 using namespace EMBEDDED_FILES_T;
423
424 std::unique_ptr<EMBEDDED_FILES::EMBEDDED_FILE> file( nullptr );
425
426 for( T token = NextTok(); token != T_RIGHT; token = NextTok() )
427 {
428 if( token != T_LEFT )
429 Expecting( T_LEFT );
430
431 token = NextTok();
432
433 if( token != T_file )
434 Expecting( "file" );
435
436 if( file )
437 {
438 if( !file->compressedEncodedData.empty() )
439 {
442 {
443 THROW_PARSE_ERROR( "Checksum error in embedded file " + file->name,
444 CurSource(), CurLine(), CurLineNumber(), CurOffset() );
445 }
446 }
447
448 aFiles->AddFile( file.release() );
449 }
450
451 file = std::unique_ptr<EMBEDDED_FILES::EMBEDDED_FILE>( nullptr );
452
453 for( token = NextTok(); token != T_RIGHT; token = NextTok() )
454 {
455 if( token != T_LEFT )
456 Expecting( T_LEFT );
457
458 token = NextTok();
459
460 switch( token )
461 {
462 case T_checksum:
463 if( !file )
464 Expecting( T_name );
465
466 NeedSYMBOLorNUMBER();
467
468 if( !IsSymbol( token ) )
469 Expecting( "checksum data" );
470
471 file->data_hash = CurStr();
472 NeedRIGHT();
473 break;
474
475 case T_data:
476 if( !file )
477 Expecting( T_name);
478
479 try
480 {
481 NeedBAR();
482 }
483 catch( const PARSE_ERROR& e )
484 {
485 // No data in the file -- due to bug in writer for 9.0.0
486 if( curTok == T_RIGHT )
487 break;
488 else
489 throw e;
490 }
491 catch( ... )
492 {
493 throw;
494 }
495
496 token = NextTok();
497
498 file->compressedEncodedData.reserve( 1 << 17 );
499
500 while( token != T_BAR )
501 {
502 if( !IsSymbol( token ) )
503 Expecting( "base64 file data" );
504
505 file->compressedEncodedData += CurStr();
506 token = NextTok();
507 }
508
509 file->compressedEncodedData.shrink_to_fit();
510
511 NeedRIGHT();
512 break;
513
514 case T_name:
515 if( file )
516 {
517 wxLogTrace( wxT( "KICAD_EMBED" ),
518 wxT( "Duplicate 'name' tag in embedded file %s" ), file->name );
519 }
520
521 NeedSYMBOLorNUMBER();
522
523 file = std::make_unique<EMBEDDED_FILES::EMBEDDED_FILE>();
524 file->name = CurStr();
525 NeedRIGHT();
526
527 break;
528
529 case T_type:
530 if( !file )
531 Expecting( T_name );
532
533 token = NextTok();
534
535 switch( token )
536 {
537 case T_datasheet: file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::DATASHEET; break;
538 case T_font: file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::FONT; break;
539 case T_model: file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::MODEL; break;
540 case T_worksheet: file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::WORKSHEET; break;
541 case T_other: file->type = EMBEDDED_FILES::EMBEDDED_FILE::FILE_TYPE::OTHER; break;
542 default: Expecting( "datasheet, font, model, worksheet or other" ); break;
543 }
544
545 NeedRIGHT();
546 break;
547
548 default:
549 Expecting( "checksum, data or name" );
550 }
551 }
552 }
553
554 // Add the last file in the collection
555 if( file )
556 {
557 if( !file->compressedEncodedData.empty() )
558 {
561 {
562 THROW_PARSE_ERROR( "Checksum error in embedded file " + file->name,
563 CurSource(), CurLine(), CurLineNumber(), CurOffset() );
564 }
565 }
566
567 aFiles->AddFile( file.release() );
568 }
569}
570
571
572wxFileName EMBEDDED_FILES::GetTemporaryFileName( const wxString& aName ) const
573{
574 wxFileName cacheFile;
575
576 auto it = m_files.find( aName );
577
578 if( it == m_files.end() )
579 return cacheFile;
580
581 cacheFile.AssignDir( PATHS::GetUserCachePath() );
582 cacheFile.AppendDir( wxT( "embed" ) );
583
584 if( !PATHS::EnsurePathExists( cacheFile.GetFullPath() ) )
585 {
586 wxLogTrace( wxT( "KICAD_EMBED" ),
587 wxT( "%s:%s:%d\n * failed to create embed cache directory '%s'" ),
588 __FILE__, __FUNCTION__, __LINE__, cacheFile.GetPath() );
589
590 cacheFile.SetPath( wxFileName::GetTempDir() );
591 }
592
593 wxFileName inputName( aName );
594
595 // Store the cache file name using the data hash to allow for shared data between
596 // multiple projects using the same files as well as deconflicting files with the same name
597 cacheFile.SetName( "kicad_embedded_" + it->second->data_hash );
598 cacheFile.SetExt( inputName.GetExt() );
599
600 if( cacheFile.FileExists() && cacheFile.IsFileReadable() )
601 return cacheFile;
602
603 wxFFileOutputStream out( cacheFile.GetFullPath() );
604
605 if( !out.IsOk() )
606 {
607 cacheFile.Clear();
608 return cacheFile;
609 }
610
611 out.Write( it->second->decompressedData.data(), it->second->decompressedData.size() );
612
613 return cacheFile;
614}
615
616
617const std::vector<wxString>* EMBEDDED_FILES::GetFontFiles() const
618{
619 return &m_fontFiles;
620}
621
622
623const std::vector<wxString>* EMBEDDED_FILES::UpdateFontFiles()
624{
625 m_fontFiles.clear();
626
627 for( const auto& [name, entry] : m_files )
628 {
629 if( entry->type == EMBEDDED_FILE::FILE_TYPE::FONT )
630 m_fontFiles.push_back( GetTemporaryFileName( name ).GetFullPath() );
631 }
632
633 return &m_fontFiles;
634}
635
636
637// Move constructor
639 m_files( std::move( other.m_files ) ),
640 m_fontFiles( std::move( other.m_fontFiles ) ),
641 m_fileAddedCallback( std::move( other.m_fileAddedCallback ) ),
642 m_embedFonts( other.m_embedFonts )
643{
644 other.m_embedFonts = false;
645}
646
647
648// Move assignment operator
650{
651 if (this != &other)
652 {
654 m_files = std::move( other.m_files );
655 m_fontFiles = std::move( other.m_fontFiles );
656 m_fileAddedCallback = std::move( other.m_fileAddedCallback );
657 m_embedFonts = other.m_embedFonts;
658 other.m_embedFonts = false;
659 }
660
661 return *this;
662}
663
664
665// Copy constructor
666//
667// Shares ownership of the underlying EMBEDDED_FILE payloads via shared_ptr so that cloning a
668// container that transitively holds embedded files (e.g. a FOOTPRINT being snapshotted into the
669// undo stack) does not duplicate large blobs such as embedded 3D models. Mutations applied
670// through raw EMBEDDED_FILE* pointers obtained from one collection will be visible to other
671// collections that share the same shared_ptr; callers that require an isolated mutable copy
672// should construct a new EMBEDDED_FILE explicitly.
680
681
682EMBEDDED_FILES::EMBEDDED_FILES( const EMBEDDED_FILES& other, bool aDeepCopy ) :
685{
686 if( aDeepCopy )
687 {
688 // True deep copy is requested. Allocate a fresh EMBEDDED_FILE for each entry so that
689 // subsequent mutations through this collection cannot affect the source collection.
690 for( const auto& [name, file] : other.m_files )
691 m_files[name] = std::make_shared<EMBEDDED_FILE>( *file );
692
693 m_fontFiles = other.m_fontFiles;
694 }
695}
696
697
698// Copy assignment operator
699//
700// Assignment performs a deep copy (in contrast to the copy constructor, which shares ownership
701// of payloads). Assignment is used by callers such as FOOTPRINT::operator= and
702// LIB_SYMBOL::operator= where the destination is a live, separately editable object that may
703// later mutate EMBEDDED_FILE fields through raw pointers; aliasing would let those mutations
704// silently bleed into the source. The cheap-clone path for FOOTPRINT::Clone() goes through the
705// copy constructor instead.
707{
708 if( this != &other )
709 {
710 m_files.clear();
711
712 for( const auto& [name, file] : other.m_files )
713 m_files[name] = std::make_shared<EMBEDDED_FILE>( *file );
714
715 m_fontFiles = other.m_fontFiles;
718 }
719
720 return *this;
721}
const char * name
void ParseEmbedded(EMBEDDED_FILES *aFiles)
std::vector< wxString > m_fontFiles
void RemoveFile(const wxString &name, bool aErase=true)
Remove a file from the collection and frees the memory.
@ OUT_OF_MEMORY
Could not allocate memory.
@ FILE_NOT_FOUND
File not found on disk.
@ CHECKSUM_ERROR
Checksum in file does not match data.
wxFileName GetTemporaryFileName(const wxString &aName) const
void WriteEmbeddedFiles(OUTPUTFORMATTER &aOut, bool aWriteData) const
Output formatter for the embedded files.
const std::vector< wxString > * UpdateFontFiles()
Helper function to get a list of fonts for fontconfig to add to the library.
FILE_ADDED_CALLBACK m_fileAddedCallback
static RETURN_CODE DecompressAndDecode(EMBEDDED_FILE &aFile)
Takes data from the #compressedEncodedData buffer and Base64 decodes it.
static RETURN_CODE ComputeFileHash(const wxFileName &aFileName, std::string &aHash)
Compute the hash of a file on disk without fully embedding it.
bool HasFile(const wxString &name) const
void ClearEmbeddedFiles(bool aDeleteFiles=true)
void ClearEmbeddedFonts()
Remove all embedded fonts from the collection.
EMBEDDED_FILES & operator=(EMBEDDED_FILES &&other) noexcept
EMBEDDED_FILE * AddFile(const wxFileName &aName, bool aOverwrite)
Load a file from disk and adds it to the collection.
static uint32_t Seed()
const std::vector< wxString > * GetFontFiles() const
If we just need the cached version of the font files, we can use this function which is const and wil...
std::map< wxString, std::shared_ptr< EMBEDDED_FILE > > m_files
EMBEDDED_FILES()=default
static RETURN_CODE CompressAndEncode(EMBEDDED_FILE &aFile)
Take data from the #decompressedData buffer and compresses it using ZSTD into the #compressedEncodedD...
bool m_embedFonts
If set, fonts will be embedded in the element on save.
A streaming C++ equivalent for MurmurHash3_x64_128.
Definition mmh3_hash.h:56
FORCE_INLINE void addDataV1(const uint8_t *data, size_t length)
Definition mmh3_hash.h:95
FORCE_INLINE void add(const std::string &input)
Definition mmh3_hash.h:117
FORCE_INLINE HASH_128 digest()
Definition mmh3_hash.h:136
An interface used to output 8 bit text in a convenient way.
Definition richio.h:291
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:507
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:422
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
Definition paths.cpp:518
static wxString GetUserCachePath()
Gets the stock (install) 3d viewer plugins path.
Definition paths.cpp:460
static const std::string KiCadUriPrefix
#define THROW_PARSE_ERROR(aProblem, aSource, aInputLine, aLineNumber, aByteIndex)
#define MIME_BASE64_LENGTH
std::vector< char > decompressedData
std::string ToString() const
Definition hash_128.h:43
A filename or source description, a problem input line, a line number, a byte offset,...
wxString result
Test unit parsing edge cases and error handling.
Definition of file extensions used in Kicad.