KiCad PCB EDA Suite
Loading...
Searching...
No Matches
sch_differ.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 3
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, you may find one here:
18 * http://www.gnu.org/licenses/gpl-3.0.html
19 */
20
21#include "sch_differ.h"
22#include "sch_diff_utils.h"
23
26
27#include <schematic.h>
28#include <schematic_settings.h>
29#include <erc/erc_settings.h>
30#include <sch_item.h>
31#include <sch_screen.h>
32#include <sch_sheet.h>
33#include <sch_sheet_path.h>
34#include <sch_symbol.h>
35#include <properties/property.h>
37
38#include <algorithm>
39
40
41namespace KICAD_DIFF
42{
43
44SCH_DIFFER::SCH_DIFFER( const SCHEMATIC* aBefore, const SCHEMATIC* aAfter,
45 const wxString& aPath ) :
46 m_before( aBefore ),
47 m_after( aAfter ),
48 m_path( aPath )
49{}
50
51
52SCH_DIFFER::~SCH_DIFFER() = default;
53
54
55void SCH_DIFFER::SetScope( const KIID_PATH& aBeforeScope, const KIID_PATH& aAfterScope )
56{
57 m_scopeBefore = aBeforeScope;
58 m_scopeAfter = aAfterScope;
59}
60
61
62wxString SCH_DIFFER::itemTypeName( const SCH_ITEM* aItem )
63{
64 if( !aItem )
65 return wxEmptyString;
66
67 return aItem->GetClass();
68}
69
70
71wxString SCH_DIFFER::itemTypeLabel( const SCH_ITEM* aItem )
72{
73 if( !aItem )
74 return wxEmptyString;
75
76 return aItem->GetFriendlyName();
77}
78
79
80std::optional<wxString> SCH_DIFFER::itemRefdes( const SCH_ITEM* aItem,
81 const SCH_SHEET_PATH* aPath )
82{
83 if( !aPath )
84 return std::nullopt;
85
86 if( auto sym = dynamic_cast<const SCH_SYMBOL*>( aItem ) )
87 return sym->GetRef( aPath );
88
89 return std::nullopt;
90}
91
92
93void SCH_DIFFER::walk( const SCHEMATIC* aSchematic, std::vector<WalkedItem>& aOut,
94 std::vector<std::unique_ptr<SCH_SHEET_PATH>>& aStorage, const KIID_PATH& aScope ) const
95{
96 // Retain one owned SCH_SHEET_PATH per sheet and alias it across that
97 // sheet's items. The per-sheet visitor materializes the copy once; the
98 // item visitor reuses the stored pointer, matching the original loop.
99 SCH_SHEET_PATH* storedPath = nullptr;
100
102 aSchematic,
103 [&]( const SCH_SHEET_PATH& aPath )
104 {
105 aStorage.push_back( std::make_unique<SCH_SHEET_PATH>( aPath ) );
106 storedPath = aStorage.back().get();
107 },
108 [&]( SCH_ITEM* aItem, const SCH_SHEET_PATH&, const KIID_PATH& aKiidPath )
109 {
110 WalkedItem w;
111 w.id = aKiidPath;
112 w.item = aItem;
113 w.sheetPath = storedPath;
114 aOut.push_back( std::move( w ) );
115 },
116 aScope );
117}
118
119
120namespace
121{
122
126BOX2I bboxOnSheet( const SCHEMATIC* aSch, const SCH_ITEM* aItem,
127 const SCH_SHEET_PATH* aPath )
128{
129 SHEET_SCOPE scope( aSch, aPath );
130 return aItem->GetBoundingBox();
131}
132
133} // anonymous namespace
134
135
136std::vector<PROPERTY_DELTA> SCH_DIFFER::diffProperties( const SCH_ITEM* aBefore,
137 const SCH_ITEM* aAfter,
138 const SCH_SHEET_PATH* aBeforePath,
139 const SCH_SHEET_PATH* aAfterPath ) const
140{
141 if( !aBefore || !aAfter || typeid( *aBefore ) != typeid( *aAfter ) )
142 return {};
143
144 SHEET_SCOPE beforeScope( m_before, aBeforePath );
145 SHEET_SCOPE afterScope( m_after, aAfterPath );
146
147 auto deltas = DiffItemProperties( aBefore, aAfter );
148
149 // In scoped mode drop properties whose value comes from a per-instance
150 // override. Comparing them across shared sheet instances flags every
151 // symbol as Modified even when the stored content is identical.
152 const bool scoped = !m_scopeBefore.empty() || !m_scopeAfter.empty();
153
154 if( scoped )
155 {
156 auto perInstance = []( const wxString& aName )
157 {
158 return aName == wxS( "Reference" ) || aName == wxS( "Unit" );
159 };
160
161 deltas.erase( std::remove_if( deltas.begin(), deltas.end(),
162 [&]( const PROPERTY_DELTA& d )
163 {
164 return perInstance( d.name );
165 } ),
166 deltas.end() );
167 }
168
169 return deltas;
170}
171
172
173void SCH_DIFFER::sortChanges( std::vector<ITEM_CHANGE>& aChanges )
174{
175 std::sort( aChanges.begin(), aChanges.end(),
176 []( const ITEM_CHANGE& aL, const ITEM_CHANGE& aR )
177 {
178 if( aL.id < aR.id ) return true;
179 if( aR.id < aL.id ) return false;
180
181 if( aL.typeName != aR.typeName )
182 return aL.typeName < aR.typeName;
183
184 return static_cast<int>( aL.kind ) < static_cast<int>( aR.kind );
185 } );
186}
187
188
190{
192 result.path = m_path;
193 result.docType = wxS( "kicad_sch" );
194
195 if( !m_before || !m_after )
196 return result;
197
198 // Walk both schematics through their entire sheet hierarchy.
199 std::vector<WalkedItem> beforeWalk;
200 std::vector<WalkedItem> afterWalk;
201 std::vector<std::unique_ptr<SCH_SHEET_PATH>> beforePaths;
202 std::vector<std::unique_ptr<SCH_SHEET_PATH>> afterPaths;
203
204 walk( m_before, beforeWalk, beforePaths, m_scopeBefore );
205 walk( m_after, afterWalk, afterPaths, m_scopeAfter );
206
207 if( m_options.progress )
208 m_options.progress( 0.2 );
209
210 // Build reconciler descriptors and a lookup back to the live items.
211 std::vector<ITEM_DESCRIPTOR> beforeDesc;
212 std::vector<ITEM_DESCRIPTOR> afterDesc;
213 std::map<KIID_PATH, const WalkedItem*> beforeMap;
214 std::map<KIID_PATH, const WalkedItem*> afterMap;
215
216 auto makeDescriptor = []( const WalkedItem& aW, const SCHEMATIC* aSch ) -> ITEM_DESCRIPTOR
217 {
219 d.id = aW.id;
220 d.type = itemTypeName( aW.item );
221 d.position = aW.item->GetPosition();
222 d.bbox = bboxOnSheet( aSch, aW.item, aW.sheetPath );
223
224 if( auto sym = dynamic_cast<const SCH_SYMBOL*>( aW.item ) )
225 {
226 d.keyProps.emplace_back( wxS( "lib_id" ),
227 std::string( sym->GetLibId().Format().c_str() ) );
228 d.keyProps.emplace_back( wxS( "reference" ),
229 sym->GetRef( aW.sheetPath ).ToStdString() );
230 }
231
232 return d;
233 };
234
235 for( const WalkedItem& w : beforeWalk )
236 {
237 beforeDesc.push_back( makeDescriptor( w, m_before ) );
238 beforeMap[w.id] = &w;
239 }
240
241 for( const WalkedItem& w : afterWalk )
242 {
243 afterDesc.push_back( makeDescriptor( w, m_after ) );
244 afterMap[w.id] = &w;
245 }
246
247 IDENTITY_RECONCILER reconciler( m_options.identity );
248 RECONCILIATION recon = reconciler.Reconcile( beforeDesc, afterDesc );
249
250 if( m_options.progress )
251 m_options.progress( 0.5 );
252
253 // Duplicate KIID_PATH entries inside either schematic.
254 for( const KIID_PATH& dup : recon.duplicatesA )
255 {
256 ITEM_CHANGE c;
257 c.id = dup;
258 c.typeName = wxS( "SCH_ITEM" );
259 c.typeLabel = _( "Item" );
261 result.changes.push_back( std::move( c ) );
262 }
263
264 for( const KIID_PATH& dup : recon.duplicatesB )
265 {
266 if( std::find_if( result.changes.begin(), result.changes.end(),
267 [&]( const ITEM_CHANGE& aC )
268 { return aC.id == dup && aC.kind == CHANGE_KIND::DUPLICATE_UUID; } )
269 != result.changes.end() )
270 {
271 continue;
272 }
273
274 ITEM_CHANGE c;
275 c.id = dup;
276 c.typeName = wxS( "SCH_ITEM" );
277 c.typeLabel = _( "Item" );
279 result.changes.push_back( std::move( c ) );
280 }
281
282 // Matched pairs: emit MODIFIED records when any delta surfaces.
283 for( const auto& [idA, idB] : recon.aToB )
284 {
285 auto itA = beforeMap.find( idA );
286 auto itB = afterMap.find( idB );
287 const WalkedItem* a = itA == beforeMap.end() ? nullptr : itA->second;
288 const WalkedItem* b = itB == afterMap.end() ? nullptr : itB->second;
289
290 if( !a || !b )
291 continue;
292
293 std::vector<PROPERTY_DELTA> propDeltas;
294
295 if( m_options.deepCompare )
296 propDeltas = diffProperties( a->item, b->item, a->sheetPath, b->sheetPath );
297
298 bool semanticallyEqual = ( *a->item == *b->item );
299 const bool scoped = !m_scopeBefore.empty() || !m_scopeAfter.empty();
300
301 if( propDeltas.empty() && ( semanticallyEqual || scoped ) )
302 continue;
303
304 ITEM_CHANGE c;
305 c.id = idA;
306 c.typeName = itemTypeName( a->item );
307 c.typeLabel = itemTypeLabel( a->item );
309 c.bbox = bboxOnSheet( m_after, b->item, b->sheetPath );
310 c.refdes = itemRefdes( b->item, b->sheetPath );
311 c.properties = std::move( propDeltas );
312 result.changes.push_back( std::move( c ) );
313 }
314
315 for( const KIID_PATH& idA : recon.aOnly )
316 {
317 auto it = beforeMap.find( idA );
318
319 if( it == beforeMap.end() || !it->second )
320 continue;
321
322 const WalkedItem* a = it->second;
323 ITEM_CHANGE c;
324 c.id = idA;
325 c.typeName = itemTypeName( a->item );
326 c.typeLabel = itemTypeLabel( a->item );
328 c.bbox = bboxOnSheet( m_before, a->item, a->sheetPath );
329 c.refdes = itemRefdes( a->item, a->sheetPath );
330
331 {
332 SHEET_SCOPE scope( m_before, a->sheetPath );
333 c.properties = ItemProperties( a->item, /*aAsAfter=*/false );
334 }
335
336 result.changes.push_back( std::move( c ) );
337 }
338
339 for( const KIID_PATH& idB : recon.bOnly )
340 {
341 auto it = afterMap.find( idB );
342
343 if( it == afterMap.end() || !it->second )
344 continue;
345
346 const WalkedItem* b = it->second;
347
348 ITEM_CHANGE c;
349 c.id = idB;
350 c.typeName = itemTypeName( b->item );
351 c.typeLabel = itemTypeLabel( b->item );
353 c.bbox = bboxOnSheet( m_after, b->item, b->sheetPath );
354 c.refdes = itemRefdes( b->item, b->sheetPath );
355
356 {
357 SHEET_SCOPE scope( m_after, b->sheetPath );
358 c.properties = ItemProperties( b->item, /*aAsAfter=*/true );
359 }
360
361 result.changes.push_back( std::move( c ) );
362 }
363
364 // Page settings live on the root SCH_SCREEN, not on any walked item, so
365 // the per-item loop above can't see a change to them. Emit a synthetic
366 // ITEM_CHANGE with empty KIID_PATH so the planner can resolve it.
367 std::vector<PROPERTY_DELTA> docDeltas;
368
369 const SCH_SCREEN* beforeRoot = m_before ? m_before->RootScreen() : nullptr;
370 const SCH_SCREEN* afterRoot = m_after ? m_after->RootScreen() : nullptr;
371
372 if( beforeRoot && afterRoot )
373 {
374 AppendPaperDeltas( docDeltas, beforeRoot->GetPageSettings(),
375 afterRoot->GetPageSettings() );
376 AppendTitleBlockDeltas( docDeltas, beforeRoot->GetTitleBlock(), afterRoot->GetTitleBlock() );
377 }
378
379 // ERC severity overrides live in the project file. Diff only fires when
380 // sibling .kicad_pro files were loaded — for plain .kicad_sch temp blobs
381 // both sides see defaults and we never get here. Be defensive about
382 // ErcSettings() — it wxASSERTs on a null project; under QA the asserter
383 // throws.
384 auto ercSeverities =
385 []( const SCHEMATIC* aSch ) -> const std::map<int, SEVERITY>*
386 {
387 if( !aSch || !aSch->IsValid() )
388 return nullptr;
389
390 return &aSch->ErcSettings().m_ERCSeverities;
391 };
392
393 const std::map<int, SEVERITY>* beforeERC = ercSeverities( m_before );
394 const std::map<int, SEVERITY>* afterERC = ercSeverities( m_after );
395
396 if( beforeERC && afterERC && *beforeERC != *afterERC )
397 {
402 docDeltas.push_back( std::move( d ) );
403 }
404
405 // Drawing sheet file path. Lives on SCHEMATIC_SETTINGS::m_SchDrawingSheet
406 // FileName (which lives inside the project file). Settings() wxASSERTs
407 // on a null project; only access when both sides loaded a sibling
408 // .kicad_pro.
409 auto schDrawingSheet = []( const SCHEMATIC* aSch ) -> wxString
410 {
411 if( !aSch || !aSch->IsValid() )
412 return wxEmptyString;
413
414 return aSch->Settings().m_SchDrawingSheetFileName;
415 };
416
417 const wxString beforeSheet = schDrawingSheet( m_before );
418 const wxString afterSheet = schDrawingSheet( m_after );
419
420 if( beforeSheet != afterSheet )
421 {
424 d.before = DIFF_VALUE::FromString( beforeSheet );
425 d.after = DIFF_VALUE::FromString( afterSheet );
426 docDeltas.push_back( std::move( d ) );
427 }
428
429 if( !docDeltas.empty() )
430 {
431 ITEM_CHANGE c;
432 c.id = KIID_PATH();
433 c.typeName = wxS( "SCHEMATIC" );
434 c.typeLabel = _( "Schematic" );
436 c.bbox = BOX2I();
437 c.properties = std::move( docDeltas );
438 result.changes.push_back( std::move( c ) );
439 }
440
441 // Per-sheet paper settings: sub-sheets in a hierarchy can carry their
442 // own paper size / orientation distinct from the root. Dedup by screen
443 // pointer so re-instantiated sub-sheets (multiple SCH_SHEET_PATHs hit
444 // the same underlying SCH_SCREEN) produce one delta, not N — otherwise
445 // the user would see duplicate rows and the applier could resolve them
446 // inconsistently.
447 auto sheetPaperByScreen =
448 []( const SCHEMATIC* aSch )
449 -> std::map<const SCH_SCREEN*, std::pair<KIID_PATH, const PAGE_INFO*>>
450 {
451 std::map<const SCH_SCREEN*, std::pair<KIID_PATH, const PAGE_INFO*>> out;
452
453 if( !aSch || !aSch->IsValid() )
454 return out;
455
456 for( const SCH_SHEET_PATH& path : aSch->BuildSheetListSortedByPageNumbers() )
457 {
458 if( const SCH_SCREEN* screen = path.LastScreen() )
459 out.try_emplace( screen, path.Path(), &screen->GetPageSettings() );
460 }
461
462 return out;
463 };
464
465 const SCH_SCREEN* const beforeRootScreen = beforeRoot;
466
467 // Build the after-side path->screen map once. We CANNOT store a pointer
468 // into a temporary SCH_SHEET_LIST from BuildSheetListSortedByPageNumbers
469 // — the list goes out of scope before we'd dereference. Storing the raw
470 // SCH_SCREEN* is safe because the screens are owned by the SCHEMATIC.
471 std::map<KIID_PATH, const SCH_SCREEN*> afterScreensByPath;
472
473 if( m_after && m_after->IsValid() )
474 {
475 for( const SCH_SHEET_PATH& p : m_after->BuildSheetListSortedByPageNumbers() )
476 {
477 if( const SCH_SCREEN* screen = p.LastScreen() )
478 afterScreensByPath.try_emplace( p.Path(), screen );
479 }
480 }
481
482 for( const auto& [beforeScreen, entry] : sheetPaperByScreen( m_before ) )
483 {
484 // Root paper is covered by the empty-KIID_PATH delta above; skip
485 // the root screen here so we don't double-report.
486 if( beforeScreen == beforeRootScreen )
487 continue;
488
489 const KIID_PATH& sheetPath = entry.first;
490 const PAGE_INFO& beforePaper = *entry.second;
491
492 // Match by KIID_PATH. Topology changes (renamed / re-parented
493 // sheets) where the path no longer matches are out of scope; the
494 // differ doesn't model sheet structure changes, only content on
495 // common paths.
496 auto afterIt = afterScreensByPath.find( sheetPath );
497
498 if( afterIt == afterScreensByPath.end() || !afterIt->second )
499 continue;
500
501 std::vector<PROPERTY_DELTA> sheetDeltas;
502 AppendPaperDeltas( sheetDeltas, beforePaper,
503 afterIt->second->GetPageSettings() );
504 AppendTitleBlockDeltas( sheetDeltas, beforeScreen->GetTitleBlock(), afterIt->second->GetTitleBlock() );
505
506 if( !sheetDeltas.empty() )
507 {
508 ITEM_CHANGE c;
509 c.id = sheetPath;
510 // Append the sentinel KIID so this ID doesn't collide with the
511 // SCH_SHEET symbol that lives at the same `sheetPath`. The
512 // applier checks the last KIID to route to the screen branch.
513 c.id.push_back( SchScreenSentinelKiid() );
514 c.typeName = wxS( "SCH_SCREEN" );
515 c.typeLabel = _( "Page Settings" );
517 c.bbox = BOX2I();
518 c.properties = std::move( sheetDeltas );
519 result.changes.push_back( std::move( c ) );
520 }
521 }
522
523 sortChanges( result.changes );
524
525 if( m_options.progress )
526 m_options.progress( 1.0 );
527
528 return result;
529}
530
531} // namespace KICAD_DIFF
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
virtual VECTOR2I GetPosition() const
Definition eda_item.h:348
virtual const BOX2I GetBoundingBox() const
Return the orthogonal bounding box of this object for display purposes.
Definition eda_item.cpp:280
virtual wxString GetFriendlyName() const
Definition eda_item.cpp:575
static DIFF_VALUE FromString(const wxString &aValue)
Reconciles item identity across two snapshots of the same document.
RECONCILIATION Reconcile(const std::vector< ITEM_DESCRIPTOR > &aA, const std::vector< ITEM_DESCRIPTOR > &aB) const
const SCHEMATIC * m_after
Definition sch_differ.h:111
static std::optional< wxString > itemRefdes(const SCH_ITEM *aItem, const SCH_SHEET_PATH *aPath)
Refdes if the item is a symbol; nullopt otherwise.
static wxString itemTypeName(const SCH_ITEM *aItem)
Type name for an SCH_ITEM (used in diff records).
void SetScope(const KIID_PATH &aBeforeScope, const KIID_PATH &aAfterScope)
Restrict the diff to one sheet on each side.
const SCHEMATIC * m_before
Definition sch_differ.h:110
static wxString itemTypeLabel(const SCH_ITEM *aItem)
Translated type name shown to the user.
SCH_DIFFER(const SCHEMATIC *aBefore, const SCHEMATIC *aAfter, const wxString &aPath=wxEmptyString)
static void sortChanges(std::vector< ITEM_CHANGE > &aChanges)
std::vector< PROPERTY_DELTA > diffProperties(const SCH_ITEM *aBefore, const SCH_ITEM *aAfter, const SCH_SHEET_PATH *aBeforePath, const SCH_SHEET_PATH *aAfterPath) const
Property-level delta via PROPERTY_MANAGER.
DOCUMENT_DIFF Diff() override
Produce a DOCUMENT_DIFF of the inputs the concrete differ was constructed with.
void walk(const SCHEMATIC *aSchematic, std::vector< WalkedItem > &aOut, std::vector< std::unique_ptr< SCH_SHEET_PATH > > &aStorage, const KIID_PATH &aScope={}) const
Walk a schematic and produce a flat list of (KIID_PATH, item) tuples.
RAII guard that temporarily swaps SCHEMATIC::CurrentSheet to a given path for the duration of a scope...
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
Holds all the data relating to one schematic.
Definition schematic.h:155
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
wxString GetClass() const override
Return the class name.
Definition sch_item.h:180
const PAGE_INFO & GetPageSettings() const
Definition sch_screen.h:144
TITLE_BLOCK & GetTitleBlock()
Definition sch_screen.h:168
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
Schematic symbol object.
Definition sch_symbol.h:76
#define _(s)
const wxString DOC_PROP_ERC_SEVERITIES
const KIID & SchScreenSentinelKiid()
Sentinel KIID appended to a sheet's KIID_PATH to mark a per-sheet SCH_SCREEN resolution (page format ...
std::vector< PROPERTY_DELTA > DiffItemProperties(const INSPECTABLE *aBefore, const INSPECTABLE *aAfter)
Enumerate the property deltas between two items of the same dynamic type.
std::string SummarizeSeverities(const SeverityMap &aMap)
Format a severity-override map (DRC or ERC, keyed by error code, value is a SEVERITY enum) as a short...
std::vector< PROPERTY_DELTA > ItemProperties(const INSPECTABLE *aItem, bool aAsAfter)
List one item's properties as one-sided deltas for an added or removed item.
void AppendTitleBlockDeltas(std::vector< PROPERTY_DELTA > &aDeltas, const TITLE_BLOCK &aBefore, const TITLE_BLOCK &aAfter)
Append a delta for every title block field that differs between the two documents,...
void AppendPaperDeltas(std::vector< PROPERTY_DELTA > &aDeltas, const PAGE_INFO &aBefore, const PAGE_INFO &aAfter)
Append DOC_PROP_PAGE_FORMAT and/or DOC_PROP_PAGE_ORIENTATION deltas to aDeltas when the two PAGE_INFO...
const wxString DOC_PROP_DRAWING_SHEET
void WalkSchematic(const SCHEMATIC *aSchematic, SHEET_VISITOR &&aSheetVisitor, ITEM_VISITOR &&aItemVisitor, const KIID_PATH &aScope={})
Visit every SCH_ITEM in every sheet of aSchematic in page-number order.
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
The full set of changes between two parsed documents of one type.
One change record on a single item.
std::vector< PROPERTY_DELTA > properties
std::optional< wxString > refdes
Descriptor used by the identity reconciler to compare items across two documents.
std::vector< std::pair< wxString, std::string > > keyProps
Single (name, before, after) triple for one mutated property on an item.
Maps every item in document A to either a peer in document B or to "only-in-A", and vice versa.
std::set< KIID_PATH > aOnly
std::vector< KIID_PATH > duplicatesA
std::map< KIID_PATH, KIID_PATH > aToB
std::vector< KIID_PATH > duplicatesB
std::set< KIID_PATH > bOnly
std::string path
wxString result
Test unit parsing edge cases and error handling.