sim/sim_model: fix an annoying issue when adding new fields: their ID was

set in undefined, that create an issue (the canonical name was returned as
"Field-1", breaking the schematic file).
Now, new field IDs are not set to -1, and the saved file uses the field name
(if exist) when saving fields with undefined ID.
This commit is contained in:
jean-pierre charras 2023-08-01 13:37:53 +02:00
parent 65450d9b5d
commit 3a82374719
2 changed files with 41 additions and 0 deletions

View File

@ -873,6 +873,11 @@ void SCH_SEXPR_PLUGIN::saveField( SCH_FIELD* aField, int aNestLevel )
if( aField->GetId() == -1 /* undefined ID */ ) if( aField->GetId() == -1 /* undefined ID */ )
{ {
// Replace the default name built by GetCanonicalName() by
// the field name if exists
if( !aField->GetName().IsEmpty() )
fieldName = aField->GetName();
aField->SetId( m_nextFreeFieldId ); aField->SetId( m_nextFreeFieldId );
m_nextFreeFieldId += 1; m_nextFreeFieldId += 1;
} }

View File

@ -1051,6 +1051,24 @@ void SIM_MODEL::doReadDataFields( const std::vector<T>* aFields,
template <typename T> template <typename T>
void SIM_MODEL::doWriteFields( std::vector<T>& aFields ) const void SIM_MODEL::doWriteFields( std::vector<T>& aFields ) const
{ {
// Remove duplicate fields: they are at the end of list
for( size_t ii = aFields.size() - 1; ii > 0; ii-- )
{
wxString currFieldName = aFields[ii].GetName();
auto end_candidate_list = aFields.begin() + ii - 1;
auto fieldIt = std::find_if( aFields.begin(), end_candidate_list,
[&]( const T& f )
{
return f.GetName() == currFieldName;
} );
// If duplicate field found: remove current checked item
if( fieldIt != end_candidate_list )
aFields.erase( aFields.begin() + ii );
}
SetFieldValue( aFields, SIM_DEVICE_TYPE_FIELD, m_serializer->GenerateDevice() ); SetFieldValue( aFields, SIM_DEVICE_TYPE_FIELD, m_serializer->GenerateDevice() );
SetFieldValue( aFields, SIM_TYPE_FIELD, m_serializer->GenerateType() ); SetFieldValue( aFields, SIM_TYPE_FIELD, m_serializer->GenerateType() );
@ -1061,6 +1079,24 @@ void SIM_MODEL::doWriteFields( std::vector<T>& aFields ) const
if( IsStoredInValue() ) if( IsStoredInValue() )
SetFieldValue( aFields, SIM_VALUE_FIELD, m_serializer->GenerateValue() ); SetFieldValue( aFields, SIM_VALUE_FIELD, m_serializer->GenerateValue() );
// New fields have a ID = -1 (undefined). so replace the undefined ID
// by a degined ID
int lastFreeId = MANDATORY_FIELDS;
// Search for the first available value:
for( auto& fld : aFields )
{
if( fld.GetId() >= lastFreeId )
lastFreeId = fld.GetId() + 1;
}
// Set undefined IDs to a better value
for( auto& fld : aFields )
{
if( fld.GetId() < 0 )
fld.SetId( lastFreeId++ );
}
} }