KiCad PCB EDA Suite
Loading...
Searching...
No Matches
library_table.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 * @author Jon Evans <[email protected]>
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#include <boost/lexical_cast.hpp>
22
23#include <cstdint>
24#include <limits>
25
26#include <kiplatform/io.h>
29#include <richio.h>
30#include <string_utils.h>
31#include <trace_helpers.h>
32#include <wx_filename.h>
33#include <xnode.h>
35
36#include <wx/buffer.h>
37#include <wx/ffile.h>
38
39
40const wxString LIBRARY_TABLE_ROW::TABLE_TYPE_NAME = wxT( "Table" );
41
42
44{
45 return m_scope == aOther.m_scope
46 && m_nickname == aOther.m_nickname
47 && m_uri == aOther.m_uri
48 && m_type == aOther.m_type
49 && m_options == aOther.m_options
50 && m_description == aOther.m_description
51 && m_disabled == aOther.m_disabled
52 && m_hidden == aOther.m_hidden;
53}
54
55
56std::map<std::string, UTF8> LIBRARY_TABLE_ROW::GetOptionsMap() const
57{
59}
60
61
62LIBRARY_TABLE::LIBRARY_TABLE( const wxFileName &aPath, LIBRARY_TABLE_SCOPE aScope ) :
63 m_scope( aScope )
64{
66
67 wxFileName fn( aPath );
69 m_path = fn.GetAbsolutePath();
70
71 if( !fn.FileExists() )
72 {
73 m_ok = false;
74 m_errorDescription = wxString::Format( _( "The library table path '%s' does not exist" ),
75 fn.GetFullPath() );
76 return;
77 }
78
79 tl::expected<LIBRARY_TABLE_IR, LIBRARY_PARSE_ERROR> ir = parser.Parse( m_path.ToStdString() );
80
81 if( ir.has_value() )
82 {
83 m_ok = initFromIR( *ir );
84 }
85 else
86 {
87 m_ok = false;
88 m_errorDescription = ir.error().description;
89 }
90}
91
92
97LIBRARY_TABLE::LIBRARY_TABLE( bool aFromClipboard, const wxString &aBuffer, LIBRARY_TABLE_SCOPE aScope ) :
98 m_path( wxEmptyString ),
99 m_scope( aScope )
100{
102
103 tl::expected<LIBRARY_TABLE_IR, LIBRARY_PARSE_ERROR> ir = parser.ParseBuffer( aBuffer.ToStdString() );
104
105 if( ir.has_value() )
106 {
107 m_ok = initFromIR( *ir );
108 }
109 else
110 {
111 m_ok = false;
112 m_errorDescription = ir.error().description;
113 }
114}
115
116
117bool LIBRARY_TABLE::operator==( const LIBRARY_TABLE& aOther ) const
118{
119 return m_path == aOther.m_path
120 && m_scope == aOther.m_scope
121 && m_type == aOther.m_type
122 && m_version == aOther.m_version
123 && m_rows == aOther.m_rows;
124}
125
126
128{
129 m_type = aIR.type;
130
131 try
132 {
133 m_version = boost::lexical_cast<int>( aIR.version );
134 }
135 catch( const boost::bad_lexical_cast & )
136 {
137 m_version = std::nullopt;
138 }
139
140 for( const LIBRARY_TABLE_ROW_IR& row : aIR.rows )
141 addRowFromIR( row );
142
143 return true;
144}
145
146
148{
150
151 row.m_nickname = wxString::FromUTF8( aIR.nickname );
152 row.m_uri = wxString::FromUTF8( aIR.uri );
153 row.m_type = wxString::FromUTF8( aIR.type );
154 row.m_options = wxString::FromUTF8( aIR.options );
155 row.m_description = wxString::FromUTF8( aIR.description );
156 row.m_hidden = aIR.hidden;
157 row.m_disabled = aIR.disabled;
158 row.m_ok = true;
159 row.m_scope = m_scope;
160
161 m_rows.emplace_back( row );
162 return true;
163}
164
165
167{
168 static const std::map<LIBRARY_TABLE_TYPE, wxString> types = {
169 { LIBRARY_TABLE_TYPE::SYMBOL, "sym_lib_table" },
170 { LIBRARY_TABLE_TYPE::FOOTPRINT, "fp_lib_table" },
171 { LIBRARY_TABLE_TYPE::DESIGN_BLOCK, "design_block_lib_table" }
172 };
173
174 wxCHECK( types.contains( Type() ), /* void */ );
175
176 XNODE self( wxXML_ELEMENT_NODE, types.at( Type() ) );
177
178 // TODO(JE) library tables - version management?
179 self.AddAttribute( "version", 7 );
180
181 for( const LIBRARY_TABLE_ROW& row : Rows() )
182 {
183 wxString uri = row.URI();
184 uri.Replace( '\\', '/' );
185
186 XNODE* rowNode = new XNODE( wxXML_ELEMENT_NODE, "lib" );
187 rowNode->AddAttribute( "name", row.Nickname() );
188 rowNode->AddAttribute( "type", row.Type() );
189 rowNode->AddAttribute( "uri", uri );
190 rowNode->AddAttribute( "options", row.Options() );
191 rowNode->AddAttribute( "descr", row.Description() );
192
193 if( row.Disabled() )
194 rowNode->AddChild( new XNODE( wxXML_ELEMENT_NODE, "disabled" ) );
195
196 if( row.Hidden() )
197 rowNode->AddChild( new XNODE( wxXML_ELEMENT_NODE, "hidden" ) );
198
199 self.AddChild( rowNode );
200 }
201
202 self.Format( aOutput );
203}
204
205
207{
208 LIBRARY_TABLE_ROW row = {};
209
210 row.SetScope( m_scope );
211 row.SetOk();
212
213 return row;
214}
215
216
218{
219 return Rows().emplace_back( MakeRow() );
220}
221
222
223bool LIBRARY_TABLE::HasRow( const wxString& aNickname ) const
224{
225 for( const LIBRARY_TABLE_ROW& row : m_rows )
226 {
227 if( row.Nickname() == aNickname )
228 return true;
229 }
230
231 return false;
232}
233
234
235bool LIBRARY_TABLE::HasRowWithURI( const wxString& aUri, const PROJECT& aProject,
236 bool aSubstituted ) const
237{
238 for( const LIBRARY_TABLE_ROW& row : m_rows )
239 {
240 if( !aSubstituted && row.URI() == aUri )
241 return true;
242
243 if( aSubstituted && LIBRARY_MANAGER::ExpandURI( row.URI(), aProject ) == aUri )
244 return true;
245 }
246
247 return false;
248}
249
250
251std::optional<LIBRARY_TABLE_ROW*> LIBRARY_TABLE::Row( const wxString& aNickname )
252{
253 for( LIBRARY_TABLE_ROW& row : m_rows )
254 {
255 if( row.Nickname() == aNickname )
256 return &row;
257 }
258
259 return std::nullopt;
260}
261
262
263std::optional<const LIBRARY_TABLE_ROW*> LIBRARY_TABLE::Row( const wxString& aNickname ) const
264{
265 for( const LIBRARY_TABLE_ROW& row : m_rows )
266 {
267 if( row.Nickname() == aNickname )
268 return &row;
269 }
270
271 return std::nullopt;
272}
273
274
276{
277 wxLogTrace( traceLibraries, "Saving %s", Path() );
278 wxFileName fn( Path() );
279 // This should already be normalized, but just in case...
280 fn.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS );
281
282 // Global user data with no other recovery path: keep a rotating .bak sibling so the
283 // user can recover from logical corruption outside our fsync window.
284 wxFFile existing( fn.GetFullPath(), wxT( "rb" ) );
285
286 if( existing.IsOpened() )
287 {
288 wxFileOffset rawLen = existing.Length();
289
290 if( rawLen >= 0
291 && static_cast<uint64_t>( rawLen ) <= std::numeric_limits<size_t>::max() )
292 {
293 size_t len = static_cast<size_t>( rawLen );
294 wxMemoryBuffer buf;
295 void* dst = len > 0 ? buf.GetWriteBuf( len ) : nullptr;
296
297 if( len == 0 || existing.Read( dst, len ) == len )
298 {
299 buf.SetDataLen( len );
300 existing.Close();
301
302 wxString bakPath = fn.GetFullPath() + wxT( ".bak" );
303 wxString bakError;
304
305 if( !KIPLATFORM::IO::AtomicWriteFile( bakPath, buf.GetData(), len, &bakError ) )
306 {
307 // Non-fatal: the original is still on disk and the atomic save below
308 // is safe.
309 wxLogTrace( traceLibraries,
310 "Could not rotate library table backup to '%s': %s", bakPath,
311 bakError );
312 }
313 }
314 }
315 }
316
317 try
318 {
319 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( fn.GetFullPath(), KICAD_FORMAT::FORMAT_MODE::LIBRARY_TABLE );
320 Format( &formatter );
321 formatter.Finish();
322 }
323 catch( IO_ERROR& e )
324 {
325 wxLogTrace( traceLibraries, "Exception while saving: %s", e.What() );
326 return tl::unexpected( LIBRARY_ERROR( e.What() ) );
327 }
328
329 return LIBRARY_RESULT<void>();
330}
331
332
333#define OPT_SEP '|'
334
335std::map<std::string, UTF8> LIBRARY_TABLE::ParseOptions( const std::string& aOptionsList )
336{
337 std::map<std::string, UTF8> props;
338
339 if( aOptionsList.size() )
340 {
341 const char* cp = &aOptionsList[0];
342 const char* end = cp + aOptionsList.size();
343
344 std::string pair;
345
346 // Parse all name=value pairs
347 while( cp < end )
348 {
349 pair.clear();
350
351 // Skip leading white space.
352 while( cp < end && isspace( *cp ) )
353 ++cp;
354
355 // Find the end of pair/field
356 while( cp < end )
357 {
358 if( *cp == '\\' && cp + 1 < end && cp[1] == OPT_SEP )
359 {
360 ++cp; // skip the escape
361 pair += *cp++; // add the separator
362 }
363 else if( *cp == OPT_SEP )
364 {
365 ++cp; // skip the separator
366 break; // process the pair
367 }
368 else
369 {
370 pair += *cp++;
371 }
372 }
373
374 // stash the pair
375 if( pair.size() )
376 {
377 // first equals sign separates 'name' and 'value'.
378 size_t eqNdx = pair.find( '=' );
379
380 if( eqNdx != pair.npos )
381 {
382 std::string name = pair.substr( 0, eqNdx );
383 std::string value = pair.substr( eqNdx + 1 );
384 props[name] = value;
385 }
386 else
387 {
388 props[pair] = ""; // property is present, but with no value.
389 }
390 }
391 }
392 }
393
394 return props;
395}
396
397
398UTF8 LIBRARY_TABLE::FormatOptions( const std::map<std::string, UTF8>* aProperties )
399{
400 UTF8 ret;
401
402 if( aProperties )
403 {
404 for( std::map<std::string, UTF8>::const_iterator it = aProperties->begin();
405 it != aProperties->end(); ++it )
406 {
407 const std::string& name = it->first;
408
409 const UTF8& value = it->second;
410
411 if( ret.size() )
412 ret += OPT_SEP;
413
414 ret += name;
415
416 // the separation between name and value is '='
417 if( value.size() )
418 {
419 ret += '=';
420
421 for( std::string::const_iterator si = value.begin(); si != value.end(); ++si )
422 {
423 // escape any separator in the value.
424 if( *si == OPT_SEP )
425 ret += '\\';
426
427 ret += *si;
428 }
429 }
430 }
431 }
432
433 return ret;
434}
const char * name
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
static wxString ExpandURI(const wxString &aShortURI, const PROJECT &aProject)
tl::expected< LIBRARY_TABLE_IR, LIBRARY_PARSE_ERROR > ParseBuffer(const std::string &aBuffer)
tl::expected< LIBRARY_TABLE_IR, LIBRARY_PARSE_ERROR > Parse(const std::filesystem::path &aPath)
LIBRARY_TABLE_ROW()=default
void SetOk(bool aOk=true)
bool operator==(const LIBRARY_TABLE_ROW &aOther) const
std::map< std::string, UTF8 > GetOptionsMap() const
static const wxString TABLE_TYPE_NAME
void SetScope(LIBRARY_TABLE_SCOPE aScope)
LIBRARY_TABLE_SCOPE m_scope
LIBRARY_RESULT< void > Save()
bool operator==(const LIBRARY_TABLE &aOther) const
void Format(OUTPUTFORMATTER *aOutput) const
static std::map< std::string, UTF8 > ParseOptions(const std::string &aOptionsList)
LIBRARY_TABLE_TYPE Type() const
LIBRARY_TABLE_TYPE m_type
What type of content this table contains (footprint, symbol, design block, etc)
std::optional< LIBRARY_TABLE_ROW * > Row(const wxString &aNickname)
LIBRARY_TABLE_ROW & InsertRow()
Builds a new row and inserts it at the end of the table; returning a reference to the row.
static UTF8 FormatOptions(const std::map< std::string, UTF8 > *aProperties)
const wxString & Path() const
wxString m_path
The full path to the file this table was parsed from, if any.
wxString m_errorDescription
LIBRARY_TABLE_ROW MakeRow() const
Builds a new row that is suitable for this table (does not insert it)
bool HasRow(const wxString &aNickname) const
LIBRARY_TABLE(const wxFileName &aPath, LIBRARY_TABLE_SCOPE aScope)
Creates a library table from a file on disk.
bool HasRowWithURI(const wxString &aUri, const PROJECT &aProject, bool aSubstituted=false) const
Returns true if the given (fully-expanded) URI exists as a library in this table.
const std::deque< LIBRARY_TABLE_ROW > & Rows() const
std::optional< int > m_version
The format version, if present in the parsed file.
std::deque< LIBRARY_TABLE_ROW > m_rows
bool addRowFromIR(const LIBRARY_TABLE_ROW_IR &aIR)
LIBRARY_TABLE_SCOPE m_scope
bool initFromIR(const LIBRARY_TABLE_IR &aIR)
An interface used to output 8 bit text in a convenient way.
Definition richio.h:295
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:700
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:71
std::string::const_iterator begin() const
Definition utf8.h:219
std::string::size_type size() const
Definition utf8.h:116
std::string::const_iterator end() const
Definition utf8.h:220
static void ResolvePossibleSymlinks(wxFileName &aFilename)
An extension of wxXmlNode that can format its contents as KiCad-style s-expressions.
Definition xnode.h:71
void Format(OUTPUTFORMATTER *out) const
Write this object as UTF8 out to an OUTPUTFORMATTER as an S-expression.
Definition xnode.cpp:113
void AddAttribute(const wxString &aName, const wxString &aValue) override
Definition xnode.cpp:92
#define _(s)
const wxChar *const traceLibraries
Flag to enable library table and library manager tracing.
#define OPT_SEP
options separator character
tl::expected< ResultType, LIBRARY_ERROR > LIBRARY_RESULT
LIBRARY_TABLE_SCOPE
bool AtomicWriteFile(const wxString &aTargetPath, const void *aData, size_t aSize, wxString *aError=nullptr)
Writes aData to aTargetPath via a sibling temp file, fsyncs the data and directory,...
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
The intermediate representation that a library table is parsed into.
std::vector< LIBRARY_TABLE_ROW_IR > rows
LIBRARY_TABLE_TYPE type
VECTOR2I end
wxLogTrace helper definitions.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:39