KiCad PCB EDA Suite
Loading...
Searching...
No Matches
altium_parser_utils.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) 2021 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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include "altium_parser_utils.h"
22
23#include <string_utils.h>
24#include <lib_id.h>
25#include <trigo.h>
26#include <math/util.h>
27#include <wx/arrstr.h>
28
29LIB_ID AltiumToKiCadLibID( const wxString& aLibName, const wxString& aLibReference )
30{
31 wxString libName = LIB_ID::FixIllegalChars( aLibName, true );
32 wxString libReference = EscapeString( aLibReference, CTX_LIBID );
33
34 wxString key = !libName.empty() ? ( libName + ":" + libReference ) : libReference;
35
36 LIB_ID libId;
37 libId.Parse( key, true );
38
39 return libId;
40}
41
42
43wxString AltiumPropertyToKiCadString( const wxString& aString )
44{
45 wxString output;
46 wxString tempString;
47 bool hasPrev = false;
48 wxUniChar prev;
49
50 for( wxString::const_iterator it = aString.begin(); it != aString.end(); ++it )
51 {
52 char ch = 0;
53
54 if( (*it).GetAsChar( &ch ) )
55 {
56 if( ch == '\\' )
57 {
58 if( hasPrev )
59 {
60 tempString += prev;
61 hasPrev = false;
62 }
63
64 continue; // Backslash is ignored and not added to the output
65 }
66 }
67
68 if( hasPrev ) // Two letters in a row with no backslash
69 {
70 if( !tempString.empty() )
71 {
72 output += "~{" + tempString + "}";
73 tempString.Clear();
74 }
75
76 output += prev;
77 }
78
79 prev = *it;
80 hasPrev = true;
81 }
82
83 // Append any leftover escaped string
84 if( !tempString.IsEmpty() )
85 output += "~{" + tempString + "}";
86
87 if( hasPrev )
88 output += prev;
89
90 return output;
91}
92
93
94wxString AltiumEscapeTextVars( const wxString& aText )
95{
96 wxString result;
97 int depth = 0;
98
99 for( size_t i = 0; i < aText.length(); i++ )
100 {
101 wxUniChar ch = aText[i];
102
103 // KiCad copies an escaped reference through its closing brace, so only the outermost one is escaped
104 if( depth == 0 && ( ch == '$' || ch == '@' ) && i + 1 < aText.length() && aText[i + 1] == '{' )
105 {
106 result += '\\';
107 result += ch;
108 result += '{';
109 depth = 1;
110 i++;
111 continue;
112 }
113
114 if( depth > 0 && ch == '{' )
115 depth++;
116 else if( depth > 0 && ch == '}' )
117 depth--;
118
119 result += ch;
120 }
121
122 return result;
123}
124
125
126// https://www.altium.com/documentation/altium-designer/sch-obj-textstringtext-string-ad#!special-strings
127wxString AltiumSchSpecialStringsToKiCadVariables( const wxString& aString,
128 const std::map<wxString, wxString>& aOverrides,
129 std::set<wxString>* aUnmapped )
130{
131 if( aString.IsEmpty() || aString.at( 0 ) != '=' )
132 return AltiumEscapeTextVars( aString );
133
134 wxString result;
135
136 // adjacent quoted fragments are one literal, '$'+'{A}' included
137 wxString literal;
138
139 size_t start = 1;
140 size_t delimiter = 0;
141 size_t escaping_start = 0;
142 do
143 {
144 delimiter = aString.find( "+", start );
145 escaping_start = aString.find( "'", start );
146
147 if( escaping_start < delimiter )
148 {
149 size_t text_start = escaping_start + 1;
150 size_t escaping_end = aString.find( "'", text_start );
151
152 if( escaping_end == wxString::npos )
153 {
154 escaping_end = aString.size();
155 }
156
157 literal += aString.substr( text_start, escaping_end - text_start );
158
159 start = escaping_end + 1;
160 }
161 else
162 {
163 wxString specialString =
164 aString.substr( start, delimiter - start ).Trim().Trim( false );
165
166 if( specialString.StartsWith( "\"" ) && specialString.EndsWith( "\"" ) )
167 specialString = specialString.Mid( 1, specialString.Length() - 2 );
168
169 if( !specialString.IsEmpty() )
170 {
171 // Note: Altium variable references are case-insensitive. KiCad matches
172 // case-sensitive OR to all-upper-case, so make the references all-upper-case.
173 specialString.UpperCase();
174
175 auto overrideIt = aOverrides.find( specialString );
176
177 if( overrideIt != aOverrides.end() )
178 specialString = overrideIt->second;
179 else if( aUnmapped )
180 aUnmapped->insert( specialString );
181
182 result += AltiumEscapeTextVars( literal ) + wxString::Format( wxT( "${%s}" ), specialString );
183 literal.clear();
184 }
185
186 start = delimiter + 1;
187 }
188 } while( delimiter != wxString::npos );
189
190 result += AltiumEscapeTextVars( literal );
191
192 return result;
193}
194
195
196// https://www.altium.com/documentation/altium-designer/text-objects-pcb
197wxString AltiumPcbSpecialStringsToKiCadStrings( const wxString& aString,
198 const std::map<wxString, wxString>& aOverrides,
199 std::set<wxString>* aUnmapped )
200{
201 if( aString.IsEmpty() )
202 return aString;
203
204 // Convert a 'special string' to a KiCad variable, substituting any override.
205 const auto getVariable = [&]( const wxString& aSpecialString )
206 {
207 wxString str = aSpecialString;
208 str.UpperCase(); // matching is implemented using upper case strings
209
210 auto it = aOverrides.find( str );
211
212 if( it != aOverrides.end() )
213 str = it->second;
214 else if( aUnmapped )
215 aUnmapped->insert( str );
216
217 return wxString::Format( wxT( "${%s}" ), str );
218 };
219
220 // special case: string starts with dot -> whole string is special string, unless it is an assignment
221 if( aString.at( 0 ) == '.' )
222 {
223 wxString specialString = aString.substr( 1 );
224
225 if( specialString.Contains( '=' ) )
226 return aString;
227
228 return getVariable( specialString );
229 }
230
231 // Strings can also have one or more special strings using apostrophes to
232 // delineate them, e.g. "foo '.bar' '.baz' = '.qux' quux"
233
234 // In the common case, the string is a simple string with no special strings,
235 // so bail out early.
236 if( !aString.Contains( "'." ) )
237 {
238 return aString;
239 }
240
241 wxString stringCopy = aString;
242
243 // Given a position of a dot, check if it is a special string variable
244 // and replace it with a variable name if defined.
245 const auto tryReplacement = [&]( wxString& aStr, unsigned aDotPos )
246 {
247 // Check that the dot has an apostrophe before it, if not, it's just a dot
248 if( aDotPos == 0 || aStr.at( aDotPos - 1 ) != '\'' )
249 return;
250
251 // Scan forward for the next apostrophe
252 size_t apostrophePos = aStr.find( '\'', aDotPos + 1 );
253
254 // Didn't find it
255 if( apostrophePos == wxString::npos )
256 return;
257
258 // Extract the special string
259 wxString specialString = aStr.substr( aDotPos + 1, apostrophePos - aDotPos - 1 );
260 wxString replacement = getVariable( specialString );
261
262 aStr.replace( aDotPos - 1, apostrophePos - aDotPos + 2, replacement );
263 };
264
265 // Work backwards through the string checking any dots
266 // (so we don't mess up the positions of the dots as we replace them)
267 for( size_t pos = stringCopy.size() - 1; pos > 0; --pos )
268 {
269 if( stringCopy[pos] == '.' )
270 {
271 tryReplacement( stringCopy, pos );
272 }
273 }
274
275 return stringCopy;
276}
277
278
279wxString AltiumPinNamesToKiCad( wxString& aString )
280{
281 if( aString.IsEmpty() )
282 return wxEmptyString;
283
284 wxString rest;
285
286 if( aString.StartsWith( '\\', &rest ) && !rest.Contains( '\\' ) )
287 return "~{" + rest + "}";
288
289 return AltiumPropertyToKiCadString( aString );
290}
291
292
293wxString AltiumPinDesignatorToKiCad( const wxString& aDesignator )
294{
295 wxString designator = aDesignator;
296 designator.Trim( true ).Trim( false );
297
298 if( !designator.Contains( wxT( "," ) ) )
299 return designator;
300
301 // Rebuild as KiCad stacked notation "[a,b,c]". If trimming collapses the list to a
302 // single token, emit the bare token so well-formed single designators never get wrapped.
303 wxArrayString cleaned;
304
305 for( wxString token : wxSplit( designator, ',', '\0' ) )
306 {
307 token.Trim( true ).Trim( false );
308
309 if( !token.IsEmpty() )
310 cleaned.Add( EscapeStackedPinItem( token ) );
311 }
312
313 if( cleaned.IsEmpty() )
314 return designator;
315
316 if( cleaned.GetCount() == 1 )
317 return cleaned[0];
318
319 return wxT( "[" ) + wxJoin( cleaned, ',', '\0' ) + wxT( "]" );
320}
321
322
323VECTOR2I AltiumGetEllipticalPos( double aMajor, double aMinor, double aAngleRadians )
324{
325 if( aMajor == 0 || aMinor == 0 )
326 return VECTOR2I( 0, 0 );
327
328 double numerator = aMajor * aMinor;
329 double majorTerm = aMajor * sin( aAngleRadians );
330 double minorTerm = aMinor * cos( aAngleRadians );
331 double denominator = sqrt( majorTerm * majorTerm + minorTerm * minorTerm );
332
333 double radius = numerator / denominator;
334
335 VECTOR2I retval( KiROUND( radius * cos( aAngleRadians ) ),
336 KiROUND( radius * sin( aAngleRadians ) ) );
337
338 return retval;
339
340}
wxString AltiumPinDesignatorToKiCad(const wxString &aDesignator)
Convert an Altium pin designator string to the equivalent KiCad pin number.
wxString AltiumPcbSpecialStringsToKiCadStrings(const wxString &aString, const std::map< wxString, wxString > &aOverrides, std::set< wxString > *aUnmapped)
Convert the special strings in Altium PCB text to KiCad variables.
wxString AltiumSchSpecialStringsToKiCadVariables(const wxString &aString, const std::map< wxString, wxString > &aOverrides, std::set< wxString > *aUnmapped)
Convert the special strings in Altium schematic text to KiCad variables.
wxString AltiumPropertyToKiCadString(const wxString &aString)
wxString AltiumEscapeTextVars(const wxString &aText)
Escape the KiCad variables and expressions in literal Altium text, which Altium shows as typed.
wxString AltiumPinNamesToKiCad(wxString &aString)
VECTOR2I AltiumGetEllipticalPos(double aMajor, double aMinor, double aAngleRadians)
LIB_ID AltiumToKiCadLibID(const wxString &aLibName, const wxString &aLibReference)
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:982
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int Parse(const UTF8 &aId, bool aFix=false)
Parse LIB_ID with the information from aId.
Definition lib_id.cpp:65
static UTF8 FixIllegalChars(const UTF8 &aLibItemName, bool aLib)
Replace illegal LIB_ID item name characters with underscores '_'.
Definition lib_id.cpp:205
wxString EscapeStackedPinItem(const wxString &aPinNumber)
Escape the characters that carry structural meaning inside stacked pin notation ('[',...
wxString EscapeString(const wxString &aSource, ESCAPE_CONTEXT aContext)
The Escape/Unescape routines use HTML-entity-reference-style encoding to handle characters which are:...
@ CTX_LIBID
int radius
wxString result
Test unit parsing edge cases and error handling.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708