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