KiCad PCB EDA Suite
Loading...
Searching...
No Matches
target3001_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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General 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 "target3001_parser.h"
21
22#include <algorithm>
23#include <charconv>
24#include <cstring>
25#include <map>
26#include <set>
27
28#include <wx/ffile.h>
29#include <wx/intl.h>
30#include <wx/filename.h>
31#include <wx/strconv.h>
32
33#include <core/base64.h>
34#include <ki_exception.h>
35
36
37namespace TARGET3001
38{
39
40namespace
41{
42
43// Version thresholds at which the settings block gained fields
44constexpr int32_t V_SETTINGS_A = 0x232a;
45constexpr int32_t V_SETTINGS_B = 0x232b;
46constexpr int32_t V_TRACK_WIDTH = 0x232c;
47constexpr int32_t V_LOGBOOK = 0x232d;
48constexpr int32_t V_SETTINGS_C = 0x232e;
49constexpr int32_t V_SETTINGS_D = 0x232f;
50constexpr int32_t V_SETTINGS_E = 0x2330;
51constexpr int32_t V_COMPONENT_EXTRA = 0x2711;
52constexpr int32_t V_SETTINGS_F = 0x2712;
53constexpr int32_t V_SAVE_TIME = 0x271b;
54constexpr int32_t V_SETTINGS_G = 0x271c;
55constexpr int32_t V_SETTINGS_H = 0x271d;
56constexpr int32_t V_SETTINGS_I = 0x271e;
57constexpr int32_t V_SETTINGS_J = 0x271f;
58constexpr int32_t V_SETTINGS_K = 0x2720;
59constexpr int32_t V_BLOBS = 0x272e;
60constexpr int32_t V_SETTINGS_L = 0x272f;
61constexpr int32_t V_CHECKSUM = 0x2739;
62constexpr int32_t V_SETTINGS_M = 0x2743;
63
64constexpr int MAX_DEPTH = 32;
65
66// A component element storing this signal holds a pad number in its component field instead
67constexpr uint16_t LINKED_SIGNAL = 65503;
68
69
71void resolveLinkedSignals( COMPONENT& aComponent, uint16_t aOwner )
72{
73 std::map<uint16_t, uint16_t> padSignals;
74
75 for( const ELEMENT& e : aComponent.packageItems )
76 {
77 if( e.type == ELEMENT_TYPE::PAD && e.pad.number != 0 )
78 padSignals[e.pad.number] = e.base.signal;
79 }
80
81 auto resolve = [&]( ELEMENT& aElem )
82 {
83 if( aElem.base.signal != LINKED_SIGNAL )
84 return;
85
86 auto it = padSignals.find( aElem.base.component );
87 aElem.base.signal = ( it != padSignals.end() && it->second != LINKED_SIGNAL ) ? it->second : 0;
88 aElem.base.component = aOwner;
89 };
90
91 for( ELEMENT& e : aComponent.packageItems )
92 resolve( e );
93
94 for( ELEMENT& sym : aComponent.symbols )
95 {
96 if( sym.symbol )
97 {
98 for( ELEMENT& e : sym.symbol->children )
99 resolve( e );
100 }
101 }
102}
103
104
105std::vector<std::string> splitFields( const std::string& aText, char aSeparator )
106{
107 std::vector<std::string> fields;
108 size_t start = 0;
109
110 while( true )
111 {
112 size_t end = aText.find( aSeparator, start );
113 fields.push_back( aText.substr( start, end - start ) );
114
115 if( end == std::string::npos )
116 return fields;
117
118 start = end + 1;
119 }
120}
121
122
123template <typename T>
124bool toInt( const std::string& aText, T& aOut )
125{
126 const char* end = aText.data() + aText.size();
127 auto [ptr, ec] = std::from_chars( aText.data(), end, aOut );
128 return ec == std::errc() && ptr == end;
129}
130
131
133std::optional<POLYGON_POUR> parsePolygonPour( const std::string& aValue )
134{
135 size_t star = aValue.find( '*' );
136
137 if( star == std::string::npos )
138 return std::nullopt;
139
140 std::vector<std::string> head = splitFields( aValue.substr( 0, star ), ',' );
141 std::vector<std::string> tail = splitFields( aValue.substr( star + 1 ), ',' );
142 POLYGON_POUR poly;
143 int hatch = 0;
144 int thermals = 0;
145 int islands = 0;
146
147 if( head.size() < 9 || !toInt( head[0], poly.layer ) || !toInt( head[1], poly.id ) || !toInt( head[2], poly.width )
148 || !toInt( head[3], hatch ) || !toInt( head[4], poly.rank ) || !toInt( head[5], thermals )
149 || !toInt( head[6], islands ) )
150 {
151 return std::nullopt;
152 }
153
154 poly.thermals = thermals != 0;
155 poly.removeIslands = islands != 0;
156
157 // Vertices are "x,y" pairs joined by ';', so they span the remaining comma fields
158 std::string vertices = head[7];
159
160 for( size_t i = 8; i < head.size(); i++ )
161 vertices += ',' + head[i];
162
163 for( const std::string& pair : splitFields( vertices, ';' ) )
164 {
165 size_t comma = pair.find( ',' );
166 int32_t x = 0;
167 int32_t y = 0;
168
169 if( comma == std::string::npos || !toInt( pair.substr( 0, comma ), x )
170 || !toInt( pair.substr( comma + 1 ), y ) )
171 {
172 return std::nullopt;
173 }
174
175 poly.outline.emplace_back( x, y );
176 }
177
178 if( !tail.empty() && !tail[0].empty() && !toInt( tail[0], poly.edgeClearance ) )
179 return std::nullopt;
180
181 // The polygon's own property list escapes commas as 0x1c and splits names from values with 0x1d;
182 // older records drop the fields before it, so it is found by its separator
183 for( size_t i = 1; i < tail.size(); i++ )
184 {
185 for( const std::string& entry : splitFields( tail[i], '\n' ) )
186 {
187 size_t split = entry.find( '\x1d' );
188
189 if( split != std::string::npos && entry.substr( 0, split ) == "AURA" )
190 {
191 std::string value = entry.substr( split + 1 );
192
193 if( !value.empty() && value.back() == '\r' )
194 value.pop_back();
195
196 toInt( value, poly.aura );
197 }
198 }
199 }
200
201 return poly;
202}
203
204
205const std::string PASSWORD_MARKER_A = "$%&\xa7";
206const std::string PASSWORD_MARKER_B = "$%&\xa7!";
207
208
209class READER
210{
211public:
212 explicit READER( const std::vector<uint8_t>& aData ) :
213 m_data( aData ),
214 m_pos( 0 )
215 {
216 }
217
218 size_t Pos() const { return m_pos; }
219 size_t Remaining() const { return m_data.size() - m_pos; }
220 bool AtEnd() const { return m_pos >= m_data.size(); }
221
222 void Require( size_t aBytes ) const
223 {
224 if( aBytes > Remaining() )
225 {
226 THROW_IO_ERROR( wxString::Format( _( "Unexpected end of TARGET 3001! file at offset %zu." ),
227 m_pos ) );
228 }
229 }
230
231 uint8_t U8()
232 {
233 Require( 1 );
234 return m_data[m_pos++];
235 }
236
237 uint16_t U16()
238 {
239 Require( 2 );
240 uint16_t v = m_data[m_pos] | ( m_data[m_pos + 1] << 8 );
241 m_pos += 2;
242 return v;
243 }
244
245 uint32_t U32()
246 {
247 Require( 4 );
248 uint32_t v = uint32_t( m_data[m_pos] ) | ( uint32_t( m_data[m_pos + 1] ) << 8 )
249 | ( uint32_t( m_data[m_pos + 2] ) << 16 ) | ( uint32_t( m_data[m_pos + 3] ) << 24 );
250 m_pos += 4;
251 return v;
252 }
253
254 int32_t S32() { return static_cast<int32_t>( U32() ); }
255
256 float F32()
257 {
258 uint32_t bits = U32();
259 float v;
260 std::memcpy( &v, &bits, sizeof( v ) );
261 return v;
262 }
263
264 void Skip( size_t aBytes )
265 {
266 Require( aBytes );
267 m_pos += aBytes;
268 }
269
270 std::vector<uint8_t> Bytes( size_t aBytes )
271 {
272 Require( aBytes );
273 std::vector<uint8_t> out( m_data.begin() + m_pos, m_data.begin() + m_pos + aBytes );
274 m_pos += aBytes;
275 return out;
276 }
277
279 size_t Count( size_t aMinItemSize )
280 {
281 int32_t n = S32();
282
283 if( n < 0 )
284 Fail( "negative count" );
285
286 if( aMinItemSize && size_t( n ) > Remaining() / aMinItemSize )
287 Fail( "count exceeds file size" );
288
289 return size_t( n );
290 }
291
292 std::string LStr()
293 {
294 size_t len = Count( 1 );
295 std::string s( reinterpret_cast<const char*>( m_data.data() + m_pos ), len );
296 m_pos += len;
297 return s;
298 }
299
300 [[noreturn]] void Fail( const char* aWhat ) const
301 {
302 THROW_IO_ERROR( wxString::Format( _( "Invalid TARGET 3001! file at offset %zu (%s)." ), m_pos,
303 aWhat ) );
304 }
305
306private:
307 const std::vector<uint8_t>& m_data;
308 size_t m_pos;
309};
310
311
312class PARSER
313{
314public:
315 explicit PARSER( const std::vector<uint8_t>& aData ) :
316 m_r( aData )
317 {
318 }
319
320 PROJECT Parse()
321 {
322 PROJECT p;
323
324 p.version = m_r.S32();
325 m_version = p.version;
326
327 parseHeader( p );
328
329 p.signals = parseTopList( nullptr );
330 p.components = parseTopList( &m_componentSlots );
331
332 // The two trees are known by their records' tags; a file may store them in the other order
333 if( holdsOnly( p.signals, ELEMENT_TYPE::COMPONENT ) && holdsOnly( p.components, ELEMENT_TYPE::SIGNAL ) )
334 std::swap( p.signals, p.components );
335
336 appendFlattened( p.schematicItems, 0 );
337 appendFlattened( p.boardItems, 0 );
338
339 // Bytes after the settings are left unread, as the source program only warns about them
340 parseSettings( p.settings );
341
342 p.ApplyTextLanguage();
343
344 return p;
345 }
346
347private:
348 void parseHeader( PROJECT& aProject )
349 {
350 aProject.schematicTextFont = m_r.LStr();
351
352 if( aProject.schematicTextFont == PASSWORD_MARKER_A || aProject.schematicTextFont == PASSWORD_MARKER_B )
353 THROW_IO_ERROR( _( "Password-protected TARGET 3001! projects are not supported." ) );
354
355 aProject.boardTextFont = m_r.LStr();
356 aProject.signalNameFont = m_r.LStr();
357
358 m_r.Skip( 70 );
359
360 m_r.Skip( 94 );
361
362 std::vector<uint8_t> functions = m_r.Bytes( BOARD_LAYER_COUNT );
363 std::vector<uint8_t> associations = m_r.Bytes( BOARD_LAYER_COUNT );
364 std::copy( functions.begin(), functions.end(), aProject.layerFunctions.begin() );
365 std::copy( associations.begin(), associations.end(), aProject.layerAssociations.begin() );
366
367 m_r.Skip( 119 );
368 uint8_t prefixCount = m_r.U8();
369
370 for( int i = 0; i < prefixCount; i++ )
371 {
372 m_r.U16();
373 m_r.LStr();
374 }
375 }
376
383 static bool holdsOnly( const std::vector<ELEMENT>& aList, ELEMENT_TYPE aType )
384 {
385 bool any = false;
386
387 for( const ELEMENT& e : aList )
388 {
389 if( e.type == ELEMENT_TYPE::NONE )
390 continue;
391
392 if( e.type != aType )
393 return false;
394
395 any = true;
396 }
397
398 return any;
399 }
400
401 std::vector<ELEMENT> parseTopList( size_t* aSlots )
402 {
403 if( m_r.U8() != uint8_t( ELEMENT_TYPE::LIST ) )
404 m_r.Fail( "element list expected" );
405
406 size_t n = m_r.Count( 1 );
407 std::vector<ELEMENT> out;
408 out.reserve( n );
409
410 for( size_t i = 0; i < n; i++ )
411 {
412 size_t before = out.size();
413 appendFlattened( out, 1 );
414
415 if( out.size() == before )
416 out.emplace_back();
417 }
418
419 if( aSlots )
420 *aSlots = n;
421
422 return out;
423 }
424
425 size_t parseListBody( std::vector<ELEMENT>& aOut, int aDepth )
426 {
427 size_t n = m_r.Count( 1 );
428 aOut.reserve( aOut.size() + n );
429
430 for( size_t i = 0; i < n; i++ )
431 appendFlattened( aOut, aDepth + 1 );
432
433 return n;
434 }
435
437 void appendFlattened( std::vector<ELEMENT>& aOut, int aDepth )
438 {
439 if( aDepth > MAX_DEPTH )
440 m_r.Fail( "element nesting too deep" );
441
442 uint8_t tag = m_r.U8();
443
444 switch( tag )
445 {
446 case uint8_t( ELEMENT_TYPE::NONE ):
447 return;
448
449 case uint8_t( ELEMENT_TYPE::LIST ):
450 parseListBody( aOut, aDepth );
451 return;
452
453 case uint8_t( ELEMENT_TYPE::LAYER_FUNCTIONS ):
454 {
455 size_t n = m_r.Count( 4 );
456
457 for( size_t i = 0; i < n; i++ )
458 m_r.LStr();
459
460 return;
461 }
462
463 default:
464 break;
465 }
466
467 if( tag < uint8_t( ELEMENT_TYPE::LINE ) || tag > uint8_t( ELEMENT_TYPE::DRC_MARKER ) )
468 m_r.Fail( "unknown element class" );
469
470 ELEMENT& e = aOut.emplace_back();
471 e.type = ELEMENT_TYPE( tag );
472 parseBase( e.base );
473 parseBody( e, aDepth );
474 }
475
476 std::vector<ELEMENT> parseChild( int aDepth )
477 {
478 std::vector<ELEMENT> out;
479 appendFlattened( out, aDepth + 1 );
480 return out;
481 }
482
483 void parseBase( ELEMENT_BASE& aBase )
484 {
485 aBase.component = m_r.U16();
486 aBase.signal = m_r.U16();
487 aBase.x = m_r.S32();
488 aBase.y = m_r.S32();
489 aBase.flags = m_r.U8();
490 aBase.status = m_r.U8();
491 aBase.layer = m_r.U8();
492 aBase.classTag = m_r.U8();
493
494 if( ( aBase.flags & 0xfe ) == 2 )
495 aBase.extra = m_r.U32();
496
497 size_t n = m_r.Count( 4 );
498
499 if( n % 2 )
500 m_r.Fail( "odd property count" );
501
502 aBase.props.reserve( n / 2 );
503
504 for( size_t i = 0; i < n; i += 2 )
505 {
506 std::string key = m_r.LStr();
507 std::string value = m_r.LStr();
508 aBase.props.emplace_back( std::move( key ), std::move( value ) );
509 }
510 }
511
512 void parseBody( ELEMENT& aElem, int aDepth )
513 {
514 switch( aElem.type )
515 {
517 {
518 LINE& l = aElem.line;
519 l.x2 = m_r.S32();
520 l.y2 = m_r.S32();
521 l.width = m_r.S32();
522 l.clearance = m_r.S32();
523 l.dashStyle = m_r.U8();
524 l.roundEnds = m_r.U8();
525 break;
526 }
527
529 {
530 PIN& p = aElem.pin;
531 p.direction = m_r.F32();
532 p.length = m_r.S32();
533 p.width = m_r.S32();
534 p.electricalType = m_r.U8();
535 p.swapLevel = m_r.U16();
536 p.inverted = m_r.U8();
537 p.clock = m_r.U8();
538 p.showNumber = m_r.U8();
539 p.supplyPin = m_r.U8();
540 p.pinNumber = m_r.U16();
541 aElem.children = parseChild( aDepth );
542 break;
543 }
544
546 {
547 PAD& p = aElem.pad;
548 p.direction = m_r.F32();
549 p.shape = m_r.U8();
550 p.width = m_r.S32();
551 p.height = m_r.S32();
552 p.clearance = m_r.S32();
553 p.drill = m_r.S32();
554 p.reserved = m_r.S32();
555 p.number = m_r.U16();
556 break;
557 }
558
560 {
561 TRIANGLE& t = aElem.triangle;
562 t.x2 = m_r.S32();
563 t.y2 = m_r.S32();
564 t.x3 = m_r.S32();
565 t.y3 = m_r.S32();
566 break;
567 }
568
570 {
571 RECTANGLE& r = aElem.rectangle;
572 r.height = m_r.S32();
573 r.width = m_r.S32();
574 r.direction = m_r.F32();
575 break;
576 }
577
579 {
580 ARC& a = aElem.arc;
581 a.endX = m_r.S32();
582 a.endY = m_r.S32();
583 a.centerX = m_r.S32();
584 a.centerY = m_r.S32();
585 a.radius = m_r.S32();
586 a.width = m_r.S32();
587 a.clearance = m_r.S32();
588 a.startAngle = m_r.F32();
589 a.endAngle = m_r.F32();
590
591 if( !std::isfinite( a.startAngle ) || !std::isfinite( a.endAngle ) )
592 m_r.Fail( "arc angle is not a number" );
593
594 break;
595 }
596
598 aElem.disc.radius = m_r.S32();
599 break;
600
602 {
603 TEXT& t = aElem.text;
604 t.text = m_r.LStr();
605 t.height = m_r.S32();
606 t.width = m_r.S32();
607 t.direction = m_r.F32();
608 t.weight = m_r.U8();
609 t.noAutoUpright = m_r.U8();
610 t.mirrored = m_r.U8();
611 t.function = m_r.U8();
612 t.font = m_r.LStr();
613 break;
614 }
615
617 {
618 FIDUCIAL& f = aElem.fiducial;
619 f.kind = m_r.U8();
620 f.radius = m_r.S32();
621 f.width = m_r.S32();
622 f.direction = m_r.F32();
623 break;
624 }
625
627 {
628 auto c = std::make_shared<COMPONENT>();
629 c->name = m_r.LStr();
630 c->value = m_r.LStr();
631 c->prefix = m_r.LStr();
632 c->library = m_r.LStr();
633 c->package = m_r.LStr();
634 c->packageSource = m_r.LStr();
635 c->referenceNumber = m_r.U16();
636
637 if( c->referenceNumber >= 65000 && c->referenceNumber < 65535 )
638 c->referenceExtension = m_r.U16();
639
640 c->connectionCount = m_r.U16();
641 c->gateState = m_r.U8();
642 c->packageItems = parseChild( aDepth );
643 c->symbols = parseChild( aDepth );
644
645 for( uint8_t& b : c->setBitmap )
646 b = m_r.U8();
647
648 resolveLinkedSignals( *c, aElem.base.component );
649
650 aElem.component = std::move( c );
651 break;
652 }
653
655 {
656 auto s = std::make_shared<SYMBOL>();
657 s->name = m_r.LStr();
658 s->suffix = m_r.LStr();
659 s->gateOrdinal = m_r.U16();
660 s->insertRequired = m_r.U8();
661 s->swapLevel = m_r.U16();
662 s->children = parseChild( aDepth );
663 aElem.symbol = std::move( s );
664 break;
665 }
666
668 {
669 auto p = std::make_shared<PACKAGE>();
670 p->package = m_r.LStr();
671 p->library = m_r.LStr();
672 p->padCount = m_r.U16();
673 p->bottomSide = m_r.U8();
674 p->direction = m_r.F32();
675 aElem.package = std::move( p );
676 break;
677 }
678
680 {
681 auto s = std::make_shared<SIGNAL>();
682 s->name = m_r.LStr();
683 s->connections = parseChild( aDepth );
684 s->tracks = parseChild( aDepth );
685 s->minWidth = m_r.S32();
686 s->minSpacing = m_r.S32();
687 s->string3 = m_r.LStr();
688 s->string4 = m_r.LStr();
689 s->record = m_r.Bytes( 48 );
690 s->string5 = m_r.LStr();
691
692 for( const auto& [key, value] : aElem.base.props )
693 {
694 if( key != "$%&POLY" )
695 continue;
696
697 if( std::optional<POLYGON_POUR> poly = parsePolygonPour( value ) )
698 s->polygons.push_back( std::move( *poly ) );
699 }
700
701 aElem.signal = std::move( s );
702 break;
703 }
704
706 {
707 SPLINE& s = aElem.spline;
708 s.endX = m_r.S32();
709 s.endY = m_r.S32();
710 s.controlX = m_r.S32();
711 s.controlY = m_r.S32();
712 s.width = m_r.S32();
713 s.clearance = m_r.S32();
714
715 break;
716 }
717
719 aElem.marker.radius = m_r.S32();
720 aElem.marker.text = m_r.LStr();
721 break;
722
723 default:
724 m_r.Fail( "unknown element class" );
725 }
726 }
727
728 void skipStrings( size_t aCount )
729 {
730 for( size_t i = 0; i < aCount; i++ )
731 m_r.LStr();
732 }
733
734 void skipCountedStrings() { skipStrings( m_r.Count( 4 ) ); }
735
736 void parseSettings( PROJECT_SETTINGS& aSettings )
737 {
738 m_r.Skip( 16 + 16 + 52 );
739 m_r.Skip( 3 * 4 );
740 m_r.Skip( 40 + 40 );
741 m_r.Skip( 5 * 4 );
742 m_r.Skip( 29 + 29 );
743
744 size_t records = m_r.Count( 16 );
745 m_r.Skip( records * 16 );
746
747 skipCountedStrings(); // functions
748 m_r.Skip( 30 );
749 m_r.LStr();
750
751 uint16_t routeLayers = m_r.U16();
752 m_r.Skip( size_t( routeLayers ) * 4 );
753
754 size_t propertyStrings = m_r.Count( 4 );
755
756 for( size_t i = 0; i + 1 < propertyStrings; i += 2 )
757 {
758 std::string key = m_r.LStr();
759 aSettings.properties.emplace_back( std::move( key ), m_r.LStr() );
760 }
761
762 if( propertyStrings % 2 )
763 m_r.LStr();
764
765 size_t padstacks = m_r.Count( 4 + 5 + 500 );
766
767 for( size_t i = 0; i < padstacks; i++ )
768 {
769 PADSTACK_DEF& def = aSettings.padstacks.emplace_back();
770 def.name = m_r.LStr();
771 m_r.Skip( 5 ); // router cost and cached use count
772
773 for( bool& on : def.onLayer )
774 on = m_r.U8() != 0;
775
776 for( int32_t& grow : def.oversize )
777 grow = int32_t( m_r.U32() );
778 }
779
780 m_r.Skip( size_t( routeLayers ) * 5 );
781 m_r.Skip( padstacks * 8 );
782
783 m_r.U32();
784 skipCountedStrings();
785 m_r.Skip( 100 + 13 + 208 );
786 skipStrings( 16 );
787
788 m_r.U8();
789 m_r.LStr();
790 m_r.LStr();
791 m_r.Skip( 22 + 15 );
792 m_r.LStr();
793 aSettings.savedBy = m_r.LStr();
794
795 size_t records9 = m_r.Count( 4 + 9 );
796
797 for( size_t i = 0; i < records9; i++ )
798 {
799 m_r.LStr();
800 m_r.Skip( 9 );
801 }
802
803 m_r.U8();
804
805 aSettings.sheetNames.reserve( 100 );
806
807 for( int i = 0; i < 100; i++ )
808 aSettings.sheetNames.push_back( m_r.LStr() );
809
810 skipStrings( 32 );
811 m_r.U8();
812
813 if( m_version >= V_SETTINGS_A )
814 {
815 m_r.LStr();
816 m_r.LStr();
817 m_r.Skip( 49 );
818 }
819
820 if( m_version >= V_SETTINGS_B )
821 m_r.LStr();
822
823 if( m_version >= V_TRACK_WIDTH )
824 m_r.Skip( 8 );
825
826 if( m_version >= V_LOGBOOK )
827 skipStrings( 3 );
828
829 if( m_version >= V_SETTINGS_C )
830 m_r.LStr();
831
832 if( m_version >= V_SETTINGS_D )
833 m_r.U16();
834
835 if( m_version >= V_SETTINGS_E )
836 m_r.LStr();
837
838 // The reader only takes these tables when the stream has not ended
839 if( m_version >= V_SETTINGS_E && !m_r.AtEnd() )
840 {
841 for( int i = 0; i < 12; i++ )
842 {
843 m_r.LStr();
844 m_r.Skip( 10 );
845 }
846
847 for( int i = 0; i < 12; i++ )
848 {
849 m_r.LStr();
850 m_r.Skip( 18 );
851 }
852 }
853
854 if( m_version >= V_COMPONENT_EXTRA )
855 {
856 for( size_t i = 0; i < m_componentSlots; i++ )
857 {
858 if( m_r.U8() )
859 m_r.Skip( 28 );
860 }
861
862 skipStrings( 223 );
863 }
864
865 if( m_version >= V_SETTINGS_F )
866 skipStrings( 2 );
867
868 if( m_version >= V_SAVE_TIME )
869 m_r.Skip( 8 );
870
871 if( m_version >= V_SETTINGS_G )
872 m_r.Skip( 40 + 40 );
873
874 if( m_version >= V_SETTINGS_H )
875 m_r.Skip( 2 );
876
877 if( m_version >= V_SETTINGS_I )
878 {
879 uint8_t language = m_r.U8();
880
881 if( language <= uint8_t( TEXT_LANGUAGE::FRENCH ) )
882 aSettings.textLanguage = TEXT_LANGUAGE( language );
883 }
884
885 if( m_version >= V_SETTINGS_J )
886 m_r.Skip( 32 );
887
888 if( m_version >= V_SETTINGS_K )
889 m_r.Skip( 1 );
890
891 if( m_version >= V_BLOBS )
892 {
893 size_t blobs = m_r.Count( 8 );
894
895 for( size_t i = 0; i < blobs; i++ )
896 {
897 m_r.LStr();
898 m_r.Skip( m_r.Count( 1 ) );
899 }
900 }
901
902 if( m_version >= V_SETTINGS_L )
903 skipStrings( 12 );
904
905 if( m_version >= V_CHECKSUM )
906 m_r.Skip( 8 );
907
908 if( m_version >= V_SETTINGS_M )
909 m_r.Skip( 16 + 16 );
910 }
911
912 READER m_r;
913 int32_t m_version = 0;
914 size_t m_componentSlots = 0;
915};
916
917} // namespace
918
919
920const std::string* ELEMENT_BASE::FindProp( const std::string& aKey ) const
921{
922 for( const auto& [key, value] : props )
923 {
924 if( key == aKey )
925 return &value;
926 }
927
928 return nullptr;
929}
930
931
932std::vector<uint8_t> ELEMENT_BASE::Picture() const
933{
934 std::vector<uint8_t> data;
935 const std::string* encoded = FindProp( "JPEG_PICTURE" );
936
937 if( !encoded )
938 return data;
939
940 // Base64 with '_' standing in for '+'
941 std::vector<uint8_t> text( encoded->begin(), encoded->end() );
942 std::replace( text.begin(), text.end(), uint8_t( '_' ), uint8_t( '+' ) );
943 base64::decode( text, data );
944 return data;
945}
946
947
948std::optional<int64_t> ELEMENT_BASE::PolygonId() const
949{
950 const std::string* value = FindProp( "POLYGONID" );
951 int64_t id = 0;
952
953 if( !value || !toInt( *value, id ) )
954 return std::nullopt;
955
956 return id;
957}
958
959
960bool ELEMENT_BASE::FlagProp( const std::string& aKey ) const
961{
962 const std::string* value = FindProp( aKey );
963
964 if( !value )
965 return false;
966
967 wxString word = ToWx( *value ).Trim().Trim( false ).Upper();
968
969 return word == wxS( "TRUE" ) || word == wxS( "YES" ) || word == wxS( "1" ) || word == wxS( "JA" )
970 || word == wxS( "OUI" ) || word == wxS( "OK" );
971}
972
973
974std::optional<std::pair<int32_t, int32_t>> ELEMENT_BASE::TextRightEnd() const
975{
976 const std::string* arxy = FindProp( "ARXY" );
977
978 if( !arxy )
979 return std::nullopt;
980
981 wxString value( *arxy );
982 long endX = 0;
983 long endY = 0;
984
985 if( !value.Contains( wxS( "|" ) ) || !value.BeforeFirst( '|' ).ToLong( &endX )
986 || !value.AfterFirst( '|' ).ToLong( &endY ) )
987 {
988 return std::nullopt;
989 }
990
991 return std::make_pair( int32_t( endX ), int32_t( endY ) );
992}
993
994
995const std::string* PROJECT::FindProperty( const std::string& aKey ) const
996{
997 for( const auto& [key, value] : settings.properties )
998 {
999 if( ToWx( key ).Trim().Trim( false ).IsSameAs( ToWx( aKey ), false ) )
1000 return &value;
1001 }
1002
1003 return nullptr;
1004}
1005
1006
1007std::optional<wxString> PROJECT::FunctionText( const TEXT& aText, bool aSchematic ) const
1008{
1009 // The change timestamp is the later of the file time and the previous save time in property 1218
1010 auto changed = [&]()
1011 {
1012 wxDateTime when = fileModified;
1013 double days = 0.0;
1014
1015 if( const std::string* saved = FindProperty( "1218" ) )
1016 {
1017 wxString value = ToWx( *saved );
1018 value.Replace( wxS( "," ), wxS( "." ) );
1019
1020 // TDateTime counts days from 1899-12-30, which is Julian day 2415018.5
1021 if( value.ToCDouble( &days ) && days > 0.0 )
1022 {
1023 wxDateTime previous( days + 2415018.5 );
1024
1025 if( !when.IsValid() || previous.IsLaterThan( when ) )
1026 when = previous;
1027 }
1028 }
1029
1030 return when;
1031 };
1032
1033 switch( TEXT_FUNCTION( aText.function ) )
1034 {
1036 {
1037 wxDateTime when = changed();
1038 return when.IsValid() ? when.Format( wxS( "%d.%m.%Y" ) ) : wxString();
1039 }
1040
1042 return fileModified.IsValid() ? fileModified.Format( wxS( "%H:%M" ) ) : wxString();
1043
1044 // Output stamps stay live; KiCad formats them as ISO date and HH:MM:SS
1045 case TEXT_FUNCTION::OUTPUT_DATE: return wxString( wxS( "${CURRENT_DATE}" ) );
1046 case TEXT_FUNCTION::OUTPUT_TIME: return wxString( wxS( "${CURRENT_TIME_HH_MM_SS}" ) );
1047
1048 // Vector output always shows the unscaled drawing; printing formats it with two decimals
1049 case TEXT_FUNCTION::SCALE: return wxString( aSchematic ? wxS( "100.00%" ) : wxS( "100%" ) );
1050
1051 case TEXT_FUNCTION::PROJECT_NAME: return wxFileName( fileName ).GetName();
1053
1055 return aSchematic ? std::optional<wxString>( wxS( "${#}" ) ) : std::nullopt;
1056
1058 return aSchematic ? std::optional<wxString>( wxS( "${SHEETNAME}" ) ) : std::nullopt;
1059
1060 default: return std::nullopt;
1061 }
1062}
1063
1064
1065const ELEMENT* PROJECT::FindSignal( uint16_t aId ) const
1066{
1067 if( aId == 0 )
1068 return nullptr;
1069
1070 for( const ELEMENT& e : signals )
1071 {
1072 if( e.type == ELEMENT_TYPE::SIGNAL && e.signal && e.base.signal == aId )
1073 return &e;
1074 }
1075
1076 return nullptr;
1077}
1078
1079
1080namespace
1081{
1082
1083struct LANGUAGE_INFO
1084{
1086 const char* key;
1087};
1088
1089
1090const LANGUAGE_INFO LANGUAGES[] = { { TEXT_LANGUAGE::GERMAN, "$%&DEUTSCH" },
1091 { TEXT_LANGUAGE::ENGLISH, "$%&ENGLISH" },
1092 { TEXT_LANGUAGE::FRENCH, "$%&FRANCAIS" } };
1093
1094
1095template <typename LIST, typename FN>
1096void forEachText( LIST& aList, FN&& aFn )
1097{
1098 for( auto& e : aList )
1099 {
1100 if( e.type == ELEMENT_TYPE::TEXT )
1101 aFn( e );
1102
1103 forEachText( e.children, aFn );
1104
1105 if( e.symbol )
1106 forEachText( e.symbol->children, aFn );
1107
1108 if( e.component )
1109 {
1110 forEachText( e.component->packageItems, aFn );
1111 forEachText( e.component->symbols, aFn );
1112 }
1113
1114 if( e.signal )
1115 {
1116 forEachText( e.signal->connections, aFn );
1117 forEachText( e.signal->tracks, aFn );
1118 }
1119 }
1120}
1121
1122
1123template <typename PROJ, typename FN>
1124void forEachProjectText( PROJ& aProject, FN&& aFn )
1125{
1126 forEachText( aProject.signals, aFn );
1127 forEachText( aProject.components, aFn );
1128 forEachText( aProject.schematicItems, aFn );
1129 forEachText( aProject.boardItems, aFn );
1130}
1131
1132
1133// Variants only ever replace literal text; other functions are computed from their owner
1134std::optional<std::string> variant( const ELEMENT& aText, const LANGUAGE_INFO& aLanguage )
1135{
1136 if( aText.text.function != uint8_t( TEXT_FUNCTION::LITERAL ) )
1137 return std::nullopt;
1138
1139 const std::string* value = aText.base.FindProp( aLanguage.key );
1140
1141 if( !value || value->empty() )
1142 return std::nullopt;
1143
1144 // Spaces are stored as 0x7f inside variants
1145 std::string text = *value;
1146 std::replace( text.begin(), text.end(), '\x7f', ' ' );
1147 return text;
1148}
1149
1150} // namespace
1151
1152
1154{
1155 bool automatic = false;
1156
1157 forEachProjectText( *this,
1158 [&]( const ELEMENT& aText )
1159 {
1160 wxString text = ToWx( aText.text.text ).Trim().Trim( false ).Upper();
1161 automatic |= text == wxS( "AUTOLANGUAGE=TRUE" );
1162 } );
1163
1164 // Without the switch the source program shows stored text whatever language the file names
1165 if( !automatic || !settings.textLanguage )
1166 return;
1167
1168 for( const LANGUAGE_INFO& lang : LANGUAGES )
1169 {
1170 if( lang.language != *settings.textLanguage )
1171 continue;
1172
1173 forEachProjectText( *this,
1174 [&]( ELEMENT& aText )
1175 {
1176 if( std::optional<std::string> text = variant( aText, lang ) )
1177 aText.text.text = *text;
1178 } );
1179 }
1180}
1181
1182
1183wxString PadNumber( const ELEMENT& aPad )
1184{
1185 if( const std::string* name = aPad.base.FindProp( "PADNAME" ) )
1186 return ToWx( *name );
1187
1188 if( aPad.pad.number )
1189 return wxString::Format( wxS( "%u" ), aPad.pad.number );
1190
1191 return wxEmptyString;
1192}
1193
1194
1195PROJECT ParseBuffer( const std::vector<uint8_t>& aData )
1196{
1197 PARSER parser( aData );
1198 return parser.Parse();
1199}
1200
1201
1202PROJECT ParseFile( const wxString& aFileName )
1203{
1204 wxFFile file( aFileName, wxS( "rb" ) );
1205
1206 if( !file.IsOpened() )
1207 THROW_IO_ERROR( wxString::Format( _( "Cannot open file '%s'." ), aFileName ) );
1208
1209 std::vector<uint8_t> data( file.Length() );
1210
1211 if( !data.empty() && file.Read( data.data(), data.size() ) != data.size() )
1212 THROW_IO_ERROR( wxString::Format( _( "Cannot read file '%s'." ), aFileName ) );
1213
1214 PROJECT project = ParseBuffer( data );
1215 wxFileName fn( aFileName );
1216
1217 project.fileName = fn.GetFullName();
1218 project.fileModified = fn.GetModificationTime();
1219 return project;
1220}
1221
1222
1223bool LooksLikeProject( const wxString& aFileName )
1224{
1225 wxFileName fn( aFileName );
1226
1227 if( fn.GetExt().CmpNoCase( wxS( "T3001" ) ) != 0 )
1228 return false;
1229
1230 wxFFile file( aFileName, wxS( "rb" ) );
1231
1232 if( !file.IsOpened() )
1233 return false;
1234
1235 uint8_t head[8];
1236
1237 if( file.Read( head, sizeof( head ) ) != sizeof( head ) )
1238 return false;
1239
1240 int32_t version = int32_t( head[0] | ( head[1] << 8 ) | ( head[2] << 16 ) | ( uint32_t( head[3] ) << 24 ) );
1241 int32_t fontLen = int32_t( head[4] | ( head[5] << 8 ) | ( head[6] << 16 ) | ( uint32_t( head[7] ) << 24 ) );
1242
1243 return version > 0 && version < 0x10000 && fontLen >= 0 && fontLen < 256;
1244}
1245
1246
1247wxString ToWx( const std::string& aRaw )
1248{
1249 static wxCSConv conv( wxFONTENCODING_CP1252 );
1250 return wxString( aRaw.data(), conv, aRaw.size() );
1251}
1252
1253} // namespace TARGET3001
const char * name
static int toInt(const wxString &aToken)
Parse a token as an integer using the C locale, returning 0 on failure.
#define _(s)
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
PARSE_RESULT Parse(const std::string &aString, NOTATION aNotation=NOTATION::SI, SIM_VALUE::TYPE aValueType=SIM_VALUE::TYPE_FLOAT)
Reader for TARGET 3001!
wxString PadNumber(const ELEMENT &aPad)
Number of a pad element in KiCad, its PADNAME when present, else its stored number.
PROJECT ParseBuffer(const std::vector< uint8_t > &aData)
Parse a project held in memory.
PROJECT ParseFile(const wxString &aFileName)
Parse a complete .T3001 file.
bool LooksLikeProject(const wxString &aFileName)
Cheap check used by the plugin managers: the extension matches and the header is plausible.
wxString ToWx(const std::string &aRaw)
Convert a stored ANSI string to a wxString.
ELEMENT_TYPE
Element class tags as stored in the file.
constexpr int BOARD_LAYER_COUNT
Board layers 0..99 carry a per-project function; 100 and above have fixed meanings.
void decode(const std::vector< uint8_t > &aInput, std::vector< uint8_t > &aOutput)
Definition base64.cpp:113
static std::vector< std::string > split(const std::string &aStr, const std::string &aDelim)
Split the input string into a vector of output strings.
double radius
double centerY
double centerX
double width
std::optional< uint32_t > extra
uint16_t component
ID of the owning component (a component stores its own), 0 for none.
uint16_t signal
ID of the owning signal (a signal stores its own), 0 for none.
std::vector< std::pair< std::string, std::string > > props
Free-form key/value properties in file order.
uint8_t classTag
repeats the element's class tag
FIDUCIAL fiducial
ELEMENT_BASE base
DRC_MARKER marker
ELEMENT_TYPE type
std::shared_ptr< COMPONENT > component
std::shared_ptr< SYMBOL > symbol
RECTANGLE rectangle
TRIANGLE triangle
std::shared_ptr< SIGNAL > signal
std::shared_ptr< PACKAGE > package
std::vector< ELEMENT > children
Children of a pin (its number text).
uint8_t kind
FIDUCIAL_KIND.
int32_t width
int32_t clearance
int32_t controlX
int32_t controlY
std::vector< uint8_t > Picture() const
Encoded image a rectangle shows stretched over its area instead of its fill, empty for none.
std::optional< int64_t > PolygonId() const
ID of the signal polygon whose stored fill this element is part of, if any.
bool FlagProp(const std::string &aKey) const
True when property aKey holds one of the format's boolean true words.
uint16_t signal
ID of the owning signal (a signal stores its own), 0 for none.
std::vector< std::pair< std::string, std::string > > props
Free-form key/value properties in file order.
std::optional< std::pair< int32_t, int32_t > > TextRightEnd() const
Right end of right-aligned text from its ARXY property, in file coordinates.
const std::string * FindProp(const std::string &aKey) const
Return the value of the first property named aKey, if any.
One element of any class.
Copper polygon of a signal, stored in a "$%&POLY" signal property.
bool thermals
own pads join by spokes rather than solidly
void ApplyTextLanguage()
Replace literal texts by their variant in the project's stored language when a text reads AUTOLANGUAG...
const std::string * FindProperty(const std::string &aKey) const
Value of project property aKey, compared case-insensitively.
wxString fileName
source file name without directory, empty for a buffer
const ELEMENT * FindSignal(uint16_t aId) const
Signal element whose ID is aId, or nullptr.
std::vector< ELEMENT > signals
PROJECT_SETTINGS settings
wxDateTime fileModified
source file modification time, invalid for a buffer
std::optional< wxString > FunctionText(const TEXT &aText, bool aSchematic) const
Text that a computed text function shows, where KiCad has an equivalent.
wxString text
double height
bool mirrored
double width
int direction
0..3, multiplied by 90 degrees counterclockwise
VECTOR2I end