KiCad PCB EDA Suite
Loading...
Searching...
No Matches
altium_binary_parser.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) 2019-2020 Thomas Pointhuber <[email protected]>
5 * Copyright (C) 2023 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
26#include "altium_parser_utils.h"
27
28#include <compoundfilereader.h>
29#include <ki_exception.h>
30#include <math/util.h>
31#include <numeric>
32#include <sstream>
33#include <utf.h>
34#include <wx/log.h>
35#include <wx/translation.h>
36
37
38// Helper for debug logging
39std::string FormatPath( const std::vector<std::string>& aVectorPath )
40{
41 return std::accumulate( aVectorPath.cbegin(), aVectorPath.cend(), std::string(),
42 []( const std::string& ss, const std::string& s )
43 {
44 return ss.empty() ? s : ss + '\\' + s;
45 } );
46}
47
48
50{
51 // Open file
52 FILE* fp = wxFopen( aFilePath, "rb" );
53
54 if( fp == nullptr )
55 {
56 THROW_IO_ERROR( wxString::Format( _( "Cannot open file '%s'." ), aFilePath ) );
57 }
58
59 fseek( fp, 0, SEEK_END );
60 long len = ftell( fp );
61
62 if( len < 0 )
63 {
64 fclose( fp );
65 THROW_IO_ERROR( _( "Error reading file: cannot determine length." ) );
66 }
67
68 // Read into buffer (TODO: add support for memory-mapped files to avoid this copy!)
69 m_buffer.resize( len );
70
71 fseek( fp, 0, SEEK_SET );
72
73 size_t bytesRead = fread( m_buffer.data(), sizeof( unsigned char ), len, fp );
74 fclose( fp );
75
76 if( static_cast<size_t>( len ) != bytesRead )
77 {
78 THROW_IO_ERROR( _( "Error reading file." ) );
79 }
80
81 try
82 {
83 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
84 }
85 catch( CFB::CFBException& exception )
86 {
87 THROW_IO_ERROR( exception.what() );
88 }
89}
90
91
92ALTIUM_COMPOUND_FILE::ALTIUM_COMPOUND_FILE( const void* aBuffer, size_t aLen )
93{
94 m_buffer.resize( aLen );
95 memcpy( m_buffer.data(), aBuffer, aLen );
96
97 try
98 {
99 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
100 }
101 catch( CFB::CFBException& exception )
102 {
103 THROW_IO_ERROR( exception.what() );
104 }
105}
106
107
108std::unique_ptr<ALTIUM_COMPOUND_FILE>
109ALTIUM_COMPOUND_FILE::DecodeIntLibStream( const CFB::COMPOUND_FILE_ENTRY& cfe )
110{
111 wxCHECK( cfe.size >= 1, nullptr );
112
113 size_t streamSize = cfe.size;
114 wxMemoryBuffer buffer( streamSize );
115 buffer.SetDataLen( streamSize );
116
117 // read file into buffer
118 GetCompoundFileReader().ReadFile( &cfe, 0, reinterpret_cast<char*>( buffer.GetData() ),
119 streamSize );
120
121 // 0x02: compressed stream, 0x00: uncompressed
122 if( buffer[0] == 0x02 )
123 {
124 wxMemoryInputStream memoryInputStream( buffer.GetData(), streamSize );
125 memoryInputStream.SeekI( 1, wxFromStart );
126
127 wxZlibInputStream zlibInputStream( memoryInputStream );
128 wxMemoryOutputStream decodedPcbLibStream;
129 decodedPcbLibStream << zlibInputStream;
130
131 wxStreamBuffer* outStream = decodedPcbLibStream.GetOutputStreamBuffer();
132
133 return std::make_unique<ALTIUM_COMPOUND_FILE>( outStream->GetBufferStart(),
134 outStream->GetIntPosition() );
135 }
136 else if( buffer[0] == 0x00 )
137 {
138 return std::make_unique<ALTIUM_COMPOUND_FILE>(
139 reinterpret_cast<uint8_t*>( buffer.GetData() ) + 1, streamSize - 1 );
140 }
141 else
142 {
143 wxFAIL_MSG( wxString::Format( "Altium IntLib unknown header: %02x %02x %02x %02x %02x",
144 buffer[0], buffer[1], buffer[2], buffer[3], buffer[4] ) );
145 }
146
147 return nullptr;
148}
149
150
151std::map<wxString, wxString> ALTIUM_COMPOUND_FILE::ListLibFootprints()
152{
153 if( m_libFootprintDirNameCache.empty() )
155
157}
158
159
160std::tuple<wxString, const CFB::COMPOUND_FILE_ENTRY*>
161ALTIUM_COMPOUND_FILE::FindLibFootprintDirName( const wxString& aFpUnicodeName )
162{
163 if( m_libFootprintNameCache.empty() )
165
166 auto it = m_libFootprintNameCache.find( aFpUnicodeName );
167
168 if( it == m_libFootprintNameCache.end() )
169 return { wxEmptyString, nullptr };
170
171 return { it->first, it->second };
172}
173
174
175const CFB::COMPOUND_FILE_ENTRY*
176ALTIUM_COMPOUND_FILE::FindStreamSingleLevel( const CFB::COMPOUND_FILE_ENTRY* aEntry,
177 const std::string aName, const bool aIsStream ) const
178{
179 if( !m_reader || !aEntry )
180 return nullptr;
181
182 const CFB::COMPOUND_FILE_ENTRY* ret = nullptr;
183
184 m_reader->EnumFiles( aEntry, 1,
185 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string& dir,
186 int level ) -> int
187 {
188 if( ret != nullptr )
189 return 1;
190
191 if( m_reader->IsStream( entry ) == aIsStream )
192 {
193 std::string name = UTF16ToUTF8( entry->name );
194 if( name == aName.c_str() )
195 {
196 ret = entry;
197 return 1;
198 }
199 }
200
201 return 0;
202 } );
203 return ret;
204}
205
206
207std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*>
208ALTIUM_COMPOUND_FILE::GetLibSymbols( const CFB::COMPOUND_FILE_ENTRY* aStart ) const
209{
210 const CFB::COMPOUND_FILE_ENTRY* root = aStart ? aStart : m_reader->GetRootEntry();
211
212 if( !root )
213 return {};
214
215 std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*> folders;
216
217 m_reader->EnumFiles( root, 1, [&]( const CFB::COMPOUND_FILE_ENTRY* tentry, const CFB::utf16string&, int ) -> int
218 {
219 wxString dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
220
221 if( m_reader->IsStream( tentry ) )
222 return 0;
223
224 m_reader->EnumFiles( tentry, 1,
225 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string&, int ) -> int
226 {
227 std::wstring fileName = UTF16ToWstring( entry->name, entry->nameLen );
228
229 if( m_reader->IsStream( entry ) && fileName == L"Data" )
230 folders[dirName] = entry;
231
232 return 0;
233 } );
234
235 return 0;
236 } );
237
238 return folders;
239}
240
241
242std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*>
243ALTIUM_COMPOUND_FILE::EnumDir( const std::wstring& aDir ) const
244{
245 const CFB::COMPOUND_FILE_ENTRY* root = m_reader->GetRootEntry();
246
247 if( !root )
248 return {};
249
250 std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*> files;
251
252 m_reader->EnumFiles(
253 root, 1,
254 [&]( const CFB::COMPOUND_FILE_ENTRY* tentry, const CFB::utf16string& dir,
255 int level ) -> int
256 {
257 if( m_reader->IsStream( tentry ) )
258 return 0;
259
260 std::wstring dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
261
262 if( dirName != aDir )
263 return 0;
264
265 m_reader->EnumFiles(
266 tentry, 1,
267 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string&,
268 int ) -> int
269 {
270 if( m_reader->IsStream( entry ) )
271 {
272 std::wstring fileName =
273 UTF16ToWstring( entry->name, entry->nameLen );
274
275 files[fileName] = entry;
276 }
277
278 return 0;
279 } );
280 return 0;
281 } );
282
283 return files;
284}
285
286
287const CFB::COMPOUND_FILE_ENTRY*
288ALTIUM_COMPOUND_FILE::FindStream( const CFB::COMPOUND_FILE_ENTRY* aStart,
289 const std::vector<std::string>& aStreamPath ) const
290{
291 if( !m_reader )
292 return nullptr;
293
294 if( !aStart )
295 aStart = m_reader->GetRootEntry();
296
297 auto it = aStreamPath.cbegin();
298
299 while( aStart != nullptr )
300 {
301 const std::string& name = *it;
302
303 if( ++it == aStreamPath.cend() )
304 {
305 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, true );
306 return ret;
307 }
308 else
309 {
310 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, false );
311 aStart = ret;
312 }
313 }
314
315 return nullptr;
316}
317
318
319const CFB::COMPOUND_FILE_ENTRY*
320ALTIUM_COMPOUND_FILE::FindStream( const std::vector<std::string>& aStreamPath ) const
321{
322 return FindStream( nullptr, aStreamPath );
323}
324
325
327{
330
331 if( !m_reader )
332 return;
333
334 const CFB::COMPOUND_FILE_ENTRY* root = m_reader->GetRootEntry();
335
336 if( !root )
337 return;
338
339 m_reader->EnumFiles( root, 1,
340 [this]( const CFB::COMPOUND_FILE_ENTRY* tentry, const CFB::utf16string& dir,
341 int level ) -> int
342 {
343 if( m_reader->IsStream( tentry ) )
344 return 0;
345
346 m_reader->EnumFiles( tentry, 1,
347 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string&, int ) -> int
348 {
349 std::wstring fileName = UTF16ToWstring( entry->name, entry->nameLen );
350
351 if( m_reader->IsStream( entry ) && fileName == L"Parameters" )
352 {
353 ALTIUM_BINARY_PARSER parametersReader( *this, entry );
354 std::map<wxString, wxString> parameterProperties =
355 parametersReader.ReadProperties();
356
357 wxString key = ALTIUM_PROPS_UTILS::ReadString(
358 parameterProperties, wxT( "PATTERN" ), wxT( "" ) );
359 wxString fpName = ALTIUM_PROPS_UTILS::ReadUnicodeString(
360 parameterProperties, wxT( "PATTERN" ), wxT( "" ) );
361
362 m_libFootprintDirNameCache[key] = fpName;
363 m_libFootprintNameCache[fpName] = tentry;
364 }
365
366 return 0;
367 } );
368 return 0;
369 } );
370}
371
372
374 const CFB::COMPOUND_FILE_ENTRY* aEntry )
375{
376 m_subrecord_end = nullptr;
377 m_size = static_cast<size_t>( aEntry->size );
378 m_error = false;
379 m_content.reset( new char[m_size] );
380 m_pos = m_content.get();
381
382 // read file into buffer
383 aFile.GetCompoundFileReader().ReadFile( aEntry, 0, m_content.get(), m_size );
384}
385
386
387ALTIUM_BINARY_PARSER::ALTIUM_BINARY_PARSER( std::unique_ptr<char[]>& aContent, size_t aSize )
388{
389 m_subrecord_end = nullptr;
390 m_size = aSize;
391 m_error = false;
392 m_content = std::move( aContent );
393 m_pos = m_content.get();
394}
395
396
397std::map<wxString, wxString> ALTIUM_BINARY_PARSER::ReadProperties(
398 std::function<std::map<wxString, wxString>( const std::string& )> handleBinaryData )
399{
400
401 std::map<wxString, wxString> kv;
402
403 uint32_t length = Read<uint32_t>();
404 bool isBinary = ( length & 0xff000000 ) != 0;
405
406 length &= 0x00ffffff;
407
408 if( length > GetRemainingBytes() )
409 {
410 m_error = true;
411 return kv;
412 }
413
414 if( length == 0 )
415 {
416 return kv;
417 }
418
419 // There is one case by kliment where Board6 ends with "|NEARDISTANCE=1000mi".
420 // Both the 'l' and the null-byte are missing, which looks like Altium swallowed two bytes.
421 bool hasNullByte = m_pos[length - 1] == '\0';
422
423 if( !hasNullByte )
424 {
425 wxLogError( _( "Missing null byte at end of property list. Imported data might be "
426 "malformed or missing." ) );
427 }
428
429 // we use std::string because std::string can handle NULL-bytes
430 // wxString would end the string at the first NULL-byte
431 std::string str = std::string( m_pos, length - ( hasNullByte ? 1 : 0 ) );
432 m_pos += length;
433
434 if( isBinary )
435 {
436 return handleBinaryData( str );
437 }
438
439 std::size_t token_end = 0;
440
441 while( token_end < str.size() && token_end != std::string::npos )
442 {
443 std::size_t token_start = str.find( '|', token_end );
444 std::size_t token_equal = str.find( '=', token_end );
445 std::size_t key_start;
446
447 if( token_start <= token_equal )
448 {
449 key_start = token_start + 1;
450 }
451 else
452 {
453 // Leading "|" before "RECORD=28" may be missing in older schematic versions.
454 key_start = token_end;
455 }
456
457 token_end = str.find( '|', key_start );
458
459 if( token_equal >= token_end )
460 {
461 continue; // this looks like an error: skip the entry. Also matches on std::string::npos
462 }
463
464 if( token_end == std::string::npos )
465 {
466 token_end = str.size() + 1; // this is the correct offset
467 }
468
469 std::string keyS = str.substr( key_start, token_equal - key_start );
470 std::string valueS = str.substr( token_equal + 1, token_end - token_equal - 1 );
471
472 // convert the strings to wxStrings, since we use them everywhere
473 // value can have non-ASCII characters, so we convert them from LATIN1/ISO8859-1
474 wxString key( keyS.c_str(), wxConvISO8859_1 );
475 // Altium stores keys either in Upper, or in CamelCase. Lets unify it.
476 wxString canonicalKey = key.Trim( false ).Trim( true ).MakeUpper();
477 // If the key starts with '%UTF8%' we have to parse the value using UTF8
478 wxString value;
479
480 if( canonicalKey.StartsWith( "%UTF8%" ) )
481 value = wxString( valueS.c_str(), wxConvUTF8 );
482 else
483 value = wxString( valueS.c_str(), wxConvISO8859_1 );
484
485 if( canonicalKey != wxS( "PATTERN" ) && canonicalKey != wxS( "SOURCEFOOTPRINTLIBRARY" ) )
486 {
487 // Breathless hack because I haven't a clue what the story is here (but this character
488 // appears in a lot of radial dimensions and is rendered by Altium as a space).
489 value.Replace( wxT( "ÿ" ), wxT( " " ) );
490 }
491
492 if( canonicalKey == wxT( "DESIGNATOR" )
493 || canonicalKey == wxT( "NAME" )
494 || canonicalKey == wxT( "TEXT" ) )
495 {
496 value = AltiumPropertyToKiCadString( value.Trim() );
497 }
498
499 kv.insert( { canonicalKey, value.Trim() } );
500 }
501
502 return kv;
503}
504
const char * name
Definition: DXF_plotter.cpp:57
std::string FormatPath(const std::vector< std::string > &aVectorPath)
Helper for debug logging (vector -> string)
wxString AltiumPropertyToKiCadString(const wxString &aString)
size_t GetRemainingBytes() const
std::unique_ptr< char[]> m_content
ALTIUM_BINARY_PARSER(const ALTIUM_COMPOUND_FILE &aFile, const CFB::COMPOUND_FILE_ENTRY *aEntry)
std::map< wxString, wxString > ReadProperties(std::function< std::map< wxString, wxString >(const std::string &)> handleBinaryData=[](const std::string &) { return std::map< wxString, wxString >();})
std::map< wxString, wxString > ListLibFootprints()
const CFB::CompoundFileReader & GetCompoundFileReader() const
std::unique_ptr< ALTIUM_COMPOUND_FILE > DecodeIntLibStream(const CFB::COMPOUND_FILE_ENTRY &cfe)
const CFB::COMPOUND_FILE_ENTRY * FindStreamSingleLevel(const CFB::COMPOUND_FILE_ENTRY *aEntry, const std::string aName, const bool aIsStream) const
std::map< wxString, const CFB::COMPOUND_FILE_ENTRY * > EnumDir(const std::wstring &aDir) const
std::vector< char > m_buffer
std::unique_ptr< CFB::CompoundFileReader > m_reader
ALTIUM_COMPOUND_FILE(const wxString &aFilePath)
Open a CFB file.
std::map< wxString, const CFB::COMPOUND_FILE_ENTRY * > GetLibSymbols(const CFB::COMPOUND_FILE_ENTRY *aStart) const
std::map< wxString, const CFB::COMPOUND_FILE_ENTRY * > m_libFootprintNameCache
std::tuple< wxString, const CFB::COMPOUND_FILE_ENTRY * > FindLibFootprintDirName(const wxString &aFpUnicodeName)
const CFB::COMPOUND_FILE_ENTRY * FindStream(const std::vector< std::string > &aStreamPath) const
std::map< wxString, wxString > m_libFootprintDirNameCache
#define _(s)
#define THROW_IO_ERROR(msg)
Definition: ki_exception.h:39
#define kv