KiCad PCB EDA Suite
Loading...
Searching...
No Matches
eeschema_jobs_handler.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) 2022 Mark Roszko <[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 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
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
23#include <algorithm>
24#include <common.h>
25#include <pgm_base.h>
26#include <kiface_base.h>
27#include <kiway_player.h>
28#include <cli/exit_codes.h>
29#include <sch_plotter.h>
32#include <jobs/job_export_bom.h>
36#include <jobs/job_sch_erc.h>
37#include <jobs/job_sch_import.h>
40#include <downgrade_target.h>
42#include <downgrade_scan.h>
43#include <downgrade_copy.h>
44#include <bus_alias.h>
45#include <lib_symbol.h>
47#include <sch_sheet_path.h>
48#include <set>
49#include <wx/ffile.h>
54#include <schematic.h>
55#include <import_net_map.h>
56#include <schematic_settings.h>
57#include <sch_screen.h>
58#include <sch_sheet.h>
59#include <sch_sheet_path.h>
60#include <sch_commit.h>
62#include <save_project_utils.h>
63#include <tool/tool_manager.h>
64#include <project.h>
66#include <wx/dir.h>
67#include <wx/file.h>
68#include <memory>
69#include <connection_graph.h>
70#include "eeschema_helpers.h"
71#include <filename_resolver.h>
72#include <kiway.h>
73#include <sch_painter.h>
74#include <locale_io.h>
75#include <erc/erc.h>
76#include <erc/erc_report.h>
77#include <erc/erc_settings.h>
81#include <paths.h>
82#include <reporter.h>
83#include <scoped_set_reset.h>
84#include <string_utils.h>
85
87
88#include <sch_file_versions.h>
89#include <sch_io/sch_io.h>
91
92#include <netlist.h>
102
104
109#include <confirm.h>
110#include <project_sch.h>
111
113
114
116 JOB_DISPATCHER( aKiway ),
117 m_cliSchematic( nullptr )
118{
119 Register( "bom", std::bind( &EESCHEMA_JOBS_HANDLER::JobExportBom, this, std::placeholders::_1 ),
120 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
121 {
122 JOB_EXPORT_BOM* bomJob = dynamic_cast<JOB_EXPORT_BOM*>( job );
123
124 SCH_EDIT_FRAME* editFrame = static_cast<SCH_EDIT_FRAME*>( aKiway->Player( FRAME_SCH, false ) );
125
126 wxCHECK( bomJob && editFrame, false );
127
128 DIALOG_SYMBOL_FIELDS_TABLE dlg( editFrame, bomJob );
129
130 if( dlg.WasAborted() )
131 return false;
132
133 return dlg.ShowModal() == wxID_OK;
134 } );
135 Register( "pythonbom", std::bind( &EESCHEMA_JOBS_HANDLER::JobExportPythonBom, this, std::placeholders::_1 ),
136 []( JOB* job, wxWindow* aParent ) -> bool
137 {
138 return true;
139 } );
140 Register( "netlist", std::bind( &EESCHEMA_JOBS_HANDLER::JobExportNetlist, this, std::placeholders::_1 ),
141 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
142 {
143 JOB_EXPORT_SCH_NETLIST* netJob = dynamic_cast<JOB_EXPORT_SCH_NETLIST*>( job );
144
145 SCH_EDIT_FRAME* editFrame = static_cast<SCH_EDIT_FRAME*>( aKiway->Player( FRAME_SCH, false ) );
146
147 wxCHECK( netJob && editFrame, false );
148
149 DIALOG_EXPORT_NETLIST dlg( editFrame, aParent, netJob );
150 return dlg.ShowModal() == wxID_OK;
151 } );
152 Register( "plot", std::bind( &EESCHEMA_JOBS_HANDLER::JobExportPlot, this, std::placeholders::_1 ),
153 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
154 {
155 JOB_EXPORT_SCH_PLOT* plotJob = dynamic_cast<JOB_EXPORT_SCH_PLOT*>( job );
156
157 SCH_EDIT_FRAME* editFrame = static_cast<SCH_EDIT_FRAME*>( aKiway->Player( FRAME_SCH, false ) );
158
159 wxCHECK( plotJob && editFrame, false );
160
161 if( plotJob->m_plotFormat == SCH_PLOT_FORMAT::HPGL )
162 {
163 DisplayErrorMessage( editFrame,
164 _( "Plotting to HPGL is no longer supported as of KiCad 10.0." ) );
165 return false;
166 }
167
168 DIALOG_PLOT_SCHEMATIC dlg( editFrame, aParent, plotJob );
169 return dlg.ShowModal() == wxID_OK;
170 } );
171 Register( "symupgrade", std::bind( &EESCHEMA_JOBS_HANDLER::JobSymUpgrade, this, std::placeholders::_1 ),
172 []( JOB* job, wxWindow* aParent ) -> bool
173 {
174 return true;
175 } );
176 Register( "symdowngrade", std::bind( &EESCHEMA_JOBS_HANDLER::JobSymDowngrade, this, std::placeholders::_1 ),
177 []( JOB* job, wxWindow* aParent ) -> bool
178 {
179 return true;
180 } );
181 Register( "symsvg", std::bind( &EESCHEMA_JOBS_HANDLER::JobSymExportSvg, this, std::placeholders::_1 ),
182 []( JOB* job, wxWindow* aParent ) -> bool
183 {
184 return true;
185 } );
186 Register( "sch_diff", std::bind( &EESCHEMA_JOBS_HANDLER::JobSchDiff, this, std::placeholders::_1 ),
187 []( JOB* job, wxWindow* aParent ) -> bool
188 {
189 return true;
190 } );
191 Register( "sym_diff", std::bind( &EESCHEMA_JOBS_HANDLER::JobSymDiff, this, std::placeholders::_1 ),
192 []( JOB* job, wxWindow* aParent ) -> bool
193 {
194 return true;
195 } );
196 Register( "erc", std::bind( &EESCHEMA_JOBS_HANDLER::JobSchErc, this, std::placeholders::_1 ),
197 []( JOB* job, wxWindow* aParent ) -> bool
198 {
199 JOB_SCH_ERC* ercJob = dynamic_cast<JOB_SCH_ERC*>( job );
200
201 wxCHECK( ercJob, false );
202
203 DIALOG_ERC_JOB_CONFIG dlg( aParent, ercJob );
204 return dlg.ShowModal() == wxID_OK;
205 } );
206 Register( "upgrade", std::bind( &EESCHEMA_JOBS_HANDLER::JobUpgrade, this, std::placeholders::_1 ),
207 []( JOB* job, wxWindow* aParent ) -> bool
208 {
209 return true;
210 } );
211 Register( "downgrade", std::bind( &EESCHEMA_JOBS_HANDLER::JobDowngrade, this, std::placeholders::_1 ),
212 []( JOB* job, wxWindow* aParent ) -> bool
213 {
214 return true;
215 } );
216 Register( "sch_import", std::bind( &EESCHEMA_JOBS_HANDLER::JobImport, this, std::placeholders::_1 ),
217 []( JOB* job, wxWindow* aParent ) -> bool
218 {
219 return true;
220 } );
221}
222
223
225{
226 if( m_cliSchematic )
227 m_cliSchematic->SetProject( nullptr );
228
229 delete m_cliSchematic;
230 m_cliSchematic = nullptr;
232}
233
234
235SCHEMATIC* EESCHEMA_JOBS_HANDLER::getSchematic( const wxString& aPath, bool aRequireRoot )
236{
237 SCHEMATIC* sch = nullptr;
238
239 if( !Pgm().IsGUI() && Pgm().GetSettingsManager().IsProjectOpenNotDummy() )
240 {
242 wxString schPath = aPath;
243
244 if( schPath.IsEmpty() )
245 {
246 wxFileName path = project.GetProjectFullName();
248 path.MakeAbsolute();
249 schPath = path.GetFullPath();
250 }
251
252 if( m_cliSchematic && aRequireRoot && !m_cliSchematicRootValidated )
254
255 if( !m_cliSchematic )
256 {
258 schPath, true, false, &project, true, aRequireRoot ? m_reporter : nullptr );
259 m_cliSchematicRootValidated = aRequireRoot;
260 }
261
262 sch = m_cliSchematic;
263 }
264 else if( Pgm().IsGUI() && Pgm().GetSettingsManager().IsProjectOpen() )
265 {
266 SCH_EDIT_FRAME* editFrame = static_cast<SCH_EDIT_FRAME*>( m_kiway->Player( FRAME_SCH, false ) );
267
268 if( editFrame )
269 sch = &editFrame->Schematic();
270 }
271 else if( !aPath.IsEmpty() )
272 {
274 aPath, true, false, nullptr, true, aRequireRoot ? m_reporter : nullptr );
275 }
276
277 if( !sch )
278 m_reporter->Report( _( "Failed to load schematic\n" ), RPT_SEVERITY_ERROR );
279
280 return sch;
281}
282
283void EESCHEMA_JOBS_HANDLER::InitRenderSettings( SCH_RENDER_SETTINGS* aRenderSettings, const wxString& aTheme,
284 SCHEMATIC* aSch, const wxString& aDrawingSheetOverride )
285{
287 aRenderSettings->LoadColors( cs );
288 aRenderSettings->m_ShowHiddenPins = false;
289 aRenderSettings->m_ShowHiddenFields = false;
290 aRenderSettings->m_ShowPinAltIcons = false;
291
292 aRenderSettings->SetDefaultPenWidth( aSch->Settings().m_DefaultLineWidth );
293 aRenderSettings->m_LabelSizeRatio = aSch->Settings().m_LabelSizeRatio;
294 aRenderSettings->m_TextOffsetRatio = aSch->Settings().m_TextOffsetRatio;
295 aRenderSettings->m_PinSymbolSize = aSch->Settings().m_PinSymbolSize;
296 aRenderSettings->m_ShowDNPMarkers = aSch->Settings().m_ShowDNPMarkers;
297
298 aRenderSettings->SetDashLengthRatio( aSch->Settings().m_DashedLineDashRatio );
299 aRenderSettings->SetGapLengthRatio( aSch->Settings().m_DashedLineGapRatio );
300
301 // Load the drawing sheet from the filename stored in BASE_SCREEN::m_DrawingSheetFileName.
302 // If empty, or not existing, the default drawing sheet is loaded.
303
304 auto loadSheet = [&]( const wxString& path ) -> bool
305 {
306 wxString msg;
307
308 if( !DS_DATA_MODEL::GetTheInstance().LoadFromName( path, wxGetCwd(), &aSch->Project(),
309 { aSch->GetEmbeddedFiles() }, &msg ) )
310 {
311 m_reporter->Report( wxString::Format( _( "Error loading drawing sheet '%s'." ), path ) + wxS( "\n" ) + msg
312 + wxS( "\n" ),
314 return false;
315 }
316
317 return true;
318 };
319
320 // try to load the override first
321 if( !aDrawingSheetOverride.IsEmpty() && loadSheet( aDrawingSheetOverride ) )
322 return;
323
324 if( aSch->Settings().m_SchDrawingSheetFileName == wxS( "empty.kicad_wks" ) )
325 {
327 return;
328 }
329
330 // no override or failed override continues here
331 loadSheet( aSch->Settings().m_SchDrawingSheetFileName );
332}
333
334
336{
337 JOB_EXPORT_SCH_PLOT* aPlotJob = dynamic_cast<JOB_EXPORT_SCH_PLOT*>( aJob );
338
339 wxCHECK( aPlotJob, CLI::EXIT_CODES::ERR_UNKNOWN );
340
341 if( aPlotJob->m_plotFormat == SCH_PLOT_FORMAT::HPGL )
342 {
343 m_reporter->Report( _( "Plotting to HPGL is no longer supported as of KiCad 10.0.\n" ), RPT_SEVERITY_ERROR );
345 }
346
347 SCHEMATIC* sch = getSchematic( aPlotJob->m_filename );
348
349 if( !sch )
351
352 aJob->SetTitleBlock( sch->RootScreen()->GetTitleBlock() );
353 sch->Project().ApplyTextVars( aJob->GetVarOverrides() );
354
355 // Determine the variant to use. The dialog edit path writes m_variant (the scalar),
356 // while the CLI path populates m_variantNames directly. Prefer the scalar so a
357 // dialog-edited selection always wins over a stale list left over from CLI input.
358 wxString variantName;
359
360 if( !aPlotJob->m_variant.IsEmpty() )
361 variantName = aPlotJob->m_variant;
362 else if( !aPlotJob->m_variantNames.empty() )
363 variantName = aPlotJob->m_variantNames.front();
364
365 if( !variantName.IsEmpty() && variantName != wxS( "all" ) )
366 sch->SetCurrentVariant( variantName );
367
368 std::unique_ptr<SCH_RENDER_SETTINGS> renderSettings = std::make_unique<SCH_RENDER_SETTINGS>();
369 InitRenderSettings( renderSettings.get(), aPlotJob->m_theme, sch, aPlotJob->m_drawingSheet );
370
371 wxString font = aPlotJob->m_defaultFont;
372
373 if( font.IsEmpty() )
374 {
376 font = cfg ? cfg->m_Appearance.default_font : wxString( KICAD_FONT_NAME );
377 }
378
379 renderSettings->SetDefaultFont( font );
380 renderSettings->SetMinPenWidth( aPlotJob->m_minPenWidth );
381
382 // Clear cached bounding boxes for all text items so they're recomputed with the correct
383 // default font. This is necessary because text bounding boxes may have been cached during
384 // schematic loading before the render settings (and thus default font) were configured.
385 SCH_SCREENS screens( sch->Root() );
386
387 for( SCH_SCREEN* screen = screens.GetFirst(); screen; screen = screens.GetNext() )
388 {
389 for( SCH_ITEM* item : screen->Items() )
390 item->ClearCaches();
391
392 for( const auto& [libItemName, libSymbol] : screen->GetLibSymbols() )
393 libSymbol->ClearCaches();
394 }
395
396 std::unique_ptr<SCH_PLOTTER> schPlotter = std::make_unique<SCH_PLOTTER>( sch );
397
399
400 switch( aPlotJob->m_plotFormat )
401 {
402 case SCH_PLOT_FORMAT::DXF: format = PLOT_FORMAT::DXF; break;
403 case SCH_PLOT_FORMAT::PDF: format = PLOT_FORMAT::PDF; break;
404 case SCH_PLOT_FORMAT::SVG: format = PLOT_FORMAT::SVG; break;
405 case SCH_PLOT_FORMAT::POST: format = PLOT_FORMAT::POST; break;
406 case SCH_PLOT_FORMAT::PNG: format = PLOT_FORMAT::PNG; break;
407 case SCH_PLOT_FORMAT::HPGL: /* no longer supported */ break;
408 }
409
410 int pageSizeSelect = PageFormatReq::PAGE_SIZE_AUTO;
411
412 switch( aPlotJob->m_pageSizeSelect )
413 {
414 case JOB_PAGE_SIZE::PAGE_SIZE_A: pageSizeSelect = PageFormatReq::PAGE_SIZE_A; break;
415 case JOB_PAGE_SIZE::PAGE_SIZE_A4: pageSizeSelect = PageFormatReq::PAGE_SIZE_A4; break;
417 }
418
419 wxFileName defaultFn = sch->GetFileName();
420 defaultFn.SetExt( GetDefaultPlotExtension( format ) );
421
422 if( !aPlotJob->GetOutputPathIsDirectory() && aPlotJob->GetConfiguredOutputPath().IsEmpty() )
423 aPlotJob->SetConfiguredOutputPath( defaultFn.GetFullName() );
424
425 wxString outPath = aPlotJob->GetFullOutputPath( &sch->Project() );
426
427 // A folder in file mode gets the default name inside it
428 if( !aPlotJob->GetOutputPathIsDirectory() )
429 outPath = JOB::AppendDefaultFileName( outPath, defaultFn.GetFullName() );
430
431 if( !PATHS::EnsurePathExists( outPath, !aPlotJob->GetOutputPathIsDirectory() ) )
432 {
433 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
435 }
436
437 SCH_PLOT_OPTS plotOpts;
438 plotOpts.m_blackAndWhite = aPlotJob->m_blackAndWhite;
439 plotOpts.m_PDFPropertyPopups = aPlotJob->m_PDFPropertyPopups;
441 plotOpts.m_PDFMetadata = aPlotJob->m_PDFMetadata;
442
443 if( aPlotJob->GetOutputPathIsDirectory() )
444 {
445 plotOpts.m_outputDirectory = outPath;
446 plotOpts.m_outputFile = wxEmptyString;
447 }
448 else
449 {
450 plotOpts.m_outputDirectory = wxEmptyString;
451 plotOpts.m_outputFile = outPath;
452 }
453
454 plotOpts.m_pageSizeSelect = pageSizeSelect;
455 plotOpts.m_plotAll = aPlotJob->m_plotAll;
456 plotOpts.m_plotDrawingSheet = aPlotJob->m_plotDrawingSheet;
457 plotOpts.m_plotPages = aPlotJob->m_plotPages;
458
459 if( !aPlotJob->m_sheetPath.IsEmpty() )
460 plotOpts.m_sheetPath = sch->Hierarchy().GetSheetPathByKIIDPath( KIID_PATH( aPlotJob->m_sheetPath ) );
461
462 plotOpts.m_theme = aPlotJob->m_theme;
463 plotOpts.m_useBackgroundColor = aPlotJob->m_useBackgroundColor;
464 plotOpts.m_plotHopOver = aPlotJob->m_show_hop_over;
465
466 if( !variantName.IsEmpty() )
467 plotOpts.m_variant = variantName;
468
469 // Always export dxf in mm by kicad-cli (similar to Pcbnew)
471
472 if( aPlotJob->m_plotFormat == SCH_PLOT_FORMAT::PNG )
473 {
474 JOB_EXPORT_SCH_PLOT_PNG* pngJob = static_cast<JOB_EXPORT_SCH_PLOT_PNG*>( aPlotJob );
475 plotOpts.m_pngDPI = pngJob->m_dpi;
476 plotOpts.m_pngAntialias = pngJob->m_antialias;
477 }
478
479 schPlotter->Plot( format, plotOpts, renderSettings.get(), m_reporter );
480
481 if( m_reporter->HasMessageOfSeverity( RPT_SEVERITY_ERROR ) )
483
484 for( const wxString& outputPath : schPlotter->GetOutputFilePaths() )
485 aJob->AddOutput( outputPath );
486
487 return CLI::EXIT_CODES::OK;
488}
489
490
492{
493 JOB_EXPORT_SCH_NETLIST* aNetJob = dynamic_cast<JOB_EXPORT_SCH_NETLIST*>( aJob );
494
495 wxCHECK( aNetJob, CLI::EXIT_CODES::ERR_UNKNOWN );
496
497 SCHEMATIC* sch = getSchematic( aNetJob->m_filename );
498
499 if( !sch )
501
502 aJob->SetTitleBlock( sch->RootScreen()->GetTitleBlock() );
503 sch->Project().ApplyTextVars( aJob->GetVarOverrides() );
504
505 // Apply variant if specified
506 if( !aNetJob->m_variantNames.empty() )
507 {
508 // For netlist export, we use the first variant name from the set
509 wxString variantName = *aNetJob->m_variantNames.begin();
510
511 if( variantName != wxS( "all" ) )
512 sch->SetCurrentVariant( variantName );
513 }
514
515 // Annotation warning check
516 SCH_REFERENCE_LIST referenceList;
517 sch->Hierarchy().GetSymbols( referenceList, SYMBOL_FILTER_NON_POWER );
518
519 if( referenceList.GetCount() > 0 )
520 {
521 if( referenceList.CheckAnnotation(
522 []( ERCE_T, const wxString&, SCH_REFERENCE*, SCH_REFERENCE* )
523 {
524 // We're only interested in the end result -- either errors or not
525 } )
526 > 0 )
527 {
528 m_reporter->Report( _( "Warning: schematic has annotation errors, please use the "
529 "schematic editor to fix them\n" ),
531 }
532 }
533
534 // Test duplicate sheet names:
535 ERC_TESTER erc( sch );
536
537 if( erc.TestDuplicateSheetNames( false ) > 0 )
538 m_reporter->Report( _( "Warning: duplicate sheet names.\n" ), RPT_SEVERITY_WARNING );
539
540 std::unique_ptr<NETLIST_EXPORTER_BASE> helper;
541 unsigned netlistOption = 0;
542
543 wxString fileExt;
544
545 switch( aNetJob->format )
546 {
549 helper = std::make_unique<NETLIST_EXPORTER_KICAD>( sch, m_kiway );
550 break;
551
554 helper = std::make_unique<NETLIST_EXPORTER_ORCADPCB2>( sch, m_kiway );
555 break;
556
559 helper = std::make_unique<NETLIST_EXPORTER_CADSTAR>( sch, m_kiway );
560 break;
561
565 helper = std::make_unique<NETLIST_EXPORTER_SPICE>( sch, m_kiway );
566 break;
567
570 helper = std::make_unique<NETLIST_EXPORTER_SPICE_MODEL>( sch, m_kiway );
571 break;
572
574 fileExt = wxS( "xml" );
575 helper = std::make_unique<NETLIST_EXPORTER_XML>( sch, m_kiway );
576 break;
577
579 fileExt = wxS( "asc" );
580 helper = std::make_unique<NETLIST_EXPORTER_PADS>( sch, m_kiway );
581 break;
582
584 fileExt = wxS( "txt" );
585 helper = std::make_unique<NETLIST_EXPORTER_ALLEGRO>( sch, m_kiway );
586 break;
587
588 default:
589 m_reporter->Report( _( "Unknown netlist format.\n" ), RPT_SEVERITY_ERROR );
591 }
592
593 wxFileName defaultFn = sch->GetFileName();
594 defaultFn.SetExt( fileExt );
595
596 if( aNetJob->GetConfiguredOutputPath().IsEmpty() )
597 aNetJob->SetConfiguredOutputPath( defaultFn.GetFullName() );
598
599 wxString outPath = JOB::AppendDefaultFileName( aNetJob->GetFullOutputPath( &sch->Project() ),
600 defaultFn.GetFullName() );
601
602 if( !PATHS::EnsurePathExists( outPath, true ) )
603 {
604 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
606 }
607
608 bool res = helper->WriteNetlist( outPath, netlistOption, *m_reporter );
609
610 if( !res )
612
613 aJob->AddOutput( outPath );
614
615 return CLI::EXIT_CODES::OK;
616}
617
618
620{
621 JOB_EXPORT_BOM* aBomJob = dynamic_cast<JOB_EXPORT_BOM*>( aJob );
622
623 wxCHECK( aBomJob, CLI::EXIT_CODES::ERR_UNKNOWN );
624
625 SCHEMATIC* sch = getSchematic( aBomJob->m_filename );
626
627 if( !sch )
629
630 aJob->SetTitleBlock( sch->RootScreen()->GetTitleBlock() );
631 sch->Project().ApplyTextVars( aJob->GetVarOverrides() );
632
633 wxString currentVariant = aBomJob->GetSelectedVariant();
634
635 if( !currentVariant.IsEmpty() && currentVariant != wxS( "all" ) )
636 sch->SetCurrentVariant( currentVariant );
637
638 // Annotation warning check
639 SCH_REFERENCE_LIST referenceList;
640 sch->Hierarchy().GetSymbols( referenceList, SYMBOL_FILTER_NON_POWER, false );
641
642 if( referenceList.GetCount() > 0 )
643 {
644 SCH_REFERENCE_LIST copy = referenceList;
645
646 // Check annotation splits references...
647 if( copy.CheckAnnotation(
648 []( ERCE_T, const wxString&, SCH_REFERENCE*, SCH_REFERENCE* )
649 {
650 // We're only interested in the end result -- either errors or not
651 } )
652 > 0 )
653 {
654 m_reporter->Report( _( "Warning: schematic has annotation errors, please use the schematic "
655 "editor to fix them\n" ),
657 }
658 }
659
660 // Test duplicate sheet names:
661 ERC_TESTER erc( sch );
662
663 if( erc.TestDuplicateSheetNames( false ) > 0 )
664 m_reporter->Report( _( "Warning: duplicate sheet names.\n" ), RPT_SEVERITY_WARNING );
665
666 // Build our data model
667 SYMBOL_FIELDS_EDITOR_GRID_DATA_MODEL dataModel( referenceList );
668 dataModel.SetCurrentVariant( currentVariant );
669
670 // Mandatory fields first
671 for( FIELD_T fieldId : MANDATORY_FIELDS )
672 dataModel.AddColumn( GetDefaultFieldName( fieldId, UNTRANSLATED ),
673 GetDefaultFieldName( fieldId, TRANSLATED ), false );
674
675 // Generated/virtual fields (e.g. ${QUANTITY}, ${ITEM_NUMBER}) present only in the fields table
678 false );
681 false );
682
683 // Attribute fields (boolean flags on symbols)
684 dataModel.AddColumn( wxS( "${DNP}" ), GetGeneratedFieldDisplayName( wxS( "${DNP}" ) ), false );
685 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_BOM}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_BOM}" ) ),
686 false );
687 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_BOARD}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_BOARD}" ) ),
688 false );
689 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_SIM}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_SIM}" ) ),
690 false );
691
692 // User field names in symbols second
693 std::set<wxString> userFieldNames;
694
695 for( size_t i = 0; i < referenceList.GetCount(); ++i )
696 {
697 SCH_SYMBOL* symbol = referenceList[i].GetSymbol();
698
699 for( SCH_FIELD& field : symbol->GetFields() )
700 {
701 if( !field.IsMandatory() && !field.IsPrivate() )
702 userFieldNames.insert( field.GetName() );
703 }
704 }
705
706 for( const wxString& fieldName : userFieldNames )
707 dataModel.AddColumn( fieldName, GetGeneratedFieldDisplayName( fieldName ), true );
708
709 // Add any templateFieldNames which aren't already present in the userFieldNames
710 for( const TEMPLATE_FIELDNAME& templateFieldname :
712 {
713 if( userFieldNames.count( templateFieldname.m_Name ) == 0 )
714 {
715 dataModel.AddColumn( templateFieldname.m_Name, GetGeneratedFieldDisplayName( templateFieldname.m_Name ),
716 false );
717 }
718 }
719
720 BOM_PRESET preset;
721
722 // Load a preset if one is specified
723 if( !aBomJob->m_bomPresetName.IsEmpty() )
724 {
725 // Find the preset
726 std::optional<BOM_PRESET> schPreset;
727
728 for( const BOM_PRESET& p : BOM_PRESET::BuiltInPresets() )
729 {
730 if( p.name == aBomJob->m_bomPresetName )
731 {
732 schPreset = p;
733 break;
734 }
735 }
736
737 for( const BOM_PRESET& p : sch->Settings().m_BomPresets )
738 {
739 if( p.name == aBomJob->m_bomPresetName )
740 {
741 schPreset = p;
742 break;
743 }
744 }
745
746 if( !schPreset )
747 {
748 m_reporter->Report(
749 wxString::Format( _( "BOM preset '%s' not found" ) + wxS( "\n" ), aBomJob->m_bomPresetName ),
751
753 }
754
755 preset = *schPreset;
756 }
757 else
758 {
759 // Normalize field names so that bare generated-field tokens (e.g. "QUANTITY") are
760 // accepted alongside the canonical "${QUANTITY}" form. Shell expansion of ${VAR}
761 // inside double quotes silently produces an empty string, so this also guards against
762 // that common CLI pitfall.
763 auto normalizeFieldName = [&dataModel]( const wxString& aName ) -> wxString
764 {
765 if( aName.IsEmpty() )
766 return wxEmptyString;
767
768 if( IsGeneratedField( aName ) )
769 return aName;
770
771 wxString wrapped = wxS( "${" ) + aName + wxS( "}" );
772
773 if( IsGeneratedField( wrapped ) && dataModel.GetFieldNameCol( wrapped ) != -1 )
774 return wrapped;
775
776 return aName;
777 };
778
779 size_t i = 0;
780
781 for( const wxString& rawFieldName : aBomJob->m_fieldsOrdered )
782 {
783 wxString fieldName = normalizeFieldName( rawFieldName );
784
785 if( fieldName.IsEmpty() )
786 {
787 i++;
788 continue;
789 }
790
791 // Handle wildcard. We allow the wildcard anywhere in the list, but it needs to respect
792 // fields that come before and after the wildcard.
793 if( fieldName == wxS( "*" ) )
794 {
795 for( const BOM_FIELD& modelField : dataModel.GetFieldsOrdered() )
796 {
797 struct BOM_FIELD field;
798
799 field.name = modelField.name;
800 field.show = true;
801 field.groupBy = false;
802 field.label = field.name;
803
804 bool fieldAlreadyPresent = false;
805
806 for( BOM_FIELD& presetField : preset.fieldsOrdered )
807 {
808 if( presetField.name == field.name )
809 {
810 fieldAlreadyPresent = true;
811 break;
812 }
813 }
814
815 bool fieldLaterInList = false;
816
817 for( const wxString& fieldInList : aBomJob->m_fieldsOrdered )
818 {
819 if( normalizeFieldName( fieldInList ) == field.name )
820 {
821 fieldLaterInList = true;
822 break;
823 }
824 }
825
826 if( !fieldAlreadyPresent && !fieldLaterInList )
827 preset.fieldsOrdered.emplace_back( field );
828 }
829
830 continue;
831 }
832
833 struct BOM_FIELD field;
834
835 field.name = fieldName;
836 field.show = !fieldName.StartsWith( wxT( "__" ), &field.name );
837 field.name = normalizeFieldName( field.name );
838
839 if( ( aBomJob->m_fieldsLabels.size() > i ) && !aBomJob->m_fieldsLabels[i].IsEmpty() )
840 field.label = aBomJob->m_fieldsLabels[i];
841 else if( IsGeneratedField( field.name ) )
842 field.label = GetGeneratedFieldDisplayName( field.name );
843 else
844 field.label = field.name;
845
846 preset.fieldsOrdered.emplace_back( field );
847 i++;
848 }
849
850 for( const wxString& rawFieldName : aBomJob->m_fieldsGroupBy )
851 {
852 wxString fieldName = rawFieldName;
853 fieldName.StartsWith( wxT( "__" ), &fieldName );
854 fieldName = normalizeFieldName( fieldName );
855
856 if( fieldName.IsEmpty() )
857 continue;
858
859 bool fieldAlreadyPresent = false;
860
861 for( BOM_FIELD& field : preset.fieldsOrdered )
862 {
863 if( field.name == fieldName )
864 {
865 field.groupBy = true;
866 fieldAlreadyPresent = true;
867 break;
868 }
869 }
870
871 if( !fieldAlreadyPresent )
872 preset.fieldsOrdered.push_back( { fieldName, GetGeneratedFieldDisplayName( fieldName ), false, true } );
873 }
874
875 preset.sortAsc = aBomJob->m_sortAsc;
876 preset.sortField = normalizeFieldName( aBomJob->m_sortField );
877 preset.filterString = aBomJob->m_filterString;
878 preset.filterScope = aBomJob->m_filterScope;
879 preset.groupSymbols = aBomJob->m_groupSymbols;
880 preset.excludeDNP = aBomJob->m_excludeDNP;
881 }
882
883 BOM_FMT_PRESET fmt;
884
885 // Load a format preset if one is specified
886 if( !aBomJob->m_bomFmtPresetName.IsEmpty() )
887 {
888 std::optional<BOM_FMT_PRESET> schFmtPreset;
889
891 {
892 if( p.name == aBomJob->m_bomFmtPresetName )
893 {
894 schFmtPreset = p;
895 break;
896 }
897 }
898
899 for( const BOM_FMT_PRESET& p : sch->Settings().m_BomFmtPresets )
900 {
901 if( p.name == aBomJob->m_bomFmtPresetName )
902 {
903 schFmtPreset = p;
904 break;
905 }
906 }
907
908 if( !schFmtPreset )
909 {
910 m_reporter->Report( wxString::Format( _( "BOM format preset '%s' not found" ) + wxS( "\n" ),
911 aBomJob->m_bomFmtPresetName ),
913
915 }
916
917 fmt = *schFmtPreset;
918 }
919 else
920 {
921 fmt.fieldDelimiter = aBomJob->m_fieldDelimiter;
922 fmt.stringDelimiter = aBomJob->m_stringDelimiter;
923 fmt.refDelimiter = aBomJob->m_refDelimiter;
925 fmt.keepTabs = aBomJob->m_keepTabs;
926 fmt.keepLineBreaks = aBomJob->m_keepLineBreaks;
928 }
929
930 wxFileName defaultFn = sch->GetFileName();
931 defaultFn.SetExt( FILEEXT::CsvFileExtension );
932
933 if( aBomJob->GetConfiguredOutputPath().IsEmpty() )
934 aBomJob->SetConfiguredOutputPath( defaultFn.GetFullName() );
935
936 wxString configuredPath = aBomJob->GetConfiguredOutputPath();
937 bool hasVariantPlaceholder = configuredPath.Contains( wxS( "${VARIANT}" ) );
938
939 // Determine which variants to process
940 std::vector<wxString> variantsToProcess;
941
942 if( aBomJob->m_variantNames.size() > 1 && hasVariantPlaceholder )
943 {
944 variantsToProcess = aBomJob->m_variantNames;
945 }
946 else
947 {
948 variantsToProcess.push_back( currentVariant );
949 }
950
951 for( const wxString& variantName : variantsToProcess )
952 {
953 std::vector<wxString> singleVariant = { variantName };
954 dataModel.SetVariantNames( singleVariant );
955 dataModel.SetCurrentVariant( variantName );
956 dataModel.UpdateReferences( dataModel.GetReferenceList() );
957 dataModel.ApplyBomPreset( preset );
958
959 wxString outPath;
960
961 if( hasVariantPlaceholder )
962 {
963 wxString variantPath = configuredPath;
964 variantPath.Replace( wxS( "${VARIANT}" ), variantName );
965 aBomJob->SetConfiguredOutputPath( variantPath );
966 outPath = aBomJob->GetFullOutputPath( &sch->Project() );
967 aBomJob->SetConfiguredOutputPath( configuredPath );
968 }
969 else
970 {
971 outPath = aBomJob->GetFullOutputPath( &sch->Project() );
972 }
973
974 outPath = JOB::AppendDefaultFileName( outPath, defaultFn.GetFullName() );
975
976 if( !PATHS::EnsurePathExists( outPath, true ) )
977 {
978 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
980 }
981
982 wxFile f;
983
984 if( !f.Open( outPath, wxFile::write ) )
985 {
986 m_reporter->Report( wxString::Format( _( "Unable to open destination '%s'" ), outPath ),
988
990 }
991
992 bool res = f.Write( dataModel.Export( fmt ) );
993
994 if( !res )
996
997 aJob->AddOutput( outPath );
998
999 m_reporter->Report( wxString::Format( _( "Wrote bill of materials to '%s'." ), outPath ), RPT_SEVERITY_ACTION );
1000 }
1001
1002 return CLI::EXIT_CODES::OK;
1003}
1004
1005
1007{
1008 JOB_EXPORT_SCH_PYTHONBOM* aNetJob = dynamic_cast<JOB_EXPORT_SCH_PYTHONBOM*>( aJob );
1009
1010 wxCHECK( aNetJob, CLI::EXIT_CODES::ERR_UNKNOWN );
1011
1012 SCHEMATIC* sch = getSchematic( aNetJob->m_filename );
1013
1014 if( !sch )
1016
1017 aJob->SetTitleBlock( sch->RootScreen()->GetTitleBlock() );
1018 sch->Project().ApplyTextVars( aJob->GetVarOverrides() );
1019
1020 // Annotation warning check
1021 SCH_REFERENCE_LIST referenceList;
1022 sch->Hierarchy().GetSymbols( referenceList, SYMBOL_FILTER_NON_POWER );
1023
1024 if( referenceList.GetCount() > 0 )
1025 {
1026 if( referenceList.CheckAnnotation(
1027 []( ERCE_T, const wxString&, SCH_REFERENCE*, SCH_REFERENCE* )
1028 {
1029 // We're only interested in the end result -- either errors or not
1030 } )
1031 > 0 )
1032 {
1033 m_reporter->Report( _( "Warning: schematic has annotation errors, please use the "
1034 "schematic editor to fix them\n" ),
1036 }
1037 }
1038
1039 // Test duplicate sheet names:
1040 ERC_TESTER erc( sch );
1041
1042 if( erc.TestDuplicateSheetNames( false ) > 0 )
1043 m_reporter->Report( _( "Warning: duplicate sheet names.\n" ), RPT_SEVERITY_WARNING );
1044
1045 std::unique_ptr<NETLIST_EXPORTER_XML> xmlNetlist = std::make_unique<NETLIST_EXPORTER_XML>( sch, m_kiway );
1046
1047 wxFileName defaultFn = sch->GetFileName();
1048 defaultFn.SetName( defaultFn.GetName() + "-bom" );
1049 defaultFn.SetExt( FILEEXT::XmlFileExtension );
1050
1051 if( aNetJob->GetConfiguredOutputPath().IsEmpty() )
1052 aNetJob->SetConfiguredOutputPath( defaultFn.GetFullName() );
1053
1054 wxString outPath = JOB::AppendDefaultFileName( aNetJob->GetFullOutputPath( &sch->Project() ),
1055 defaultFn.GetFullName() );
1056
1057 if( !PATHS::EnsurePathExists( outPath, true ) )
1058 {
1059 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1061 }
1062
1063 bool res = xmlNetlist->WriteNetlist( outPath, GNL_OPT_BOM, *m_reporter );
1064
1065 if( !res )
1067
1068 aJob->AddOutput( outPath );
1069
1070 m_reporter->Report( wxString::Format( _( "Wrote bill of materials to '%s'." ), outPath ), RPT_SEVERITY_ACTION );
1071
1072 return CLI::EXIT_CODES::OK;
1073}
1074
1075
1077 LIB_SYMBOL* symbol )
1078{
1079 wxCHECK( symbol, CLI::EXIT_CODES::ERR_UNKNOWN );
1080
1081 std::shared_ptr<LIB_SYMBOL> parent;
1082 LIB_SYMBOL* symbolToPlot = symbol;
1083
1084 // if the symbol is an alias, then the draw items are stored in the root symbol
1085 if( symbol->IsDerived() )
1086 {
1087 parent = symbol->GetRootSymbol();
1088
1089 wxCHECK( parent, CLI::EXIT_CODES::ERR_UNKNOWN );
1090
1091 symbolToPlot = parent.get();
1092 }
1093
1094 // iterate from unit 1, unit 0 would be "all units" which we don't want
1095 for( int unit = 1; unit < symbol->GetUnitCount() + 1; unit++ )
1096 {
1097 for( int bodyStyle = 1; bodyStyle <= symbol->GetBodyStyleCount(); ++bodyStyle )
1098 {
1099 wxString filename;
1100 wxFileName fn;
1101
1102 fn.SetPath( aSvgJob->m_outputDirectory );
1103 fn.SetExt( FILEEXT::SVGFileExtension );
1104
1105 filename = symbol->GetName();
1106
1107 for( wxChar c : wxFileName::GetForbiddenChars( wxPATH_DOS ) )
1108 filename.Replace( c, ' ' );
1109
1110 // Even single units get a unit number in the filename. This simplifies the
1111 // handling of the files as they have a uniform pattern.
1112 // Also avoids aliasing 'sym', unit 2 and 'sym_unit2', unit 1 to the same file.
1113 filename += wxString::Format( "_unit%d", unit );
1114
1115 if( symbol->HasDeMorganBodyStyles() )
1116 {
1117 if( bodyStyle == 2 )
1118 filename += wxS( "_demorgan" );
1119 }
1120 else if( bodyStyle <= (int) symbol->GetBodyStyleNames().size() )
1121 {
1122 filename += wxS( "_" ) + symbol->GetBodyStyleNames()[bodyStyle - 1].Lower();
1123 }
1124
1125 fn.SetName( filename );
1126 m_reporter->Report( wxString::Format( _( "Plotting symbol '%s' unit %d to '%s'\n" ), symbol->GetName(),
1127 unit, fn.GetFullPath() ),
1129
1130 BOX2I symbolBB = GetSymbolPlotBBox( *symbol, unit, bodyStyle, aSvgJob->m_includeHiddenFields );
1131
1132 if( !PlotSymbolToSVG( *symbolToPlot, *symbol, unit, bodyStyle, symbolBB, *aRenderSettings,
1133 aSvgJob->m_blackAndWhite, fn.GetFullPath(), m_reporter ) )
1134 {
1136 }
1137 }
1138 }
1139
1140 if( m_reporter->HasMessageOfSeverity( RPT_SEVERITY_ERROR ) )
1142
1143 return CLI::EXIT_CODES::OK;
1144}
1145
1146
1148{
1149 JOB_SYM_EXPORT_SVG* svgJob = dynamic_cast<JOB_SYM_EXPORT_SVG*>( aJob );
1150
1151 wxCHECK( svgJob, CLI::EXIT_CODES::ERR_UNKNOWN );
1152
1153 wxFileName fn( svgJob->m_libraryPath );
1154 fn.MakeAbsolute();
1155
1156 // When the input is a single symbol file we restrict plotting to the symbols defined in
1157 // that file. Stays empty (no restriction) when the input is a whole library.
1158 wxString singleFileFilter;
1159
1160 auto schLibrary = std::make_unique<SCH_IO_KICAD_SEXPR_LIB_CACHE>( fn.GetFullPath() );
1161
1162 try
1163 {
1164 schLibrary->Load();
1165 }
1166 catch( ... )
1167 {
1168 // A single file holding a derived symbol whose parent is in a sibling file cannot load
1169 // alone. Retry against the enclosing directory, then plot only this file's symbols.
1170 bool recovered = false;
1171
1172 if( !fn.IsDir() && wxDir::Exists( fn.GetPath() ) )
1173 {
1174 try
1175 {
1176 schLibrary = std::make_unique<SCH_IO_KICAD_SEXPR_LIB_CACHE>( fn.GetPath() );
1177 schLibrary->Load();
1178 singleFileFilter = fn.GetFullPath();
1179 recovered = true;
1180 }
1181 catch( ... )
1182 {
1183 // Fall through to the generic load error below.
1184 }
1185 }
1186
1187 if( !recovered )
1188 {
1189 m_reporter->Report( _( "Unable to load library\n" ), RPT_SEVERITY_ERROR );
1191 }
1192 }
1193
1194 if( m_progressReporter )
1195 m_progressReporter->KeepRefreshing();
1196
1197 LIB_SYMBOL* symbol = nullptr;
1198
1199 if( !svgJob->m_symbol.IsEmpty() )
1200 {
1201 // See if the selected symbol exists
1202 symbol = schLibrary->GetSymbol( svgJob->m_symbol );
1203
1204 if( !symbol )
1205 {
1206 m_reporter->Report( _( "There is no symbol selected to save." ) + wxS( "\n" ), RPT_SEVERITY_ERROR );
1208 }
1209 }
1210
1211 if( !svgJob->m_outputDirectory.IsEmpty() && !wxDir::Exists( svgJob->m_outputDirectory ) )
1212 {
1213 if( !wxFileName::Mkdir( svgJob->m_outputDirectory ) )
1214 {
1215 m_reporter->Report( wxString::Format( _( "Unable to create output directory '%s'." ) + wxS( "\n" ),
1216 svgJob->m_outputDirectory ),
1219 }
1220 }
1221
1222 SCH_RENDER_SETTINGS renderSettings;
1224 renderSettings.LoadColors( cs );
1225 renderSettings.SetDefaultPenWidth( DEFAULT_LINE_WIDTH_MILS * schIUScale.IU_PER_MILS );
1226 renderSettings.m_ShowHiddenPins = svgJob->m_includeHiddenPins;
1227 renderSettings.m_ShowHiddenFields = svgJob->m_includeHiddenFields;
1228
1229 int exitCode = CLI::EXIT_CODES::OK;
1230
1231 if( symbol )
1232 {
1233 exitCode = doSymExportSvg( svgJob, &renderSettings, symbol );
1234 }
1235 else
1236 {
1237 // Just plot all the symbols we can
1238 const LIB_SYMBOL_MAP& libSymMap = schLibrary->GetSymbolMap();
1239 const std::map<wxString, wxString>& sourceFiles = schLibrary->GetSymbolSourceFiles();
1240 const wxFileName filterFile( singleFileFilter );
1241
1242 for( const auto& [name, libSymbol] : libSymMap )
1243 {
1244 // When a single file was requested, skip symbols that came from sibling files.
1245 if( !singleFileFilter.IsEmpty() )
1246 {
1247 auto srcIt = sourceFiles.find( name );
1248
1249 if( srcIt == sourceFiles.end() || !wxFileName( srcIt->second ).SameAs( filterFile ) )
1250 continue;
1251 }
1252
1253 if( m_progressReporter )
1254 {
1255 m_progressReporter->AdvancePhase( wxString::Format( _( "Exporting %s" ), name ) );
1256 m_progressReporter->KeepRefreshing();
1257 }
1258
1259 exitCode = doSymExportSvg( svgJob, &renderSettings, libSymbol );
1260
1261 if( exitCode != CLI::EXIT_CODES::OK )
1262 break;
1263 }
1264 }
1265
1266 return exitCode;
1267}
1268
1269
1271{
1272 JOB_SYM_DOWNGRADE* job = dynamic_cast<JOB_SYM_DOWNGRADE*>( aJob );
1273
1274 wxCHECK( job, CLI::EXIT_CODES::ERR_UNKNOWN );
1275
1276 const DOWNGRADE_TARGET* target =
1277 job->m_target.IsEmpty() ? &GetDowngradeTargets().front() : FindDowngradeTarget( job->m_target );
1278
1279 if( !target )
1280 {
1281 m_reporter->Report( wxString::Format( _( "Unknown target version '%s'. Valid targets: %s\n" ), job->m_target,
1285 }
1286
1287 // The cache owns the symbols, so it outlives every use of them
1289 std::vector<LIB_SYMBOL*> symbols;
1290
1291 try
1292 {
1293 pi.EnumerateSymbolLib( symbols, job->m_libraryPath );
1294 }
1295 catch( const IO_ERROR& ioe )
1296 {
1297 m_reporter->Report( wxString::Format( _( "Error loading symbol library '%s'.\n%s" ), job->m_libraryPath,
1298 ioe.What().GetData() ),
1301 }
1302
1303 COMPATIBILITY_REPORT report;
1304
1305 for( const LIB_SYMBOL* symbol : symbols )
1306 report.Merge( ClassifyLibSymbolForDowngrade( symbol, *target, job->m_dropInsteadOfApproximate ) );
1307
1308 job->m_report = report;
1309 report.Print( m_reporter );
1310
1311 if( job->m_dryRun )
1313
1314 if( report.IsBlocked() )
1315 {
1316 m_reporter->Report( _( "Cannot export: the library uses features the target cannot represent.\n" ),
1319 }
1320
1321 if( report.IsLossy() && !job->m_force )
1322 {
1323 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
1326 }
1327
1328 wxString error;
1329
1331 {
1332 m_reporter->Report( error + wxS( "\n" ), RPT_SEVERITY_ERROR );
1334 }
1335
1336 DOWNGRADE_OUTPUT_DIRECTORIES outputDirectories;
1337 wxFileName output( job->m_outputLibraryPath );
1338
1339 if( !outputDirectories.Create( output.GetPath() ) )
1340 {
1341 m_reporter->Report( _( "Could not create the output folder.\n" ), RPT_SEVERITY_ERROR );
1343 }
1344
1345 // Staged so a failed write leaves no half-written library at the destination
1346 DOWNGRADE_FILE_TRANSACTION transaction;
1347 wxString staged = transaction.Stage( job->m_outputLibraryPath );
1348
1349 if( staged.IsEmpty() )
1350 {
1351 m_reporter->Report( _( "Could not export the downgraded library.\n" ), RPT_SEVERITY_ERROR );
1353 }
1354
1355 try
1356 {
1357 for( LIB_SYMBOL* symbol : symbols )
1359
1360 SaveSymbolLibraryForTarget( symbols, staged, *target );
1361 }
1362 catch( const IO_ERROR& ioe )
1363 {
1364 m_reporter->Report(
1365 wxString::Format( _( "Error exporting '%s'.\n%s" ), job->m_libraryPath, ioe.What().GetData() ),
1368 }
1369
1370 wxString failedDestination = transaction.Commit();
1371
1372 if( !failedDestination.IsEmpty() )
1373 {
1374 m_reporter->Report( wxString::Format( _( "Could not replace '%s'.\n" ), failedDestination ),
1377 }
1378
1379 outputDirectories.Commit();
1380 m_reporter->Report( _( "Downgraded symbol library\n" ), RPT_SEVERITY_INFO );
1381
1383}
1384
1385
1387{
1388 JOB_SYM_UPGRADE* upgradeJob = dynamic_cast<JOB_SYM_UPGRADE*>( aJob );
1389
1390 wxCHECK( upgradeJob, CLI::EXIT_CODES::ERR_UNKNOWN );
1391
1392 wxFileName fn( upgradeJob->m_libraryPath );
1393 fn.MakeAbsolute();
1394
1395 SCH_IO_MGR::SCH_FILE_T fileType = SCH_IO_MGR::GuessPluginTypeFromLibPath( fn.GetFullPath() );
1396
1397 if( !upgradeJob->m_outputLibraryPath.IsEmpty() )
1398 {
1399 if( wxFile::Exists( upgradeJob->m_outputLibraryPath ) )
1400 {
1401 m_reporter->Report( _( "Output path must not conflict with existing path\n" ), RPT_SEVERITY_ERROR );
1402
1404 }
1405 }
1406 else if( fileType != SCH_IO_MGR::SCH_KICAD )
1407 {
1408 m_reporter->Report( _( "Output path must be specified to convert legacy and non-KiCad libraries\n" ),
1410
1412 }
1413
1414 if( fileType == SCH_IO_MGR::SCH_KICAD )
1415 {
1416 SCH_IO_KICAD_SEXPR_LIB_CACHE schLibrary( fn.GetFullPath() );
1417
1418 try
1419 {
1420 schLibrary.Load();
1421 }
1422 catch( ... )
1423 {
1424 m_reporter->Report( _( "Unable to load library\n" ), RPT_SEVERITY_ERROR );
1426 }
1427
1428 if( m_progressReporter )
1429 m_progressReporter->KeepRefreshing();
1430
1431 bool shouldSave =
1433
1434 if( shouldSave )
1435 {
1436 m_reporter->Report( _( "Saving symbol library in updated format\n" ), RPT_SEVERITY_ACTION );
1437
1438 try
1439 {
1440 if( !upgradeJob->m_outputLibraryPath.IsEmpty() )
1441 schLibrary.SetFileName( upgradeJob->m_outputLibraryPath );
1442
1443 schLibrary.SetModified();
1444 schLibrary.Save();
1445 }
1446 catch( ... )
1447 {
1448 m_reporter->Report( ( "Unable to save library\n" ), RPT_SEVERITY_ERROR );
1450 }
1451 }
1452 else
1453 {
1454 m_reporter->Report( _( "Symbol library was not updated\n" ), RPT_SEVERITY_ERROR );
1455 }
1456 }
1457 else
1458 {
1459 if( !SCH_IO_MGR::ConvertLibrary( nullptr, fn.GetAbsolutePath(), upgradeJob->m_outputLibraryPath, m_reporter ) )
1460 {
1461 m_reporter->Report( ( "Unable to convert library\n" ), RPT_SEVERITY_ERROR );
1463 }
1464 }
1465
1466 return CLI::EXIT_CODES::OK;
1467}
1468
1469
1471{
1472 JOB_SCH_ERC* ercJob = dynamic_cast<JOB_SCH_ERC*>( aJob );
1473
1474 wxCHECK( ercJob, CLI::EXIT_CODES::ERR_UNKNOWN );
1475
1476 SCHEMATIC* sch = getSchematic( ercJob->m_filename );
1477
1478 if( !sch )
1480
1481 aJob->SetTitleBlock( sch->RootScreen()->GetTitleBlock() );
1482 sch->Project().ApplyTextVars( aJob->GetVarOverrides() );
1483
1484 wxFileName defaultFn = sch->GetFileName();
1485 defaultFn.SetName( defaultFn.GetName() + wxS( "-erc" ) );
1486
1488 defaultFn.SetExt( FILEEXT::JsonFileExtension );
1489 else
1490 defaultFn.SetExt( FILEEXT::ReportFileExtension );
1491
1492 // Use a transient working path so an empty configured output filename isn't persisted
1493 // back into the jobset file. Mirrors the PCB DRC handler.
1494 if( ercJob->GetConfiguredOutputPath().IsEmpty() )
1495 ercJob->SetWorkingOutputPath( defaultFn.GetFullName() );
1496
1497 wxString outPath = JOB::AppendDefaultFileName( ercJob->GetFullOutputPath( &sch->Project() ),
1498 defaultFn.GetFullName() );
1499
1500 if( !PATHS::EnsurePathExists( outPath, true ) )
1501 {
1502 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1504 }
1505
1506 EDA_UNITS units;
1507
1508 switch( ercJob->m_units )
1509 {
1510 case JOB_SCH_ERC::UNITS::INCH: units = EDA_UNITS::INCH; break;
1511 case JOB_SCH_ERC::UNITS::MILS: units = EDA_UNITS::MILS; break;
1512 case JOB_SCH_ERC::UNITS::MM: units = EDA_UNITS::MM; break;
1513 default: units = EDA_UNITS::MM; break;
1514 }
1515
1516 std::shared_ptr<SHEETLIST_ERC_ITEMS_PROVIDER> markersProvider =
1517 std::make_shared<SHEETLIST_ERC_ITEMS_PROVIDER>( sch );
1518
1519 // Running ERC requires libraries be loaded, so make sure they have been
1521 adapter->AsyncLoad();
1522 adapter->BlockUntilLoaded();
1523
1524 ERC_TESTER ercTester( sch );
1525
1526 std::unique_ptr<DS_PROXY_VIEW_ITEM> drawingSheet( getDrawingSheetProxyView( sch ) );
1527 SCH_EDIT_FRAME* editFrame = nullptr;
1528
1529 if( Pgm().IsGUI() )
1530 {
1531 editFrame = static_cast<SCH_EDIT_FRAME*>( m_kiway->Player( FRAME_SCH, false ) );
1532
1533 if( editFrame && &editFrame->Schematic() != sch )
1534 editFrame = nullptr;
1535 }
1536
1537 if( editFrame )
1538 editFrame->ClearErcMarkers();
1539
1540 ercTester.RunTests( drawingSheet.get(), editFrame, m_kiway->KiFACE( KIWAY::FACE_CVPCB ), &sch->Project(),
1542
1543 if( editFrame )
1544 editFrame->RefreshErcMarkers();
1545
1546 markersProvider->SetSeverities( ercJob->m_severity );
1547
1548 m_reporter->Report( wxString::Format( _( "Found %d violations\n" ), markersProvider->GetCount() ),
1550
1551 ERC_REPORT reportWriter( sch, units, markersProvider );
1552
1553 bool wroteReport = false;
1554
1556 wroteReport = reportWriter.WriteJsonReport( outPath );
1557 else
1558 wroteReport = reportWriter.WriteTextReport( outPath );
1559
1560 if( !wroteReport )
1561 {
1562 m_reporter->Report( wxString::Format( _( "Unable to save ERC report to %s\n" ), outPath ), RPT_SEVERITY_ERROR );
1564 }
1565
1566 m_reporter->Report( wxString::Format( _( "Saved ERC Report to %s\n" ), outPath ), RPT_SEVERITY_ACTION );
1567
1568 if( ercJob->m_exitCodeViolations )
1569 {
1570 if( markersProvider->GetCount() > 0 )
1572 }
1573
1575}
1576
1577
1579{
1580 JOB_SCH_UPGRADE* aUpgradeJob = dynamic_cast<JOB_SCH_UPGRADE*>( aJob );
1581
1582 if( aUpgradeJob == nullptr )
1584
1585 SCHEMATIC* sch = getSchematic( aUpgradeJob->m_filename, false );
1586
1587 if( !sch )
1589
1590 bool shouldSave = aUpgradeJob->m_force;
1591
1593 shouldSave = true;
1594
1595 if( !shouldSave )
1596 {
1597 m_reporter->Report( _( "Schematic file was not updated\n" ), RPT_SEVERITY_ERROR );
1599 }
1600
1601 // needs an absolute path
1602 wxFileName schPath( aUpgradeJob->m_filename );
1603 schPath.MakeAbsolute();
1604 const wxString schFullPath = schPath.GetFullPath();
1605
1606 try
1607 {
1608 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
1609 SCH_SHEET* loadedSheet = pi->LoadSchematicFile( schFullPath, sch );
1610 pi->SaveSchematicFile( schFullPath, loadedSheet, sch );
1611 }
1612 catch( const IO_ERROR& ioe )
1613 {
1614 wxString msg =
1615 wxString::Format( _( "Error saving schematic file '%s'.\n%s" ), schFullPath, ioe.What().GetData() );
1616 m_reporter->Report( msg, RPT_SEVERITY_ERROR );
1618 }
1619
1620 m_reporter->Report( _( "Successfully saved schematic file using the latest format\n" ), RPT_SEVERITY_INFO );
1621
1623}
1624
1625
1626// Unloads a project that was only opened for the duration of a job.
1628{
1632
1634 {
1635 if( m_active )
1636 m_mgr.UnloadProject( m_project, false );
1637 }
1638};
1639
1640
1641// Classify library symbols so their losses appear in the report.
1642static void classifySymbolLibraries( const wxString& aDir, const DOWNGRADE_TARGET& aTarget,
1643 COMPATIBILITY_REPORT& aReport, bool aDropInsteadOfApproximate )
1644{
1645 wxArrayString files;
1646 wxDir::GetAllFiles( aDir, &files, wxT( "*.kicad_sym" ) );
1647
1648 for( const wxString& file : files )
1649 {
1650 if( IsDowngradeWorkingArtifact( file ) )
1651 continue;
1652
1653 try
1654 {
1656 std::vector<LIB_SYMBOL*> symbols;
1657 pi.EnumerateSymbolLib( symbols, file );
1658
1659 for( const LIB_SYMBOL* symbol : symbols )
1660 {
1661 aReport.Merge( ClassifyLibSymbolForDowngrade( symbol, aTarget, aDropInsteadOfApproximate ) );
1662 }
1663 }
1664 catch( const IO_ERROR& )
1665 {
1666 // A library that fails to load is caught later by the downgrade pass itself.
1667 }
1668 }
1669}
1670
1671
1672// Downgrade every .kicad_sym under the folder in place. Returns the first file the target could
1673// not open, or empty when all are safe.
1674static wxString downgradeSymbolLibraries( const wxString& aDir, const DOWNGRADE_TARGET& aTarget,
1675 bool aDropInsteadOfApproximate,
1676 DOWNGRADE_FILE_TRANSACTION* aTransaction = nullptr,
1677 wxString* aRecoveryError = nullptr )
1678{
1679 auto convert = [&]( const wxString& aFile, const wxString& aTmp ) -> DOWNGRADE_FILE_RESULT
1680 {
1682 std::vector<LIB_SYMBOL*> symbols;
1683 pi.EnumerateSymbolLib( symbols, aFile );
1684
1685 // The format wants parents before the symbols that inherit from them, so sort by depth.
1686 std::stable_sort( symbols.begin(), symbols.end(),
1687 []( const LIB_SYMBOL* a, const LIB_SYMBOL* b )
1688 {
1689 return a->GetInheritanceDepth() < b->GetInheritanceDepth();
1690 } );
1691
1692 for( LIB_SYMBOL* symbol : symbols )
1693 DowngradeLibSymbolInPlace( symbol, aTarget, aDropInsteadOfApproximate );
1694
1695 SaveSymbolLibraryForTarget( symbols, aTmp, aTarget );
1697 };
1698
1700 aDir, wxT( "*.kicad_sym" ), aTarget.m_symLibVersion,
1701 [&]( const wxString& aText )
1702 {
1703 return FindUnsupportedSchToken( aText, aTarget );
1704 },
1705 convert, aTransaction, aRecoveryError );
1706}
1707
1708
1710{
1711 JOB_SCH_DOWNGRADE* job = dynamic_cast<JOB_SCH_DOWNGRADE*>( aJob );
1712
1713 if( job == nullptr )
1715
1716 const DOWNGRADE_TARGET* target =
1717 job->m_target.IsEmpty() ? &GetDowngradeTargets().front() : FindDowngradeTarget( job->m_target );
1718
1719 if( target == nullptr )
1720 {
1721 m_reporter->Report( wxString::Format( _( "Unknown target version '%s'. Valid targets: %s\n" ), job->m_target,
1725 }
1726
1727 if( !job->m_libraryDir.IsEmpty() && !wxDirExists( job->m_libraryDir ) )
1728 {
1729 m_reporter->Report( wxString::Format( _( "The library folder '%s' does not exist.\n" ), job->m_libraryDir ),
1732 }
1733
1734 DOWNGRADE_OUTPUT_DIRECTORIES outputDirectories;
1735 wxString libraryWorkDir = job->m_libraryDir;
1736 wxString libraryCopyDir;
1737 wxString outputError;
1738
1739 if( !job->m_inPlace && !job->m_dryRun )
1740 {
1741 wxFileName output = wxFileName::DirName( job->m_outputDir );
1742
1743 if( job->m_outputDir.IsEmpty() || !output.MakeAbsolute()
1744 || !ValidateFreshDowngradeOutput( output.GetPath(), outputError ) )
1745 {
1746 if( outputError.IsEmpty() )
1747 outputError = _( "An output folder is required. Use --output." );
1748
1749 m_reporter->Report( outputError + wxS( "\n" ), RPT_SEVERITY_ERROR );
1751 }
1752
1753 job->m_outputDir = output.GetPath();
1754 }
1755
1756 if( !job->m_libraryDir.IsEmpty() )
1757 {
1758 if( !ValidateDowngradeLibrarySource( job->m_libraryDir, outputError ) )
1759 {
1760 m_reporter->Report( outputError + wxS( "\n" ), RPT_SEVERITY_ERROR );
1762 }
1763
1764 if( !job->m_inPlace && !job->m_dryRun )
1765 {
1766 libraryCopyDir = DowngradeLibraryCopyPath( job->m_libraryDir, job->m_outputDir );
1767
1768 if( !ValidateDowngradeLibraryCopy( job->m_libraryDir, libraryCopyDir, outputError ) )
1769 {
1770 m_reporter->Report( outputError + wxS( "\n" ), RPT_SEVERITY_ERROR );
1772 }
1773 }
1774 }
1775
1776 auto prepareOutput = [&]() -> bool
1777 {
1778 if( job->m_inPlace )
1779 return true;
1780
1781 if( !outputDirectories.Create( job->m_outputDir, true ) )
1782 {
1783 m_reporter->Report( _( "Could not create the schematic output folder.\n" ), RPT_SEVERITY_ERROR );
1784 return false;
1785 }
1786
1787 if( !libraryCopyDir.IsEmpty() )
1788 {
1789 if( !CopyDowngradeLibraryDirectory( job->m_libraryDir, libraryCopyDir, outputDirectories, outputError ) )
1790 {
1791 m_reporter->Report( outputError + wxS( "\n" ), RPT_SEVERITY_ERROR );
1792 return false;
1793 }
1794
1795 libraryWorkDir = libraryCopyDir;
1796 }
1797
1798 return true;
1799 };
1800
1801 auto downgradeLibraries = [&]( DOWNGRADE_FILE_TRANSACTION* aTransaction = nullptr ) -> int
1802 {
1803 if( job->m_dryRun || job->m_libraryDir.IsEmpty() )
1805
1806 try
1807 {
1808 wxString recoveryError;
1809 wxString badLib = downgradeSymbolLibraries( libraryWorkDir, *target, job->m_dropInsteadOfApproximate,
1810 aTransaction, &recoveryError );
1811
1812 if( !badLib.IsEmpty() )
1813 {
1814 m_reporter->Report( wxString::Format( _( "Cannot export: symbol library '%s' uses a feature %s "
1815 "cannot open.\n" ),
1816 badLib, target->m_name ),
1818
1819 if( !recoveryError.IsEmpty() )
1820 m_reporter->Report( recoveryError, RPT_SEVERITY_ERROR );
1821
1823 }
1824 }
1825 catch( const IO_ERROR& ioe )
1826 {
1827 m_reporter->Report(
1828 wxString::Format( _( "Error downgrading symbol libraries.\n%s" ), ioe.What().GetData() ),
1831 }
1832
1834 };
1835
1836 // No schematic to process. Do the libraries and stop.
1837 if( job->m_filename.IsEmpty() )
1838 {
1839 if( !job->m_variant.IsEmpty() )
1840 {
1841 m_reporter->Report( _( "Variants do not apply to a library downgrade.\n" ), RPT_SEVERITY_ERROR );
1843 }
1844
1845 if( !job->m_libraryDir.IsEmpty() )
1846 {
1847 COMPATIBILITY_REPORT report;
1849 job->m_report = report;
1850 job->m_report.Print( m_reporter );
1851
1852 if( !job->m_dryRun && report.IsBlocked() )
1853 {
1854 m_reporter->Report( _( "Cannot export: the libraries use features the target cannot represent.\n" ),
1857 }
1858
1859 if( !job->m_dryRun && report.IsLossy() && !job->m_force )
1860 {
1861 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
1864 }
1865 }
1866
1867 if( job->m_dryRun )
1869
1870 if( !prepareOutput() )
1872
1873 int result = downgradeLibraries();
1874
1876 outputDirectories.Commit();
1877
1878 return result;
1879 }
1880
1881 // The project and schematic loaders require absolute paths.
1882 wxFileName schInputFn( job->m_filename );
1883 schInputFn.MakeAbsolute();
1884 job->m_filename = schInputFn.GetFullPath();
1885
1886 // Load a private copy, never the live editor schematic. A transient project keeps it apart
1887 // from anything open in the GUI.
1889
1890 wxFileName projectFn( job->m_filename );
1891 projectFn.SetExt( FILEEXT::ProjectFileExtension );
1892
1893 PROJECT* projectPtr = mgr.GetProject( projectFn.GetFullPath() );
1894 bool createdTransientProject = false;
1895
1896 if( !projectPtr )
1897 {
1898 mgr.LoadProject( projectFn.GetFullPath(), false );
1899 projectPtr = mgr.GetProject( projectFn.GetFullPath() );
1900 createdTransientProject = ( projectPtr != nullptr );
1901 }
1902
1903 if( !projectPtr )
1904 {
1905 m_reporter->Report( _( "Could not establish a project for the schematic\n" ), RPT_SEVERITY_ERROR );
1907 }
1908
1909 TRANSIENT_PROJECT_GUARD transientProjectGuard{ mgr, projectPtr, createdTransientProject };
1910
1912
1913 // Binding a SCHEMATIC to a project reallocates that project's ERC and schematic settings. When
1914 // we borrowed a live project, snapshot the pointers so we can put them back. This relies on
1915 // ~SCHEMATIC not calling SetProject.
1916 PROJECT_FILE& projectFile = projectPtr->GetProjectFile();
1917
1918 // The settings loader repairs missing root filenames as if this were a renamed
1919 // template. That is unsafe during export: check the stored list before using the
1920 // repaired in-memory list, or a missing sibling can be replaced by the main sheet.
1921 if( auto storedRoots = projectFile.GetJson( "schematic.top_level_sheets" ); storedRoots && storedRoots->is_array() )
1922 {
1923 for( const auto& info : *storedRoots )
1924 {
1925 if( !info.contains( "filename" ) || !info["filename"].is_string() )
1926 continue;
1927
1928 const wxString filename = wxString::FromUTF8( info["filename"].get<std::string>() );
1929 wxFileName rootFile( filename );
1930 rootFile.MakeAbsolute( projectPtr->GetProjectPath() );
1931
1932 if( filename.IsEmpty() || !rootFile.FileExists() )
1933 {
1934 m_reporter->Report( wxString::Format( _( "Cannot export: top-level schematic '%s' is missing.\n" ),
1935 rootFile.GetFullPath() ),
1938 }
1939 }
1940 }
1941
1942 ERC_SETTINGS* savedErc = createdTransientProject ? nullptr : projectFile.m_ErcSettings;
1943 SCHEMATIC_SETTINGS* savedSch = createdTransientProject ? nullptr : projectFile.m_SchematicSettings;
1944
1945 std::unique_ptr<SCHEMATIC> owned = std::make_unique<SCHEMATIC>( projectPtr );
1946 owned->CreateDefaultScreens();
1947 SCHEMATIC* sch = owned.get();
1948
1949 struct SCH_PROJECT_GUARD
1950 {
1951 SCHEMATIC* m_sch;
1952 PROJECT* m_project;
1953 bool m_created;
1954 ERC_SETTINGS* m_savedErc;
1955 SCHEMATIC_SETTINGS* m_savedSch;
1956
1957 ~SCH_PROJECT_GUARD()
1958 {
1959 if( m_created )
1960 {
1961 m_sch->SetProject( nullptr );
1962 }
1963 else
1964 {
1965 // Drop the settings this schematic made and put the live project's own back.
1966 PROJECT_FILE& pf = m_project->GetProjectFile();
1967 delete pf.m_ErcSettings;
1968 delete pf.m_SchematicSettings;
1969 pf.m_ErcSettings = m_savedErc;
1970 pf.m_SchematicSettings = m_savedSch;
1971 }
1972 }
1973 } schProjectGuard{ sch, projectPtr, createdTransientProject, savedErc, savedSch };
1974
1975 try
1976 {
1977 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
1978 SCH_SHEET* root = pi->LoadSchematicFile( job->m_filename, sch );
1979
1980 if( !root )
1981 {
1982 m_reporter->Report( _( "Failed to load schematic\n" ), RPT_SEVERITY_ERROR );
1984 }
1985
1986 // The loader collects sub-sheet errors instead of throwing. An incomplete hierarchy must
1987 // not be exported, or missing sheets would be written out empty.
1988 if( !pi->GetError().IsEmpty() )
1989 {
1990 m_reporter->Report( wxString::Format( _( "Cannot export: the schematic did not load "
1991 "completely.\n%s" ),
1992 pi->GetError() ),
1995 }
1996
1997 // The loader does not install the hierarchy. Without this the sheet walk below sees only
1998 // the empty default screens and the export silently does nothing.
1999 std::vector<SCH_SHEET*> topLevelSheets = sch->GetTopLevelSheets();
2000 bool rootIsTopLevel = std::find( topLevelSheets.begin(), topLevelSheets.end(), root ) != topLevelSheets.end();
2001 bool rootIsVirtualRoot = root == &sch->Root() || root->IsVirtualRootSheet();
2002 bool changed = false;
2003
2004 if( !rootIsTopLevel && !rootIsVirtualRoot )
2005 {
2006 topLevelSheets = { root };
2007 changed = true;
2008 }
2009
2010 // A flat hierarchy records its other top-level sheets only in the project file. They
2011 // must load too, or classification never sees them and their trees never convert.
2012 if( !rootIsVirtualRoot )
2013 {
2014 for( const TOP_LEVEL_SHEET_INFO& info : projectFile.GetTopLevelSheets() )
2015 {
2016 wxFileName fn( projectPtr->GetProjectPath(), info.filename );
2017 fn.MakeAbsolute();
2018
2019 if( fn.GetFullPath() == job->m_filename )
2020 continue;
2021
2022 SCH_SHEET* sibling = pi->LoadSchematicFile( fn.GetFullPath(), sch );
2023
2024 if( !sibling || !pi->GetError().IsEmpty() )
2025 {
2026 m_reporter->Report( wxString::Format( _( "Cannot export: the schematic did not load "
2027 "completely.\n%s" ),
2028 pi->GetError() ),
2031 }
2032
2033 if( info.uuid != niluuid )
2034 const_cast<KIID&>( sibling->m_Uuid ) = info.uuid;
2035
2036 sibling->SetName( info.name );
2037 topLevelSheets.push_back( sibling );
2038 changed = true;
2039 }
2040 }
2041
2042 if( changed )
2043 sch->SetTopLevelSheets( topLevelSheets );
2044
2045 sch->LoadVariants();
2046 }
2047 catch( const IO_ERROR& ioe )
2048 {
2049 m_reporter->Report( wxString::Format( _( "Error loading schematic: %s\n" ), ioe.What() ), RPT_SEVERITY_ERROR );
2051 }
2052
2053 // A screen can be shared by several sheets, so gather each one once.
2054 std::set<SCH_SCREEN*> seen;
2055 std::vector<std::pair<SCH_SHEET*, SCH_SCREEN*>> screens;
2056
2057 for( const SCH_SHEET_PATH& path : sch->BuildUnorderedSheetList() )
2058 {
2059 SCH_SHEET* sheet = path.Last();
2060 SCH_SCREEN* screen = sheet ? sheet->GetScreen() : nullptr;
2061
2062 if( screen && seen.insert( screen ).second )
2063 screens.emplace_back( sheet, screen );
2064 }
2065
2066 COMPATIBILITY_REPORT report;
2067
2068 // Variants (20250922) are schematic-wide, so report them once for the whole schematic.
2069 int variantCount = static_cast<int>( sch->GetVariantNames().size() );
2070
2071 if( target->m_schVersion < SCH_VER_VARIANTS && variantCount > 0 )
2072 {
2073 job->m_foundVariants.assign( sch->GetVariantNames().begin(), sch->GetVariantNames().end() );
2074 }
2075
2076 if( !job->m_variant.IsEmpty() )
2077 {
2078 if( target->m_schVersion >= SCH_VER_VARIANTS )
2079 {
2080 m_reporter->Report( _( "The target supports variants, so there is nothing to flatten.\n" ),
2083 }
2084
2085 if( !sch->GetVariantNames().count( job->m_variant ) )
2086 {
2087 m_reporter->Report( wxString::Format( _( "The schematic has no variant named '%s'.\n" ), job->m_variant ),
2090 }
2091
2092 wxString conflict;
2093
2094 if( !FlattenSchematicVariant( *sch, job->m_variant, &conflict ) )
2095 {
2096 m_reporter->Report(
2097 wxString::Format( _( "Cannot export selected variant '%s': %s" ), job->m_variant, conflict )
2098 + wxS( "\n" ),
2101 }
2102 }
2103
2104 for( const auto& [sheet, screen] : screens )
2105 {
2106 report.Merge( ClassifyScreenForDowngrade( screen, *target, job->m_dropInsteadOfApproximate ) );
2107 }
2108
2109 if( target->m_schVersion < SCH_VER_VARIANTS && variantCount > 0 )
2110 {
2111 report.Add( DOWNGRADE_BUCKET::DROP, _( "Schematic variants" ), _( "The variant registry is removed." ),
2112 variantCount );
2113 }
2114
2115 report.Merge( ClassifySchematicStructureForDowngrade( *sch, *target ) );
2116
2117 // Net chains are connectivity-derived and a plain reload drops them. Detect them in the source
2118 // so the user is warned.
2119 if( target->m_schVersion < SCH_VER_NET_CHAINS )
2120 {
2121 wxString rootContent;
2122 wxFFile rootFile( job->m_filename, wxT( "rb" ) );
2123
2124 if( rootFile.IsOpened() && rootFile.ReadAll( &rootContent ) && rootContent.Contains( wxT( "(net_chain" ) ) )
2125 {
2126 report.Add( DOWNGRADE_BUCKET::DROP, _( "Net chains" ),
2127 _( "No equivalent in the target. Net chain grouping is removed." ), 1 );
2128 }
2129 }
2130
2131 // Library losses belong in the report the user approves too.
2132 if( !job->m_libraryDir.IsEmpty() )
2134
2135 job->m_report = report;
2136
2137 report.Print( m_reporter );
2138
2139 if( job->m_dryRun )
2141
2142 if( report.IsBlocked() )
2143 {
2144 m_reporter->Report( _( "Cannot export: the schematic uses features the target cannot represent.\n" ),
2147 }
2148
2149 if( report.IsLossy() && !job->m_force )
2150 {
2151 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
2154 }
2155
2156 if( !libraryCopyDir.IsEmpty() )
2157 {
2158 wxFileName base( job->m_filename );
2159 base.MakeAbsolute();
2160 const wxString rootPrefix = wxFileName::DirName( base.GetPath() ).GetPathWithSep();
2161 std::vector<wxString> destinations;
2162
2163 for( const auto& [sheet, screen] : screens )
2164 {
2165 wxFileName source( screen->GetFileName() );
2166
2167 if( !source.IsAbsolute() )
2168 source.MakeAbsolute( base.GetPath() );
2169
2170 source.Normalize( wxPATH_NORM_DOTS );
2171 const wxString sourcePath = source.GetFullPath();
2172 const bool contained = wxFileName::IsCaseSensitive() ? sourcePath.StartsWith( rootPrefix )
2173 : sourcePath.Lower().StartsWith( rootPrefix.Lower() );
2174
2175 if( !contained )
2176 {
2177 m_reporter->Report(
2178 wxString::Format( _( "Cannot export: sheet '%s' lies outside the project folder.\n" ),
2179 sourcePath ),
2182 }
2183
2184 destinations.push_back( job->m_outputDir + wxFileName::GetPathSeparator()
2185 + sourcePath.Mid( rootPrefix.length() ) );
2186 }
2187
2188 wxFileName projectOutput = projectFn;
2189 projectOutput.SetPath( job->m_outputDir );
2190 destinations.push_back( projectOutput.GetFullPath() );
2191 std::error_code error;
2192 wxString library =
2193 DowngradeWxPath( std::filesystem::weakly_canonical( DowngradeNativePath( libraryCopyDir ), error ) );
2194
2195 if( error )
2196 {
2197 m_reporter->Report( _( "The library output path is not accessible.\n" ), RPT_SEVERITY_ERROR );
2199 }
2200
2201 for( const wxString& destination : destinations )
2202 {
2203 wxString path =
2204 DowngradeWxPath( std::filesystem::weakly_canonical( DowngradeNativePath( destination ), error ) );
2205
2206 if( error )
2207 {
2208 m_reporter->Report( _( "The schematic output path is not accessible.\n" ), RPT_SEVERITY_ERROR );
2210 }
2211
2212 wxString libraryPath = library;
2213
2214 if( !wxFileName::IsCaseSensitive() )
2215 {
2216 path.MakeLower();
2217 libraryPath.MakeLower();
2218 }
2219
2220 const wxString separator( wxFileName::GetPathSeparator() );
2221
2222 if( path == libraryPath || path.StartsWith( libraryPath + separator )
2223 || libraryPath.StartsWith( path + separator ) )
2224 {
2225 m_reporter->Report( _( "The copied library folder overlaps a schematic or project output path. "
2226 "Choose a different library folder.\n" ),
2229 }
2230 }
2231 }
2232
2233 if( !prepareOutput() )
2235
2236 if( target->m_schVersion < SCH_VER_VARIANTS )
2237 {
2238 std::vector<wxString> variants( sch->GetVariantNames().begin(), sch->GetVariantNames().end() );
2239
2240 for( const wxString& name : variants )
2241 sch->DeleteVariant( name, nullptr /* no undo */ );
2242 }
2243
2244 // Keep designs, companion metadata, and libraries staged until every file is verified.
2245 DOWNGRADE_FILE_TRANSACTION transaction;
2246 wxString currentTemp;
2247
2248 try
2249 {
2250 wxFileName base( job->m_filename );
2251 base.MakeAbsolute();
2252
2253 for( const auto& [sheet, screen] : screens )
2254 {
2255 DowngradeScreenInPlace( screen, *target, job->m_dropInsteadOfApproximate );
2256
2257 wxFileName screenFn( screen->GetFileName() );
2258
2259 if( !screenFn.IsAbsolute() )
2260 screenFn.MakeAbsolute( base.GetPath() );
2261
2262 // Resolve embedded dot segments, or an absolute path with ../ could sidestep the check.
2263 screenFn.Normalize( wxPATH_NORM_DOTS );
2264
2265 // Never write outside the tree that holds the root schematic. A sheet with an absolute
2266 // or ../ path would otherwise overwrite the user's original shared sheet.
2267 wxFileName rootDir( base.GetPath(), wxEmptyString );
2268
2269 wxString screenPath = screenFn.GetFullPath();
2270 wxString rootPrefix = rootDir.GetPathWithSep();
2271
2272 // Case-insensitive filesystems must not let a case mismatch sidestep the check.
2273 bool contained = wxFileName::IsCaseSensitive() ? screenPath.StartsWith( rootPrefix )
2274 : screenPath.Lower().StartsWith( rootPrefix.Lower() );
2275
2276 if( !contained )
2277 {
2278 m_reporter->Report( wxString::Format( _( "Cannot export: sheet '%s' lies outside the project "
2279 "folder.\n" ),
2280 screenFn.GetFullPath() ),
2283 }
2284
2285 wxString finalPath = screenFn.GetFullPath();
2286
2287 // With an output folder, mirror the sheet's place in the tree there instead of
2288 // rewriting the original.
2289 if( !job->m_outputDir.IsEmpty() )
2290 {
2291 wxFileName destFn( job->m_outputDir + wxFileName::GetPathSeparator()
2292 + screenPath.Mid( rootPrefix.length() ) );
2293
2294 if( !wxDirExists( destFn.GetPath() )
2295 && !wxFileName::Mkdir( destFn.GetPath(), wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
2296 {
2297 m_reporter->Report(
2298 wxString::Format( _( "Could not create the output folder '%s'.\n" ), destFn.GetPath() ),
2301 }
2302
2303 finalPath = destFn.GetFullPath();
2304 }
2305
2306 if( !job->m_inPlace && !ValidateFreshDowngradeOutput( finalPath, outputError ) )
2307 THROW_IO_ERROR( outputError );
2308
2309 currentTemp = transaction.Stage( finalPath );
2310
2311 if( currentTemp.IsEmpty() )
2312 THROW_IO_ERROR( _( "Could not stage the schematic export." ) );
2313
2314 SaveSchematicForTarget( sheet, sch, currentTemp, *target );
2315
2316 wxString unsupported;
2317
2318 bool good = VerifyDowngradedFile(
2319 currentTemp, target->m_schVersion,
2320 [&]( const wxString& aText )
2321 {
2322 return FindUnsupportedSchToken( aText, *target );
2323 },
2324 &unsupported );
2325
2326 if( !good )
2327 {
2328 if( !unsupported.IsEmpty() )
2329 m_reporter->Report( wxString::Format( _( "Cannot export: the result still uses '%s', which %s "
2330 "cannot open. This feature has no downgrade rule "
2331 "yet.\n" ),
2332 unsupported, target->m_name ),
2334 else
2335 m_reporter->Report(
2336 wxString::Format( _( "Cannot export: could not verify '%s'.\n" ), screenFn.GetFullPath() ),
2338
2340 }
2341
2342 currentTemp.Clear();
2343 }
2344
2345 if( target->m_schVersion >= SCH_VER_VARIANTS )
2346 {
2347 nlohmann::json document = nlohmann::json::object();
2348 wxString content;
2349
2350 if( projectFn.FileExists() )
2351 {
2352 wxFFile sourceProject( projectFn.GetFullPath(), wxT( "rb" ) );
2353
2354 if( !sourceProject.IsOpened() || !sourceProject.ReadAll( &content ) )
2355 THROW_IO_ERROR( _( "Could not read the schematic project settings." ) );
2356
2357 try
2358 {
2359 document = nlohmann::json::parse( content.ToStdString( wxConvUTF8 ) );
2360 }
2361 catch( const nlohmann::json::exception& )
2362 {
2363 THROW_IO_ERROR( _( "Could not read the schematic project settings." ) );
2364 }
2365 }
2366
2367 if( !document.is_object() )
2368 THROW_IO_ERROR( _( "The schematic project settings are invalid." ) );
2369
2370 nlohmann::json aliases = nlohmann::json::object();
2371
2372 for( const auto& alias : sch->GetAllBusAliases() )
2373 {
2374 nlohmann::json members = nlohmann::json::array();
2375
2376 for( const wxString& member : alias->Members() )
2377 members.push_back( member.ToStdString( wxConvUTF8 ) );
2378
2379 aliases[alias->GetName().ToStdString( wxConvUTF8 )] = std::move( members );
2380 }
2381
2382 if( !document.contains( "schematic" ) || !document["schematic"].is_object() )
2383 document["schematic"] = nlohmann::json::object();
2384
2385 nlohmann::json& schematicSettings = document["schematic"];
2386 bool needsProject = !job->m_outputDir.IsEmpty()
2387 || schematicSettings.value( "bus_aliases", nlohmann::json::object() ) != aliases;
2388
2389 if( needsProject )
2390 {
2391 schematicSettings["bus_aliases"] = std::move( aliases );
2392 nlohmann::json roots = nlohmann::json::array();
2393
2394 for( const TOP_LEVEL_SHEET_INFO& root : projectFile.GetTopLevelSheets() )
2395 {
2396 wxFileName filename( root.filename );
2397 filename.MakeAbsolute( projectPtr->GetProjectPath() );
2398 filename.MakeRelativeTo( base.GetPath() );
2399 roots.push_back( { { "uuid", root.uuid.AsString().ToStdString( wxConvUTF8 ) },
2400 { "name", root.name.ToStdString( wxConvUTF8 ) },
2401 { "filename", filename.GetFullPath().ToStdString( wxConvUTF8 ) } } );
2402 }
2403
2404 schematicSettings["top_level_sheets"] = roots;
2405
2406 if( !document.contains( "meta" ) )
2407 document["meta"] = { { "version", 3 } };
2408
2409 wxFileName destination = projectFn;
2410
2411 if( !job->m_outputDir.IsEmpty() )
2412 destination.SetPath( job->m_outputDir );
2413
2414 wxString finalPath = destination.GetFullPath();
2415 if( !job->m_inPlace && !ValidateFreshDowngradeOutput( finalPath, outputError ) )
2416 THROW_IO_ERROR( outputError );
2417
2418 currentTemp = transaction.Stage( finalPath );
2419
2420 if( currentTemp.IsEmpty() )
2421 THROW_IO_ERROR( _( "Could not stage the schematic project settings." ) );
2422
2423 wxFFile outputProject( currentTemp, wxT( "wb" ) );
2424
2425 if( !outputProject.IsOpened()
2426 || !outputProject.Write( wxString::FromUTF8( ( document.dump( 2 ) + "\n" ).c_str() ) )
2427 || !outputProject.Close() )
2428 {
2429 THROW_IO_ERROR( _( "Could not save the schematic project settings." ) );
2430 }
2431
2432 currentTemp.Clear();
2433 }
2434 }
2435 }
2436 catch( const IO_ERROR& ioe )
2437 {
2438 m_reporter->Report(
2439 wxString::Format( _( "Error saving schematic file '%s'.\n%s" ), job->m_filename, ioe.What().GetData() ),
2442 }
2443
2444 if( int libResult = downgradeLibraries( &transaction ); libResult != CLI::EXIT_CODES::SUCCESS )
2445 return libResult;
2446
2447 wxString failedDestination = transaction.Commit();
2448
2449 if( !failedDestination.IsEmpty() )
2450 {
2451 m_reporter->Report( wxString::Format( _( "Could not replace '%s'.\n" ), failedDestination ),
2453
2454 if( !transaction.GetRecoveryError().IsEmpty() )
2455 m_reporter->Report( transaction.GetRecoveryError(), RPT_SEVERITY_ERROR );
2456
2458 }
2459
2460 outputDirectories.Commit();
2461 m_reporter->Report( _( "Saved downgraded schematic\n" ), RPT_SEVERITY_INFO );
2462
2464}
2465
2466
2468{
2469 JOB_SCH_IMPORT* job = dynamic_cast<JOB_SCH_IMPORT*>( aJob );
2470
2471 if( !job )
2473
2474 job->m_netNameMap.clear();
2475
2476 if( !wxFile::Exists( job->m_inputFile ) )
2477 {
2478 m_reporter->Report( wxString::Format( _( "Input file not found: '%s'\n" ), job->m_inputFile ),
2481 }
2482
2483 // AUTO restricts autodetect to non-KiCad plugins so a native file is not re-imported.
2484 SCH_IO_MGR::SCH_FILE_T fileType = SCH_IO_MGR::SCH_FILE_UNKNOWN;
2485
2486 switch( job->m_format )
2487 {
2490 break;
2491 case JOB_SCH_IMPORT::FORMAT::ALTIUM: fileType = SCH_IO_MGR::SCH_ALTIUM; break;
2492 case JOB_SCH_IMPORT::FORMAT::EAGLE: fileType = SCH_IO_MGR::SCH_EAGLE; break;
2493 case JOB_SCH_IMPORT::FORMAT::CADSTAR: fileType = SCH_IO_MGR::SCH_CADSTAR_ARCHIVE; break;
2494 case JOB_SCH_IMPORT::FORMAT::EASYEDA: fileType = SCH_IO_MGR::SCH_EASYEDA; break;
2495 case JOB_SCH_IMPORT::FORMAT::EASYEDAPRO: fileType = SCH_IO_MGR::SCH_EASYEDAPRO; break;
2496 case JOB_SCH_IMPORT::FORMAT::LTSPICE: fileType = SCH_IO_MGR::SCH_LTSPICE; break;
2497 case JOB_SCH_IMPORT::FORMAT::PADS: fileType = SCH_IO_MGR::SCH_PADS; break;
2498 case JOB_SCH_IMPORT::FORMAT::DIPTRACE: fileType = SCH_IO_MGR::SCH_DIPTRACE; break;
2499 case JOB_SCH_IMPORT::FORMAT::PCAD: fileType = SCH_IO_MGR::SCH_PCAD; break;
2500 case JOB_SCH_IMPORT::FORMAT::ORCAD: fileType = SCH_IO_MGR::SCH_ORCAD; break;
2501 case JOB_SCH_IMPORT::FORMAT::EASYPC: fileType = SCH_IO_MGR::SCH_EASYPC; break;
2502 case JOB_SCH_IMPORT::FORMAT::TARGET3001: fileType = SCH_IO_MGR::SCH_TARGET3001; break;
2503 }
2504
2505 if( fileType == SCH_IO_MGR::SCH_FILE_UNKNOWN )
2506 {
2507 // Quiet sentinel: lets the top-level `import` command treat the file as not-a-schematic.
2508 m_reporter->Report( wxString::Format( _( "No schematic importer recognizes the file format "
2509 "of '%s'\n" ),
2510 job->m_inputFile ),
2513 }
2514
2515 wxString outputPath = job->GetConfiguredOutputPath();
2516
2517 if( outputPath.IsEmpty() )
2519
2520 wxFileName inputFn( job->m_inputFile );
2521 inputFn.MakeAbsolute();
2522
2523 wxFileName outputFn( outputPath );
2524 outputFn.MakeAbsolute();
2525
2526 // Foreign importers resolve their symbol library against the *active* project, so an import
2527 // with no project loaded needs a transient active one at the output location (never written to
2528 // disk; LoadProject returns false yet still registers it, hence the GetProject() check).
2530 PROJECT* projectPtr = nullptr;
2531 bool createdTransientProject = false;
2532
2533 if( mgr.IsProjectOpenNotDummy() )
2534 {
2535 projectPtr = &mgr.Prj();
2536 }
2537 else
2538 {
2539 wxFileName projectFn( outputFn );
2540 projectFn.SetExt( FILEEXT::ProjectFileExtension );
2541
2542 mgr.LoadProject( projectFn.GetFullPath(), true );
2543 projectPtr = mgr.GetProject( projectFn.GetFullPath() );
2544 createdTransientProject = ( projectPtr != nullptr );
2545 }
2546
2547 if( !projectPtr )
2548 {
2549 m_reporter->Report( _( "Could not establish a project for the import\n" ),
2552 }
2553
2554 PROJECT& project = *projectPtr;
2555
2556 // Declared before the SCHEMATIC so reverse-destruction tears the schematic (which references
2557 // the project) down first; unloads the transient project on every exit path.
2558 TRANSIENT_PROJECT_GUARD transientProjectGuard{ mgr, projectPtr, createdTransientProject };
2559
2561
2562 std::unique_ptr<SCHEMATIC> schematic = std::make_unique<SCHEMATIC>( &project );
2563
2564 wxString formatName = SCH_IO_MGR::ShowType( fileType );
2565 SCH_SHEET* loadedSheet = nullptr;
2566
2567 // Declared before the plugin so it outlives the plugin's pointer to it
2568 IMPORT_MESSAGE_COLLECTOR importMessages( *m_reporter );
2569
2570 // outlives the load so the retained symbol definitions can be reconciled below
2571 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( fileType ) );
2572
2573 if( !pi )
2574 {
2575 m_reporter->Report( wxString::Format( _( "No plugin found for file type '%s'\n" ),
2576 formatName ),
2579 }
2580
2581 // Without this the importer's warnings go to the wx log and never reach the import report
2582 pi->SetReporter( &importMessages );
2583
2584 try
2585 {
2586 m_reporter->Report( wxString::Format( _( "Importing '%s' using %s format...\n" ),
2587 inputFn.GetFullPath(), formatName ),
2589
2590 loadedSheet = pi->LoadSchematicFile( inputFn.GetFullPath(), schematic.get() );
2591
2592 if( !loadedSheet )
2593 {
2594 m_reporter->Report( _( "Failed to load schematic\n" ), RPT_SEVERITY_ERROR );
2596 }
2597 }
2598 catch( const IO_ERROR& ioe )
2599 {
2600 m_reporter->Report( wxString::Format( _( "Error during import: %s\n" ), ioe.What() ),
2603 }
2604
2605 size_t symbolCount = 0;
2606 size_t sheetCount = 0;
2607
2608 try
2609 {
2610 // Some importers build the top-level sheet set themselves; only collapse to the returned
2611 // sheet otherwise (mirrors SCH_EDIT_FRAME::importFile()).
2612 std::vector<SCH_SHEET*> topLevelSheets = schematic->GetTopLevelSheets();
2613 bool loadedIsTopLevel = std::find( topLevelSheets.begin(), topLevelSheets.end(),
2614 loadedSheet ) != topLevelSheets.end();
2615 bool loadedIsVirtualRoot = loadedSheet == &schematic->Root()
2616 || loadedSheet->IsVirtualRootSheet();
2617
2618 if( !loadedIsTopLevel && !loadedIsVirtualRoot )
2619 schematic->SetTopLevelSheets( { loadedSheet } );
2620
2621 // Extract a project symbol library and re-link LIB_IDs, as importFile() does; without it
2622 // the saved schematic references nicknames no library table row resolves.
2623 ReconcileImportedSymbols( *pi, *schematic, project, inputFn.GetFullPath(), nullptr,
2624 *m_reporter );
2625
2626 // Recompute connectivity so instance data is valid before saving, as importFile() does.
2627 std::unique_ptr<TOOL_MANAGER> toolManager = std::make_unique<TOOL_MANAGER>();
2628 toolManager->SetEnvironment( schematic.get(), nullptr, nullptr, Kiface().KifaceSettings(),
2629 nullptr );
2630
2631 {
2632 SCH_COMMIT dummyCommit( toolManager.get() );
2633 schematic->RecalculateConnections( &dummyCommit, GLOBAL_CLEANUP, toolManager.get() );
2634 dummyCommit.Push( _( "Schematic Cleanup" ), SKIP_UNDO | SKIP_CONNECTIVITY | DELETE_REMOVED_ITEMS );
2635 }
2636
2637 schematic->SetSheetNumberAndCount();
2638
2639 // Imported schematics preserve their source page frame as schematic graphics.
2640 // Match the editor import path and suppress KiCad's default frame/title block.
2641 schematic->Settings().m_SchDrawingSheetFileName = wxS( "empty.kicad_wks" );
2643
2644 if( SCH_SHEET* topSheet = schematic->GetTopLevelSheet() )
2645 topSheet->SetFileName( outputFn.GetFullName() );
2646
2647 schematic->RootScreen()->SetFileName( outputFn.GetFullPath() );
2648
2649 SCH_SCREENS screens( schematic->Root() );
2650
2651 std::unordered_map<SCH_SCREEN*, wxString> filenameMap;
2652 filenameMap[schematic->RootScreen()] = outputFn.GetFullPath();
2653
2654 wxString errorMsg;
2655
2656 if( !PrepareSaveAsFiles( *schematic, screens, inputFn, outputFn, /*aSaveCopy*/ true,
2657 /*aCopySubsheets*/ true, /*aIncludeExternSheets*/ true,
2658 filenameMap, errorMsg ) )
2659 {
2660 m_reporter->Report( errorMsg + wxS( "\n" ), RPT_SEVERITY_ERROR );
2662 }
2663
2664 // PrepareSaveAsFiles seeds an entry (empty for sheets it does not relocate) for every
2665 // screen; empty paths are skipped.
2666 IO_RELEASER<SCH_IO> kicadPi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
2667
2668 for( size_t i = 0; i < screens.GetCount(); i++ )
2669 {
2670 SCH_SCREEN* screen = screens.GetScreen( i );
2671 wxString path = filenameMap[screen];
2672
2673 if( path.IsEmpty() )
2674 continue;
2675
2676 wxFileName fn( path );
2678
2679 kicadPi->SaveSchematicFile( fn.GetFullPath(), screens.GetSheet( i ), schematic.get() );
2680 sheetCount++;
2681
2682 auto symbols = screen->Items().OfType( SCH_SYMBOL_T );
2683 symbolCount += std::distance( symbols.begin(), symbols.end() );
2684 }
2685 }
2686 catch( const IO_ERROR& ioe )
2687 {
2688 m_reporter->Report( wxString::Format( _( "Error saving imported schematic: %s\n" ),
2689 ioe.What() ),
2692 }
2693 catch( const std::exception& exc )
2694 {
2695 m_reporter->Report( wxString::Format( _( "Error saving imported schematic: %s\n" ),
2696 exc.what() ),
2699 }
2700
2701 // The board job renames its nets from this; nothing is written beside the schematic.
2702 if( const IMPORT_NET_MAP* map = schematic->GetImportNetMap() )
2704
2705 m_reporter->Report( wxString::Format( _( "Successfully saved imported schematic to '%s'\n" ),
2706 outputFn.GetFullPath() ),
2708
2709 // Linked by the top-level `import` command's subsequent SaveProject().
2710 if( Pgm().GetSettingsManager().IsProjectOpenNotDummy() )
2711 {
2712 std::vector<FILE_INFO_PAIR>& projectSheets = project.GetProjectFile().GetSheets();
2713 projectSheets.clear();
2714
2715 for( const SCH_SHEET_PATH& sheetPath : schematic->Hierarchy() )
2716 {
2717 SCH_SHEET* sheet = sheetPath.Last();
2718
2719 if( sheet && !sheet->IsVirtualRootSheet() )
2720 projectSheets.emplace_back( std::make_pair( sheet->m_Uuid, sheet->GetName() ) );
2721 }
2722
2723 // Reload uses the top-level sheet list, not the UUID-to-name map.
2724 std::vector<TOP_LEVEL_SHEET_INFO> topLevelSheets = schematic->TopLevelSheetInfos();
2725
2726 if( !topLevelSheets.empty() )
2727 project.GetProjectFile().GetTopLevelSheets() = std::move( topLevelSheets );
2728 }
2729
2730 // Extra top-level sheets need a project file to remain reachable.
2731 if( createdTransientProject && schematic->GetTopLevelSheets().size() > 1 )
2732 {
2733 m_reporter->Report( wxString::Format( _( "%zu sheets were written, but only '%s' is "
2734 "reachable: top-level sheets are recorded in a "
2735 "project file. Use 'kicad-cli import' to create "
2736 "one.\n" ),
2737 sheetCount, outputFn.GetFullName() ),
2739 }
2740
2741 IMPORT_REPORT_DATA reportData;
2742 importMessages.Flush( job->m_reportFormat, reportData );
2743
2745 {
2746 reportData.m_sourceFile = inputFn.GetFullName();
2747 reportData.m_sourceFormat = formatName;
2748 reportData.m_outputFile = outputFn.GetFullName();
2749 reportData.m_statistics = {
2750 { wxS( "symbols" ), symbolCount },
2751 { wxS( "sheets" ), sheetCount }
2752 };
2753
2754 reportData.m_statistics.emplace_back( wxS( "renamed_board_nets" ), job->m_netNameMap.size() );
2755
2756 if( !WriteImportReport( m_reporter, job->m_reportFormat, job->m_reportFile, reportData ) )
2758 }
2759
2761}
2762
2763
2765{
2766 DS_PROXY_VIEW_ITEM* drawingSheet =
2768 &aSch->RootScreen()->GetTitleBlock(), aSch->GetProperties() );
2769
2770 drawingSheet->SetPageNumber( TO_UTF8( aSch->RootScreen()->GetPageNumber() ) );
2771 drawingSheet->SetSheetCount( aSch->RootScreen()->GetPageCount() );
2772 drawingSheet->SetFileName( TO_UTF8( aSch->RootScreen()->GetFileName() ) );
2775 drawingSheet->SetIsFirstPage( aSch->RootScreen()->GetVirtualPageNumber() == 1 );
2776
2777 wxString currentVariant = aSch->GetCurrentVariant();
2778 wxString variantDesc = aSch->GetVariantDescription( currentVariant );
2779 drawingSheet->SetVariantName( TO_UTF8( currentVariant ) );
2780 drawingSheet->SetVariantDesc( TO_UTF8( variantDesc ) );
2781
2782 drawingSheet->SetSheetName( "" );
2783 drawingSheet->SetSheetPath( "" );
2784
2785 return drawingSheet;
2786}
2787
2788
2789// ============================================================================
2790// JobSchDiff: sch_diff implementation
2791// ============================================================================
2794#include <diff_merge/diff_scene.h>
2795#include <diff_merge/sch_differ.h>
2799#include <project/project_file.h>
2801#include <jobs/job_sch_diff.h>
2802#include <jobs/scratch_doc.h>
2803#include <wx/file.h>
2804
2805
2806// Load a schematic into a SCRATCH_DOC<SCHEMATIC> that keeps a dedicated scratch
2807// PROJECT attached for the document's lifetime. Without a per-document project,
2808// a second LoadProject(path, true) destroys the first project and the first
2809// schematic's m_project dangles. The destructor severs the link via
2810// SetProject( nullptr ). Shared by every SCH diff/merge job.
2812{
2814 aMgr, aPath,
2815 [aPath]( PROJECT* aProject )
2816 {
2817 return std::unique_ptr<SCHEMATIC>(
2819 /*aSetActive=*/false,
2820 /*aForceDefaultProject=*/false, aProject,
2821 /*aCalculateConnectivity=*/false ) );
2822 },
2823 []( SCHEMATIC* aSch )
2824 {
2825 aSch->SetProject( nullptr );
2826 } );
2827}
2828
2829
2830// A bare PROJECT has no PROJECT_FILE and SCHEMATIC::SetProject dereferences GetProjectFile(),
2831// so the missing side of a diff needs a real scratch project just like the loaded side.
2833{
2834 // A fixed name in the shared temp directory could be loaded as the scratch project, and
2835 // would collide between two KiCad instances diffing at once.
2836 wxFileName synthetic( wxFileName::GetTempDir(),
2837 wxString::Format( wxS( "%s_%ld_%p" ), aTag, static_cast<long>( wxGetProcessId() ), &aMgr ) );
2838
2840 aMgr, synthetic.GetFullPath(),
2841 []( PROJECT* aProject )
2842 {
2843 auto sch = std::make_unique<SCHEMATIC>( aProject );
2844 sch->CreateDefaultScreens();
2845 return sch;
2846 },
2847 []( SCHEMATIC* aSch )
2848 {
2849 aSch->SetProject( nullptr );
2850 } );
2851}
2852
2853
2855{
2856 JOB_SCH_DIFF* diffJob = dynamic_cast<JOB_SCH_DIFF*>( aJob );
2857
2858 if( !diffJob )
2860
2861 // Two schematics in the same SettingsManager need scratch PROJECTs;
2862 // otherwise the second LoadProject(path, true) destroys the first
2863 // project and the first schematic's m_project dangles, crashing on
2864 // any per-instance bbox / field / reference resolution (e.g. inside
2865 // SCH_DIFFER's makeDescriptor calling SCH_SYMBOL::GetRef).
2867
2870
2871 if( !a.doc )
2872 {
2873 m_reporter->Report( wxString::Format( _( "Failed to load %s\n" ), diffJob->m_inputA ), RPT_SEVERITY_ERROR );
2875 }
2876
2877 if( !b.doc )
2878 {
2879 m_reporter->Report( wxString::Format( _( "Failed to load %s\n" ), diffJob->m_inputB ), RPT_SEVERITY_ERROR );
2881 }
2882
2883 SCHEMATIC* schA = a.doc.get();
2884 SCHEMATIC* schB = b.doc.get();
2885
2886 KICAD_DIFF::SCH_DIFFER differ( schA, schB, diffJob->m_inputB );
2888
2889 int diffExitCode = KICAD_DIFF::DiffExitCode( result );
2890
2891 if( diffJob->m_exitCodeOnly )
2892 return diffExitCode;
2893
2894 // The schematic geometry (wires, junctions, symbol/sheet/label bbox
2895 // outlines) renders beneath the change rectangles for PNG/SVG, matching
2896 // the interactive dialog.
2898 KICAD_DIFF::MakeEmitOptions( *diffJob, diffJob->m_inputA, diffJob->m_inputB );
2900 emitOpts.referenceGeometry = [&]( const KIGFX::COLOR4D& aColor )
2901 { return KICAD_DIFF::ExtractSchematicGeometry( *schA, aColor ); };
2902 emitOpts.comparisonGeometry = [&]( const KIGFX::COLOR4D& aColor )
2903 { return KICAD_DIFF::ExtractSchematicGeometry( *schB, aColor ); };
2904
2905 return KICAD_DIFF::EmitDiffResult( result, emitOpts, diffExitCode, *m_reporter );
2906}
2907
2908
2909// ============================================================================
2910// JobSymDiff: sym_diff implementation
2911// ============================================================================
2914#include <jobs/job_sym_diff.h>
2915
2916
2917// Load one side of a symbol-library diff into its owner vector and name map.
2918// When aAllowEmpty is set an empty path resolves to a clean (empty) side; the
2919// non-interactive job path leaves it unset so a missing path is an input error.
2920static int loadSymbolLibrarySide( const wxString& aPath,
2921 std::vector<std::unique_ptr<LIB_SYMBOL>>& aOwners,
2922 KICAD_DIFF::SYM_LIB_DIFFER::SYMBOL_MAP& aMap, bool aAllowEmpty,
2923 REPORTER& aReporter )
2924{
2925 if( aAllowEmpty && aPath.IsEmpty() )
2927
2928 try
2929 {
2930 auto loaded = KICAD_DIFF::SYM_LIB_DIFFER::LoadLibrary( aPath );
2931 aOwners = std::move( loaded.first );
2932 aMap = std::move( loaded.second );
2934 }
2935 catch( const IO_ERROR& ioe )
2936 {
2937 aReporter.Report( wxString::Format( _( "Failed to load %s: %s\n" ), aPath, ioe.What() ),
2939 }
2940 catch( const std::exception& e )
2941 {
2942 aReporter.Report(
2943 wxString::Format( _( "Failed to load %s: %s\n" ), aPath, wxString::FromUTF8( e.what() ) ),
2945 }
2946
2948}
2949
2950
2951// Flatten a symbol-library name map into a single DOCUMENT_GEOMETRY tinted with
2952// the supplied per-side theme colour.
2955{
2957
2958 for( const auto& [name, symbol] : aMap )
2959 {
2960 if( symbol )
2961 KICAD_DIFF::AppendGeometry( geometry, KICAD_DIFF::ExtractSymbolGeometry( *symbol, aColor ) );
2962 }
2963
2964 return geometry;
2965}
2966
2967
2969{
2970 JOB_SYM_DIFF* diffJob = dynamic_cast<JOB_SYM_DIFF*>( aJob );
2971
2972 if( !diffJob )
2974
2975 std::vector<std::unique_ptr<LIB_SYMBOL>> ownersA;
2976 std::vector<std::unique_ptr<LIB_SYMBOL>> ownersB;
2979
2980 if( int rc = loadSymbolLibrarySide( diffJob->m_inputA, ownersA, mapA, false, *m_reporter );
2982 {
2983 return rc;
2984 }
2985
2986 if( int rc = loadSymbolLibrarySide( diffJob->m_inputB, ownersB, mapB, false, *m_reporter );
2988 {
2989 return rc;
2990 }
2991
2992 KICAD_DIFF::SYM_LIB_DIFFER differ( mapA, mapB, diffJob->m_inputB );
2994
2995 int diffExitCode = KICAD_DIFF::DiffExitCode( result );
2996
2997 if( diffJob->m_exitCodeOnly )
2998 return diffExitCode;
2999
3001 KICAD_DIFF::MakeEmitOptions( *diffJob, diffJob->m_inputA, diffJob->m_inputB );
3003 emitOpts.referenceGeometry = [&]( const KIGFX::COLOR4D& aColor )
3004 { return symbolLibraryGeometry( mapA, aColor ); };
3005 emitOpts.comparisonGeometry = [&]( const KIGFX::COLOR4D& aColor )
3006 { return symbolLibraryGeometry( mapB, aColor ); };
3007
3008 return KICAD_DIFF::EmitDiffResult( result, emitOpts, diffExitCode, *m_reporter );
3009}
3010
3011
3012// ============================================================================
3013// JobOpenDiffDialog: load two on-disk files and open DIALOG_KICAD_DIFF.
3014// Dispatched from the project manager / PR-review dialog via KIWAY.
3015// ============================================================================
3021#include <jobs/scratch_doc.h>
3022
3023
3024// Both schematics of a diff, kept while the caller draws them.
3035
3036
3037static int loadSchDiffSides( SETTINGS_MANAGER& aMgr, REPORTER& aReporter, const wxString& aFileA,
3038 const wxString& aFileB, SCH_DIFF_SIDES& aSides )
3039{
3040 aSides.a = loadScratchSchematic( aMgr, aFileA );
3041 aSides.b = loadScratchSchematic( aMgr, aFileB );
3042
3043 if( !aSides.a.doc && !aFileA.IsEmpty() )
3044 {
3045 aReporter.Report( wxString::Format( _( "Failed to load %s\n" ), aFileA ), RPT_SEVERITY_ERROR );
3047 }
3048
3049 if( !aSides.b.doc && !aFileB.IsEmpty() )
3050 {
3051 aReporter.Report( wxString::Format( _( "Failed to load %s\n" ), aFileB ), RPT_SEVERITY_ERROR );
3053 }
3054
3055 // Synthesize empty SCHEMATICs for any missing side so SCH_DIFFER sees a valid empty
3056 // document. Each empty side needs its own defaults-only project: a bare PROJECT has no
3057 // PROJECT_FILE, and SCHEMATIC::SetProject dereferences GetProjectFile().
3058 if( !aSides.a.doc )
3059 aSides.emptyA = emptyScratchSchematic( aMgr, wxT( "kicad_diff_empty_a" ) );
3060
3061 if( !aSides.b.doc )
3062 aSides.emptyB = emptyScratchSchematic( aMgr, wxT( "kicad_diff_empty_b" ) );
3063
3064 aSides.schA = aSides.a.doc ? aSides.a.doc.get() : aSides.emptyA.doc.get();
3065 aSides.schB = aSides.b.doc ? aSides.b.doc.get() : aSides.emptyB.doc.get();
3066
3067 KICAD_DIFF::SCH_DIFFER differ( aSides.schA, aSides.schB, aFileB );
3068 aSides.diff = differ.Diff();
3069
3071}
3072
3073
3074// The two schematics a window outside the kiface shows, taken off their canvases before they go.
3076{
3077public:
3079 m_before( aBefore ),
3080 m_after( aAfter )
3081 {
3082 }
3083
3085 {
3086 // The painter keeps a schematic pointer, so give the canvases one that points at nothing.
3087 const KICAD_DIFF::DIFF_COLOR_THEME theme;
3088
3089 for( WIDGET_DIFF_CANVAS* canvas : { m_before, m_after } )
3090 {
3091 canvas->SetContextItems( {} );
3092 canvas->SetContextPainter(
3093 KICAD_DIFF::MakeSchDiffContextPainter( canvas->GetGAL(), nullptr, theme.reference ) );
3094 }
3095 }
3096
3098
3099private:
3102};
3103
3104
3106EESCHEMA_JOBS_HANDLER::AttachDiffCanvases( KICAD_DIFF::DOC_KIND aKind, const wxString& aFileA, const wxString& aFileB,
3107 WIDGET_DIFF_CANVAS* aBefore, WIDGET_DIFF_CANVAS* aAfter,
3108 KICAD_DIFF::DOCUMENT_DIFF& aDiff, REPORTER* aReporter )
3109{
3110 SCOPED_SET_RESET<REPORTER*> reporterGuard( m_reporter, aReporter ? aReporter : m_reporter );
3111
3112 if( aKind != KICAD_DIFF::DOC_KIND::SCH )
3113 return nullptr;
3114
3115 auto context = std::make_unique<SCH_DIFF_CANVAS_CONTEXT>( aBefore, aAfter );
3116
3117 if( loadSchDiffSides( Pgm().GetSettingsManager(), *m_reporter, aFileA, aFileB, context->m_sides )
3119 {
3120 return nullptr;
3121 }
3122
3123 const KICAD_DIFF::DIFF_COLOR_THEME theme;
3124 SCHEMATIC* schA = context->m_sides.schA;
3125 SCHEMATIC* schB = context->m_sides.schB;
3126
3127 KICAD_DIFF::ConfigureSchDiffCanvasContext( *aBefore, schA, nullptr, theme.reference, {}, {}, {}, schA->RootScreen(),
3128 nullptr );
3129 KICAD_DIFF::ConfigureSchDiffCanvasContext( *aAfter, nullptr, schB, theme.reference, {}, {}, {}, nullptr,
3130 schB->RootScreen() );
3131
3132 aDiff = context->m_sides.diff;
3133 return context.release();
3134}
3135
3136
3138 const wxString& aFileB, const wxString& aLabelA,
3139 const wxString& aLabelB, wxWindow* aParent,
3140 REPORTER* aReporter )
3141{
3142 // Restore m_reporter on scope exit so a caller's transient (often
3143 // stack-local) reporter doesn't outlive this call as a dangling member.
3145 aReporter ? aReporter : m_reporter );
3146
3147 wxWindow* parent = aParent ? aParent : ( wxTheApp ? wxTheApp->GetTopWindow() : nullptr );
3148 const wxString labelA = aLabelA.IsEmpty() ? aFileA : aLabelA;
3149 const wxString labelB = aLabelB.IsEmpty() ? aFileB : aLabelB;
3150
3151 switch( aKind )
3152 {
3154 {
3155 SCH_DIFF_SIDES sides;
3156
3157 if( int rc = loadSchDiffSides( Pgm().GetSettingsManager(), *m_reporter, aFileA, aFileB, sides );
3159 {
3160 return rc;
3161 }
3162
3163 SCHEMATIC* schA = sides.schA;
3164 SCHEMATIC* schB = sides.schB;
3165 const KICAD_DIFF::DOCUMENT_DIFF& result = sides.diff;
3166 const KICAD_DIFF::DIFF_COLOR_THEME theme;
3167
3168 // A deleted item exists only in the reference schematic, so the comparison-side context cannot
3169 // draw it. Keyed by sheet path, or removing one instance of a shared sheet ghosts the others.
3170 std::map<KIID_PATH, std::set<KIID>> removedBySheet;
3171
3172 for( const KICAD_DIFF::ITEM_CHANGE& change : result.changes )
3173 {
3174 if( change.kind == KICAD_DIFF::CHANGE_KIND::REMOVED && !change.id.empty() )
3175 {
3176 KIID_PATH sheetPath = change.id;
3177 sheetPath.pop_back();
3178 removedBySheet[sheetPath].insert( change.id.back() );
3179 }
3180 }
3181
3182 DIALOG_KICAD_DIFF dlg( parent, labelA, labelB, result,
3185 [schA, schB, removedBySheet, color = theme.reference]( WIDGET_DIFF_CANVAS& aCanvas,
3186 const KIID_PATH& aSheetPath )
3187 {
3188 SCH_SCREEN* compScreen = schB ? schB->RootScreen() : nullptr;
3189
3190 if( !aSheetPath.empty() && schB )
3191 {
3192 if( auto sp = schB->Hierarchy().GetSheetPathByKIIDPath( aSheetPath, true ) )
3193 compScreen = sp->LastScreen();
3194 }
3195
3196 SCH_SCREEN* refScreen = schA ? schA->RootScreen() : nullptr;
3197
3198 if( !aSheetPath.empty() && schA )
3199 {
3200 if( auto sp = schA->Hierarchy().GetSheetPathByKIIDPath( aSheetPath, true ) )
3201 refScreen = sp->LastScreen();
3202 }
3203
3204 std::vector<KIGFX::VIEW_ITEM*> deletedItems;
3205 auto removedHere = removedBySheet.find( aSheetPath );
3206
3207 // The initial display passes an empty path for the root
3208 // sheet, which the change ids name by uuid.
3209 if( removedHere == removedBySheet.end() && aSheetPath.empty() && schA )
3210 {
3211 KIID_PATH rootPath;
3212 rootPath.push_back( schA->Root().m_Uuid );
3213 removedHere = removedBySheet.find( rootPath );
3214 }
3215
3216 if( refScreen && removedHere != removedBySheet.end() )
3217 {
3218 for( SCH_ITEM* item : refScreen->Items() )
3219 {
3220 if( removedHere->second.count( item->m_Uuid ) )
3221 deletedItems.push_back( item );
3222 }
3223 }
3224
3225 // Drawing the reference too would overlay the old and new
3226 // versions of a moved item, so only its deleted items are used.
3227 KICAD_DIFF::ConfigureSchDiffCanvasContext( aCanvas, nullptr, schB, color, {},
3228 deletedItems, {}, nullptr, compScreen );
3229 } );
3230 dlg.ShowModal();
3231
3233 }
3235 {
3236 std::vector<std::unique_ptr<LIB_SYMBOL>> ownersA;
3237 std::vector<std::unique_ptr<LIB_SYMBOL>> ownersB;
3240
3241 if( int rc = loadSymbolLibrarySide( aFileA, ownersA, mapA, true, *m_reporter );
3243 {
3244 return rc;
3245 }
3246
3247 if( int rc = loadSymbolLibrarySide( aFileB, ownersB, mapB, true, *m_reporter );
3249 {
3250 return rc;
3251 }
3252
3253 KICAD_DIFF::SYM_LIB_DIFFER differ( mapA, mapB, aFileB );
3254 KICAD_DIFF::DOCUMENT_DIFF result = differ.Diff();
3255
3256 // The selected symbol is drawn whole, since outlines of every symbol pile up in one place
3257 DIALOG_KICAD_DIFF dlg( parent, labelA, labelB, result );
3258 dlg.DrawChosenLibraryItem(
3259 [&]( WIDGET_DIFF_CANVAS& aCanvas, const wxString& aName )
3260 {
3261 KICAD_DIFF::ShowSymbolPair( aCanvas, mapA, mapB, aName );
3262 } );
3263 dlg.ShowModal();
3264
3266 }
3267 default:
3268 m_reporter->Report( _( "Unsupported document kind for this dispatcher.\n" ), RPT_SEVERITY_ERROR );
3270 }
3271}
3272
3273
3274// ============================================================================
3275// JobSchMerge: sch_merge implementation
3276// ============================================================================
3280#include <jobs/scratch_doc.h>
3281
3282
3283int EESCHEMA_JOBS_HANDLER::RunMerge( KICAD_DIFF::DOC_KIND aKind, const wxString& aAncestor,
3284 const wxString& aOurs, const wxString& aTheirs,
3285 const wxString& aOutput, bool aInteractive, bool aSingleFile,
3286 REPORTER* aReporter )
3287{
3288 // Restore m_reporter on scope exit so a caller's transient (often
3289 // stack-local) reporter doesn't outlive this call as a dangling member.
3291 aReporter ? aReporter : m_reporter );
3292
3293 if( aKind == KICAD_DIFF::DOC_KIND::SYM_LIB )
3294 return runSymLibMerge( aAncestor, aOurs, aTheirs, aOutput, aInteractive );
3295
3296 return runSchMerge( aAncestor, aOurs, aTheirs, aOutput, aInteractive );
3297}
3298
3299
3300int EESCHEMA_JOBS_HANDLER::runSchMerge( const wxString& aAncestor, const wxString& aOurs,
3301 const wxString& aTheirs, const wxString& aOutput,
3302 bool aInteractive )
3303{
3305
3306 SCRATCH_DOC<SCHEMATIC> ancestor = loadScratchSchematic( mgr, aAncestor );
3307 SCRATCH_DOC<SCHEMATIC> ours = loadScratchSchematic( mgr, aOurs );
3308 SCRATCH_DOC<SCHEMATIC> theirs = loadScratchSchematic( mgr, aTheirs );
3309
3310 if( !ancestor.doc || !ours.doc || !theirs.doc )
3311 {
3312 m_reporter->Report( _( "Failed to load one or more input schematics\n" ), RPT_SEVERITY_ERROR );
3314 }
3315
3316 // Multi-sheet hierarchies are supported: each non-root sub-sheet is
3317 // written alongside the output root using its original basename. Top-level
3318 // sheets stay singular — multiple roots is an editor invariant the diff
3319 // engine never models, so refuse those.
3320 auto hasSingleRoot = []( const SCHEMATIC* aSch )
3321 {
3322 return aSch->GetTopLevelSheets().size() == 1;
3323 };
3324
3325 if( !hasSingleRoot( ancestor.doc.get() ) || !hasSingleRoot( ours.doc.get() ) || !hasSingleRoot( theirs.doc.get() ) )
3326 {
3327 m_reporter->Report( _( "sch merge requires each input to have a single top-level sheet\n" ),
3330 }
3331
3332 auto loadedVersion = []( const SCHEMATIC* aSch )
3333 {
3334 return aSch->RootScreen() ? aSch->RootScreen()->GetFileFormatVersionAtLoad() : 0;
3335 };
3336
3337 const wxString formatNotice =
3338 KICAD_DIFF::OlderFormatNotice( loadedVersion( ancestor.doc.get() ), loadedVersion( ours.doc.get() ),
3339 loadedVersion( theirs.doc.get() ), SEXPR_SCHEMATIC_FILE_VERSION );
3340
3341 if( !formatNotice.IsEmpty() )
3342 m_reporter->Report( formatNotice + wxS( "\n" ), RPT_SEVERITY_WARNING );
3343
3344 KICAD_DIFF::SCH_DIFFER ourDiff( ancestor.doc.get(), ours.doc.get() );
3345 KICAD_DIFF::SCH_DIFFER theirDiff( ancestor.doc.get(), theirs.doc.get() );
3346
3347 KICAD_DIFF::DOCUMENT_DIFF ourDocDiff = ourDiff.Diff();
3348 KICAD_DIFF::DOCUMENT_DIFF theirDocDiff = theirDiff.Diff();
3349
3351 KICAD_DIFF::MERGE_PLAN plan = engine.Plan( ourDocDiff, theirDocDiff );
3352
3353 if( aInteractive && !KICAD_DIFF::BuildConflictList( plan ).empty() )
3354 {
3357
3358 const KICAD_DIFF::DIFF_COLOR_THEME theme;
3360 ctx.formatNotice = formatNotice;
3361
3362 if( ancestor.doc )
3364
3365 if( ours.doc )
3367
3368 if( theirs.doc )
3370
3372 KICAD_DIFF::CollectChangeBBoxes( theirDocDiff, ctx.theirsBBoxes );
3373
3374 ctx.describeItem = [&ours, &theirs, &ancestor]( const KIID_PATH& aId ) -> wxString
3375 {
3376 if( aId.empty() )
3377 return wxEmptyString;
3378
3380
3381 for( SCHEMATIC* doc : { ours.doc.get(), theirs.doc.get(), ancestor.doc.get() } )
3382 {
3383 if( !doc )
3384 continue;
3385
3386 if( SCH_ITEM* item = doc->ResolveItem( aId.back(), nullptr, true ) )
3387 return item->GetItemDescription( &units, false );
3388 }
3389
3390 return wxEmptyString;
3391 };
3392
3393 // A conflict's path is its sheet path followed by the item, so dropping the item
3394 // names the sheet it lives on.
3395 auto screenForConflict = []( SCHEMATIC* aDoc, const std::optional<KIID_PATH>& aId ) -> SCH_SCREEN*
3396 {
3397 if( !aId.has_value() || aId->size() < 2 )
3398 return aDoc->RootScreen();
3399
3400 KIID_PATH sheetPath = *aId;
3401 sheetPath.pop_back();
3402
3404
3405 if( std::optional<SCH_SHEET_PATH> path = sheets.GetSheetPathByKIIDPath( sheetPath ) )
3406 {
3407 if( SCH_SCREEN* screen = path->LastScreen() )
3408 return screen;
3409 }
3410
3411 return aDoc->RootScreen();
3412 };
3413
3414 ctx.drawSide = [&ancestor, &ours, &theirs, theme, screenForConflict]( WIDGET_DIFF_CANVAS& aCanvas,
3416 const std::optional<KIID_PATH>& aId )
3417 {
3418 SCHEMATIC* doc = nullptr;
3419 KIGFX::COLOR4D colour = theme.reference;
3420
3421 switch( aSide )
3422 {
3423 case DIALOG_KICAD_MERGE_3WAY::SIDE::OURS: doc = ours.doc.get(); break;
3424
3426 doc = theirs.doc.get();
3427 colour = theme.comparison;
3428 break;
3429
3430 case DIALOG_KICAD_MERGE_3WAY::SIDE::ANCESTOR: doc = ancestor.doc.get(); break;
3431 }
3432
3433 if( doc )
3434 {
3435 KICAD_DIFF::ConfigureSchDiffCanvasContext( aCanvas, doc, nullptr, colour, {}, {}, {},
3436 screenForConflict( doc, aId ) );
3437 }
3438 };
3439
3440 DIALOG_KICAD_MERGE_3WAY dlg( wxTheApp->GetTopWindow(), plan, std::move( ctx ) );
3441
3442 // Cancelling leaves the conflicts unresolved and the files untouched.
3443 if( dlg.ShowModal() != wxID_APPLY )
3445
3446 plan = dlg.GetResolvedPlan();
3447 }
3448
3449 // Snapshot of the plan before the applier moves it; drives the
3450 // unresolved-conflict report below.
3451 const KICAD_DIFF::MERGE_PLAN planSnapshot = plan;
3452
3453 KICAD_DIFF::SCH_MERGE_APPLIER applier( ancestor.doc.get(), ours.doc.get(), theirs.doc.get(), std::move( plan ) );
3454
3455 if( !applier.Apply() )
3456 {
3457 m_reporter->Report( _( "Merge applier failed to produce a schematic\n" ), RPT_SEVERITY_ERROR );
3459 }
3460
3461 // Sheet add/remove/replace resolutions are explicitly skipped by
3462 // SCH_MERGE_APPLIER (see isSheetItem); succeeding here would silently
3463 // drop hierarchy edits.
3464 if( applier.GetReport().sheetActionsSkipped > 0 )
3465 {
3466 m_reporter->Report( _( "Merge contains hierarchical sheet structure changes that sch merge "
3467 "cannot apply\n" ),
3470 }
3471
3472 // Refusal above guarantees a single top-level sheet.
3473 SCH_SHEET* rootSheet = ancestor.doc->GetTopLevelSheet( 0 );
3474
3475 wxFileName outFn( aOutput );
3476 outFn.MakeAbsolute();
3477
3478 // Sub-sheets land alongside the root by basename. Preserving the original
3479 // relative-path subdirectory structure would force kicad-cli sch merge to
3480 // mkdir into user space; the basename-flat scheme is what makes the common
3481 // git-mergetool case work without surprises.
3482 const wxString outDir = outFn.GetPath();
3483
3484 SCH_SCREENS screens( rootSheet );
3485 SCH_SCREEN* rootScreen = rootSheet->GetScreen();
3486
3487 // Detect two sub-sheets sharing a basename (e.g., a/foo.kicad_sch and
3488 // b/foo.kicad_sch) before any I/O — the flat output layout can't honor
3489 // both, and silently overwriting one is the worst outcome.
3490 std::map<wxString, SCH_SCREEN*> basenameOwner;
3491
3492 for( size_t i = 0; i < screens.GetCount(); ++i )
3493 {
3494 SCH_SCREEN* screen = screens.GetScreen( i );
3495
3496 if( !screen || screen == rootScreen )
3497 continue;
3498
3499 const wxString basename = wxFileName( screen->GetFileName() ).GetFullName();
3500
3501 if( basename.IsEmpty() )
3502 continue;
3503
3504 auto [it, inserted] = basenameOwner.emplace( basename, screen );
3505
3506 if( !inserted && it->second != screen )
3507 {
3508 m_reporter->Report( wxString::Format( _( "Cannot flatten sub-sheets with duplicate "
3509 "basename '%s'\n" ),
3510 basename ),
3513 }
3514 }
3515
3516 // Rewrite every SCH_SHEET symbol's filename field to its child screen's
3517 // basename, so the root file (and any intermediate sheet) references the
3518 // flattened layout we're about to write.
3519 for( size_t i = 0; i < screens.GetCount(); ++i )
3520 {
3521 SCH_SCREEN* parent = screens.GetScreen( i );
3522
3523 if( !parent )
3524 continue;
3525
3526 for( SCH_ITEM* item : parent->Items().OfType( SCH_SHEET_T ) )
3527 {
3528 SCH_SHEET* childRef = static_cast<SCH_SHEET*>( item );
3529 SCH_SCREEN* childScreen = childRef->GetScreen();
3530
3531 if( !childScreen || childScreen == rootScreen )
3532 continue;
3533
3534 const wxString basename = wxFileName( childScreen->GetFileName() ).GetFullName();
3535
3536 if( !basename.IsEmpty() )
3537 childRef->SetFileName( basename );
3538 }
3539 }
3540
3541 try
3542 {
3543 IO_RELEASER<SCH_IO> pi( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
3544 pi->SaveSchematicFile( outFn.GetFullPath(), rootSheet, ancestor.doc.get() );
3545
3546 for( size_t i = 0; i < screens.GetCount(); ++i )
3547 {
3548 SCH_SCREEN* screen = screens.GetScreen( i );
3549 SCH_SHEET* sheet = screens.GetSheet( i );
3550
3551 if( !screen || !sheet || screen == rootScreen )
3552 continue;
3553
3554 const wxString basename = wxFileName( screen->GetFileName() ).GetFullName();
3555
3556 if( basename.IsEmpty() )
3557 continue;
3558
3559 wxFileName outSubFn( outDir, basename );
3560 pi->SaveSchematicFile( outSubFn.GetFullPath(), sheet, ancestor.doc.get() );
3561 }
3562 }
3563 catch( const IO_ERROR& ioe )
3564 {
3565 m_reporter->Report( wxString::Format( _( "Failed to save merged schematic: %s\n" ), ioe.What() ),
3568 }
3569
3570 // If the applier mutated project-file-scoped state (ERC severities, etc),
3571 // persist it as a sibling .kicad_pro alongside the .kicad_sch output —
3572 // otherwise the resolution dies with the process. Only write when actually
3573 // needed; clobbering an existing .kicad_pro with ancestor's project
3574 // would lose unrelated user settings (library tables, mru paths).
3575 if( applier.GetReport().projectFileTouched && ancestor.project )
3576 {
3577 wxFileName proFn = outFn;
3578 proFn.SetExt( FILEEXT::ProjectFileExtension );
3579
3580 // JSON-patch path: only the diffed DOC_PROP fields are written into
3581 // the output .kicad_pro, so any non-diffed user customisations
3582 // (library tables, last paths, layer presets, text variables) are
3583 // preserved. Fall back to SaveProjectCopy on parse failure.
3584 PROJECT_FILE& ancProj = ancestor.project->GetProjectFile();
3585 ancProj.Store();
3586
3587 const KICAD_DIFF::SCH_MERGE_APPLIER::REPORT& mergeReport = applier.GetReport();
3588
3589 // PROJECT_FILE::Store() flushes the project file's own params but not
3590 // its registered NESTED_SETTINGS. Flush only the resolved nested
3591 // settings so Internals() reflects the merge result without touching
3592 // unrelated project subtrees.
3593 if( mergeReport.ercSeveritiesTouched && ancestor.doc )
3594 ancestor.doc->ErcSettings().SaveToFile( wxEmptyString, true );
3595
3596 if( mergeReport.drawingSheetFileTouched && ancestor.doc )
3597 ancestor.doc->Settings().SaveToFile( wxEmptyString, true );
3598
3599 std::set<wxString> touched;
3600 if( mergeReport.ercSeveritiesTouched )
3601 touched.insert( KICAD_DIFF::DOC_PROP_ERC_SEVERITIES );
3602
3603 if( mergeReport.drawingSheetFileTouched )
3604 touched.insert( KICAD_DIFF::DOC_PROP_DRAWING_SHEET );
3605
3606 if( !KICAD_DIFF::ApplyProjectFilePatches( proFn.GetFullPath(), *ancProj.Internals(), touched,
3608 {
3609 if( !Pgm().GetSettingsManager().SaveProjectCopy( proFn.GetFullPath(), ancestor.project ) )
3610 {
3611 m_reporter->Report(
3612 wxString::Format( _( "Failed to save merged project file: %s\n" ), proFn.GetFullPath() ),
3615 }
3616 }
3617 }
3618
3619 // Surface post-apply validator findings (refdes collisions, schema
3620 // mismatch, missed connectivity rebuild). Advisory — they do not change the
3621 // exit code, only the merge's resolved/unresolved status does.
3623 m_reporter->Report( wxString::Format( wxS( "%s: %s\n" ), f.validator, f.message ), f.severity );
3624
3625 // The merged schematic was written to m_outputPath above, so the output is
3626 // always valid. Unresolved conflicts are reported and signalled via the
3627 // exit code; the user resolves them with the interactive mergetool.
3628 if( !planSnapshot.Resolved() )
3629 {
3630 m_reporter->Report( wxString::Format( _( "Merge completed with %zu unresolved conflict(s) in %s\n" ),
3631 planSnapshot.ConflictCount(), aOutput ),
3634 }
3635
3637}
3638
3639
3640// ============================================================================
3641// JobSymLibMerge: 3-way merge of .kicad_sym libraries.
3642// ============================================================================
3645#include <wx/ffile.h>
3646
3647
3648int EESCHEMA_JOBS_HANDLER::runSymLibMerge( const wxString& aAncestor, const wxString& aOurs,
3649 const wxString& aTheirs, const wxString& aOutput, bool aInteractive )
3650{
3651 if( aOutput.IsEmpty() )
3652 {
3653 m_reporter->Report( _( "--output is required\n" ), RPT_SEVERITY_ERROR );
3655 }
3656
3657 // Three sides into name -> LIB_SYMBOL maps.
3658 struct LIB_SIDE
3659 {
3660 std::vector<std::unique_ptr<LIB_SYMBOL>> owners;
3662 };
3663
3664 LIB_SIDE ancestor, ours, theirs;
3665
3666 auto loadSide = [&]( const wxString& aPath, LIB_SIDE& aSide ) -> int
3667 {
3668 try
3669 {
3670 auto loaded = KICAD_DIFF::SYM_LIB_DIFFER::LoadLibrary( aPath );
3671 aSide.owners = std::move( loaded.first );
3672 aSide.map = std::move( loaded.second );
3674 }
3675 catch( const IO_ERROR& ioe )
3676 {
3677 m_reporter->Report( wxString::Format( _( "Failed to load %s: %s\n" ), aPath, ioe.What() ),
3679 }
3680 catch( const std::exception& e )
3681 {
3682 m_reporter->Report(
3683 wxString::Format( _( "Failed to load %s: %s\n" ), aPath, wxString::FromUTF8( e.what() ) ),
3685 }
3686
3688 };
3689
3690 if( int rc = loadSide( aAncestor, ancestor ); rc != CLI::EXIT_CODES::SUCCESS )
3691 return rc;
3692
3693 if( int rc = loadSide( aOurs, ours ); rc != CLI::EXIT_CODES::SUCCESS )
3694 return rc;
3695
3696 if( int rc = loadSide( aTheirs, theirs ); rc != CLI::EXIT_CODES::SUCCESS )
3697 return rc;
3698
3699 KICAD_DIFF::SYM_LIB_DIFFER ourDiff( ancestor.map, ours.map, aOurs );
3700 KICAD_DIFF::SYM_LIB_DIFFER theirDiff( ancestor.map, theirs.map, aTheirs );
3701
3702 KICAD_DIFF::DOCUMENT_DIFF ourDocDiff = ourDiff.Diff();
3703 KICAD_DIFF::DOCUMENT_DIFF theirDocDiff = theirDiff.Diff();
3704
3706 KICAD_DIFF::MERGE_PLAN plan = engine.Plan( ourDocDiff, theirDocDiff );
3707
3708 std::map<KIID_PATH, const KICAD_DIFF::ITEM_CHANGE*> ourChanges = KICAD_DIFF::IndexChangesByKiid( ourDocDiff );
3709 std::map<KIID_PATH, const KICAD_DIFF::ITEM_CHANGE*> theirChanges = KICAD_DIFF::IndexChangesByKiid( theirDocDiff );
3710
3711 auto changeFor = []( const std::map<KIID_PATH, const KICAD_DIFF::ITEM_CHANGE*>& aChanges,
3712 const KIID_PATH& aId ) -> const KICAD_DIFF::ITEM_CHANGE*
3713 {
3714 auto it = aChanges.find( aId );
3715 return it != aChanges.end() ? it->second : nullptr;
3716 };
3717
3718 auto combine = [&]( const KIID_PATH& aId ) -> std::unique_ptr<LIB_SYMBOL>
3719 {
3720 const KICAD_DIFF::ITEM_CHANGE* ourChange = changeFor( ourChanges, aId );
3721 const KICAD_DIFF::ITEM_CHANGE* theirChange = changeFor( theirChanges, aId );
3722
3723 if( !ourChange || !theirChange || !ourChange->refdes )
3724 return nullptr;
3725
3726 const wxString& name = *ourChange->refdes;
3727 auto ancestorSymbol = ancestor.map.find( name );
3728 auto ourSymbol = ours.map.find( name );
3729 auto theirSymbol = theirs.map.find( name );
3730
3731 if( ancestorSymbol == ancestor.map.end() || ourSymbol == ours.map.end() || theirSymbol == theirs.map.end() )
3732 return nullptr;
3733
3734 return KICAD_DIFF::CombineSymbolEdits( *ancestorSymbol->second, *ourSymbol->second, *theirSymbol->second,
3735 *ourChange, *theirChange );
3736 };
3737
3738 std::function<std::set<wxString>( const KIID_PATH& )> editedNames;
3739
3740 // Only the dialog can settle two edits of one symbol that do not combine
3741 if( aInteractive )
3742 editedNames = KICAD_DIFF::EditedNamesIn( ourDocDiff, theirDocDiff );
3743
3745 plan,
3746 [&]( const KIID_PATH& aId )
3747 {
3748 return combine( aId ) != nullptr;
3749 },
3750 editedNames );
3751
3752 bool userDecided = false;
3753
3754 if( aInteractive && !KICAD_DIFF::BuildConflictList( plan ).empty() )
3755 {
3758
3759 std::set<wxString> names;
3760
3761 for( const KICAD_DIFF::SYM_LIB_DIFFER::SYMBOL_MAP* side : { &ancestor.map, &ours.map, &theirs.map } )
3762 {
3763 for( const auto& [name, symbol] : *side )
3764 names.insert( name );
3765 }
3766
3767 // Each side is drawn over the common version so its own edits stand out
3769 names,
3770 [&]( WIDGET_DIFF_CANVAS& aCanvas, DIALOG_KICAD_MERGE_3WAY::SIDE aSide, const wxString& aName )
3771 {
3772 const KICAD_DIFF::SYM_LIB_DIFFER::SYMBOL_MAP* side = &ours.map;
3773
3775 side = &theirs.map;
3776 else if( aSide == DIALOG_KICAD_MERGE_3WAY::SIDE::ANCESTOR )
3777 side = &ancestor.map;
3778
3779 KICAD_DIFF::ShowSymbolPair( aCanvas, ancestor.map, *side, aName );
3780 } );
3781
3782 DIALOG_KICAD_MERGE_3WAY dlg( wxTheApp->GetTopWindow(), plan, std::move( ctx ) );
3783
3784 // Cancelling leaves the conflicts unresolved and the files untouched
3785 if( dlg.ShowModal() != wxID_APPLY )
3787
3788 plan = dlg.GetResolvedPlan();
3789 userDecided = true;
3790 }
3791
3792 const KICAD_DIFF::MERGE_PLAN planSnapshot = plan;
3793
3794 KICAD_DIFF::SYM_LIB_MERGE_APPLIER applier( ancestor.map, ours.map, theirs.map, std::move( plan ), combine );
3795 std::vector<std::unique_ptr<LIB_SYMBOL>> merged = applier.Apply();
3796
3797 // A symbol whose edits do not combine falls back to our side. Surface that
3798 // as unresolved so the user sees a marker instead of silent partial-merge.
3799 const bool hadSilentFallback = applier.GetReport().mergePropsFallback > 0;
3800
3801 // Serialize via the sexpr lib cache: create at output path, add each
3802 // merged symbol, save. The cache owns its symbols once added.
3803 wxFileName outFn( aOutput );
3804 outFn.MakeAbsolute();
3805
3806 try
3807 {
3808 SCH_IO_KICAD_SEXPR_LIB_CACHE cache( outFn.GetFullPath() );
3809
3810 // SCH_IO_LIB_CACHE::AddSymbol takes ownership; the cache destructor
3811 // deletes the symbols it holds.
3812 for( auto& sym : merged )
3813 {
3814 if( sym )
3815 cache.AddSymbol( std::move( sym ) );
3816 }
3817
3818 cache.SetModified( true );
3819 cache.Save();
3820 }
3821 catch( const IO_ERROR& ioe )
3822 {
3823 m_reporter->Report( wxString::Format( _( "Failed to save merged symbol library: %s\n" ), ioe.What() ),
3826 }
3827
3828 // The merged library was saved above, so the output is always valid.
3829 try
3830 {
3831 // A pick can still orphan a derived symbol, which the reload rejects
3832 auto [mergedOwners, mergedMap] = KICAD_DIFF::SYM_LIB_DIFFER::LoadLibrary( outFn.GetFullPath() );
3833
3834 // A side the user picks drops the other side's edit on purpose
3835 if( userDecided && planSnapshot.Resolved() && !hadSilentFallback )
3837
3838 // Unresolved symbols fall back to one side, so a merge is clean only when it provably keeps both
3839 if( KICAD_DIFF::SYM_LIB_DIFFER::MergeKeepsBothSides( ancestor.map, ours.map, theirs.map, mergedMap ) )
3841 }
3842 catch( const IO_ERROR& ioe )
3843 {
3844 m_reporter->Report( wxString::Format( _( "Failed to load %s: %s\n" ), aOutput, ioe.What() ),
3846 }
3847
3848 if( !planSnapshot.Resolved() || hadSilentFallback )
3849 {
3850 // Conflict count = engine-unresolved ∪ applier-downgraded (deduped, so
3851 // an item that was both unresolved and silently downgraded counts once).
3852 std::set<KIID_PATH> conflicts( planSnapshot.unresolved.begin(), planSnapshot.unresolved.end() );
3853
3854 for( const KIID_PATH& id : applier.GetReport().mergePropsFallbackIds )
3855 conflicts.insert( id );
3856
3857 m_reporter->Report( wxString::Format( _( "Symbol library merge completed with %zu unresolved "
3858 "conflict(s) in %s\n" ),
3859 conflicts.size(), aOutput ),
3862 }
3863
3864 m_reporter->Report( wxString::Format( _( "Symbol library merge in %s dropped an edit from one side\n" ), aOutput ),
3867}
const char * name
constexpr EDA_IU_SCALE schIUScale
Definition base_units.h:130
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
int GetPageCount() const
Definition base_screen.h:68
int GetVirtualPageNumber() const
Definition base_screen.h:71
const wxString & GetPageNumber() const
Color settings are a bit different than most of the settings objects in that there can be more than o...
What an export to a given target will keep, approximate, drop, or block.
void Add(DOWNGRADE_BUCKET aBucket, const wxString &aFeature, const wxString &aDetail=wxEmptyString, int aCount=1)
void Print(REPORTER *aReporter) const
void Merge(const COMPATIBILITY_REPORT &aOther)
bool IsLossy() const
True if anything is approximated or dropped. This is what triggers the lossy warning.
bool IsBlocked() const
True if some feature makes the target impossible. The user cannot export anyway.
File-compare dialog (Phase 7).
Resolve a three-way merge by choosing a version for each conflicting item.
const KICAD_DIFF::MERGE_PLAN & GetResolvedPlan() const
Returns the plan with the user's resolutions applied.
static CONFLICT_CONTEXT LibraryContext(const std::set< wxString > &aNames, LIBRARY_ITEM_DRAWER aDraw)
Context for merging a library, whose items are known by the names in aNames.
static bool CanOpen(REPORTER &aReporter)
Report to aReporter and return false when this process cannot open a dialog.
SIDE
Which side's version the canvas should currently display.
int ShowModal() override
Stage related design and library files together, retaining originals until every write is ready.
const wxString & GetRecoveryError() const
Recovery details are nonempty only if restoring an original or removing a new output failed.
wxString Commit()
Replace all destinations, rolling back earlier replacements if a rename fails.
wxString Stage(const wxString &aDestination)
Return an exclusively-created sibling staging file, or empty if it cannot be created.
bool Create(const wxString &aDirectory, bool aOwnContents=false)
static DS_DATA_MODEL & GetTheInstance()
Return the instance of DS_DATA_MODEL used in the application.
void SetSheetPath(const std::string &aSheetPath)
Set the sheet path displayed in the title block.
void SetSheetCount(int aSheetCount)
Change the sheet-count number displayed in the title block.
void SetVariantName(const std::string &aVariant)
Set the current variant name and description to be shown on the drawing sheet.
void SetVariantDesc(const std::string &aVariantDesc)
void SetPageNumber(const std::string &aPageNumber)
Change the page number displayed in the title block.
void SetSheetName(const std::string &aSheetName)
Set the sheet name displayed in the title block.
void SetPageBorderColorLayer(int aLayerId)
Override the layer used to pick the color of the page border (normally LAYER_GRID)
void SetIsFirstPage(bool aIsFirstPage)
Change if this is first page.
void SetFileName(const std::string &aFileName)
Set the file name displayed in the title block.
void SetColorLayer(int aLayerId)
Can be used to override which layer ID is used for drawing sheet item colors.
const KIID m_Uuid
Definition eda_item.h:599
static SCHEMATIC * LoadSchematic(const wxString &aFileName, bool aSetActive, bool aForceDefaultProject, PROJECT *aProject=nullptr, bool aCalculateConnectivity=true, REPORTER *aRootReporter=nullptr)
int runSchMerge(const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive)
void InitRenderSettings(SCH_RENDER_SETTINGS *aRenderSettings, const wxString &aTheme, SCHEMATIC *aSch, const wxString &aDrawingSheetOverride=wxEmptyString)
Configure the SCH_RENDER_SETTINGS object with the correct data to be used with plotting.
int RunMerge(KICAD_DIFF::DOC_KIND aKind, const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive, bool aSingleFile, REPORTER *aReporter)
Non-job entry points (reached via the kiface KIFACE_MERGE_DOCUMENT / KIFACE_OPEN_DIFF_DIALOG function...
DS_PROXY_VIEW_ITEM * getDrawingSheetProxyView(SCHEMATIC *aSch)
KICAD_DIFF::DIFF_CANVAS_CONTEXT * AttachDiffCanvases(KICAD_DIFF::DOC_KIND aKind, const wxString &aFileA, const wxString &aFileB, WIDGET_DIFF_CANVAS *aBefore, WIDGET_DIFF_CANVAS *aAfter, KICAD_DIFF::DOCUMENT_DIFF &aDiff, REPORTER *aReporter)
Diff two schematics for a window outside the kiface, drawing the first on aBefore and the second on a...
int runSymLibMerge(const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive)
SCHEMATIC * getSchematic(const wxString &aPath, bool aRequireRoot=true)
int OpenDiffDialog(KICAD_DIFF::DOC_KIND aKind, const wxString &aFileA, const wxString &aFileB, const wxString &aLabelA, const wxString &aLabelB, wxWindow *aParent, REPORTER *aReporter)
void ClearCachedSchematic()
Clear the cached CLI schematic so the next job reloads from the current project.
int doSymExportSvg(JOB_SYM_EXPORT_SVG *aSvgJob, SCH_RENDER_SETTINGS *aRenderSettings, LIB_SYMBOL *symbol)
EE_TYPE OfType(KICAD_T aType) const
Definition sch_rtree.h:248
bool WriteJsonReport(const wxString &aFullFileName)
Writes a JSON formatted ERC Report to the given file path in the c-locale.
bool WriteTextReport(const wxString &aFullFileName)
Writes the text report also available via GetTextReport directly to a given file path.
Container for ERC settings.
Runs the electrical rules checks and adds a SCH_MARKER for each violation.
Definition erc.h:60
void RunTests(DS_PROXY_VIEW_ITEM *aDrawingSheet, SCH_EDIT_FRAME *aEditFrame, KIFACE *aCvPcb, PROJECT *aProject, PROGRESS_REPORTER *aProgressReporter)
Definition erc.cpp:3522
void SetVariantNames(const std::vector< wxString > &aVariantNames)
std::vector< BOM_FIELD > GetFieldsOrdered()
static const wxString ITEM_NUMBER_VARIABLE
wxString Export(const BOM_FMT_PRESET &aSettings)
int GetFieldNameCol(const wxString &aFieldName) const
void ApplyBomPreset(const BOM_PRESET &aPreset)
void AddColumn(const wxString &aFieldName, const wxString &aLabel, bool aAddedByUser) override
void SetCurrentVariant(const wxString &aVariantName) override
Select the displayed variant, retaining un-applied edits in every variant.
Reporter handed to an importer during an import job.
void Flush(IMPORT_REPORT_FORMAT aFormat, IMPORT_REPORT_DATA &aData)
Move the collected messages into aData when a report will be written, otherwise forward them to the j...
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()
wxString m_inputB
Comparison document (file or directory)
wxString m_inputA
Reference document (file or directory)
void Register(const std::string &aJobTypeName, std::function< int(JOB *job)> aHandler, std::function< bool(JOB *job, wxWindow *aParent)> aConfigHandler)
JOB_DISPATCHER(KIWAY *aKiway)
PROGRESS_REPORTER * m_progressReporter
REPORTER * m_reporter
wxString GetSelectedVariant() const
std::vector< wxString > m_variantNames
wxString m_stringDelimiter
wxString m_fieldDelimiter
bool m_includeByteOrderMark
wxString m_filename
wxString m_filterString
std::vector< wxString > m_fieldsOrdered
wxString m_refRangeDelimiter
std::vector< wxString > m_fieldsLabels
wxString m_refDelimiter
std::vector< wxString > m_fieldsGroupBy
wxString m_bomFmtPresetName
wxString m_sortField
wxString m_bomPresetName
BOM_FILTER_SCOPE m_filterScope
std::vector< wxString > m_variantNames
JOB_PAGE_SIZE m_pageSizeSelect
SCH_PLOT_FORMAT m_plotFormat
std::vector< wxString > m_variantNames
std::vector< wxString > m_plotPages
bool m_exitCodeViolations
Definition job_rc.h:52
int m_severity
Definition job_rc.h:49
UNITS m_units
Definition job_rc.h:48
OUTPUT_FORMAT m_format
Definition job_rc.h:50
wxString m_filename
Definition job_rc.h:47
std::vector< wxString > m_foundVariants
Variant names found in the schematic when the target drops variants.
wxString m_outputDir
Write downgraded sheets under this fresh folder.
wxString m_variant
Flatten this variant into the export. Empty means the base design.
wxString m_libraryDir
If set, downgrade every .kicad_sym symbol library under this folder too.
bool m_inPlace
Internal only: convert the coordinator's already-copied export files.
bool m_dryRun
Only classify and fill m_report, do not write anything.
wxString m_filename
Root schematic file (may be empty to downgrade only libraries)
COMPATIBILITY_REPORT m_report
Filled by the handler so the caller can show it.
wxString m_target
Target release name or id, e.g. "KiCad 10.0" or "10.0". Empty means the newest.
bool m_dropInsteadOfApproximate
Omit features that would otherwise be approximated.
bool m_force
Export even when features must be dropped or approximated.
Job to import a non-KiCad schematic file to KiCad format.
wxString m_reportFile
wxString m_inputFile
IMPORT_REPORT_FORMAT m_reportFormat
std::map< wxString, wxString > m_netNameMap
COMPATIBILITY_REPORT m_report
Filled by the handler so the caller can show it.
wxString m_libraryPath
The .kicad_sym library to convert.
wxString m_target
Target release name or id, e.g. "KiCad 9.0". Empty means the newest.
bool m_force
Convert even when features must be dropped or approximated.
bool m_dryRun
Only classify and fill m_report, do not write anything.
wxString m_outputLibraryPath
Where to write the converted copy.
bool m_dropInsteadOfApproximate
Omit features that would otherwise be approximated.
wxString m_outputLibraryPath
An simple container class that lets us dispatch output jobs to kifaces.
Definition job.h:184
void SetConfiguredOutputPath(const wxString &aPath)
Sets the configured output path for the job, this path is always saved to file.
Definition job.cpp:181
void AddOutput(wxString aOutputPath)
Definition job.h:216
wxString GetFullOutputPath(PROJECT *aProject) const
Returns the full output path for the job, taking into account the configured output path,...
Definition job.cpp:174
static wxString AppendDefaultFileName(const wxString &aPath, const wxString &aDefaultName)
Complete a resolved file output path that names a folder, either by a trailing separator or by being ...
Definition job.cpp:152
bool GetOutputPathIsDirectory() const
Definition job.h:266
wxString GetConfiguredOutputPath() const
Returns the configured output path for the job.
Definition job.h:235
void SetTitleBlock(const TITLE_BLOCK &aTitleBlock)
Definition job.h:204
void SetWorkingOutputPath(const wxString &aPath)
Sets a transient output path for the job, it takes priority over the configured output path when GetF...
Definition job.h:241
const std::map< wxString, wxString > & GetVarOverrides() const
Definition job.h:197
std::optional< nlohmann::json > GetJson(const std::string &aPath) const
Fetches a JSON object that is a subset of this JSON_SETTINGS object, using a path of the form "key1....
JSON_SETTINGS_INTERNALS * Internals()
Keeps the documents drawn on a pair of diff canvases alive.
Three-way merge plan generator.
MERGE_PLAN Plan(const DOCUMENT_DIFF &aAncestorOurs, const DOCUMENT_DIFF &aAncestorTheirs) const
Plan the merge given the canonical pair of diffs.
const REPORT & GetReport() const
std::vector< std::unique_ptr< ITEM > > Apply()
Diff two already-parsed SCHEMATICs and produce a DOCUMENT_DIFF.
Definition sch_differ.h:55
DOCUMENT_DIFF Diff() override
Produce a DOCUMENT_DIFF of the inputs the concrete differ was constructed with.
Materialize a MERGE_PLAN into a merged SCHEMATIC by mutating the ancestor in place.
bool Apply()
Apply the plan to the ancestor.
const REPORT & GetReport() const
Diff two .kicad_sym symbol libraries.
static bool MergeKeepsBothSides(const SYMBOL_MAP &aAncestor, const SYMBOL_MAP &aOurs, const SYMBOL_MAP &aTheirs, const SYMBOL_MAP &aMerged)
True when aMerged differs from each side of a three-way merge exactly as the other side differs from ...
DOCUMENT_DIFF Diff() override
Produce a DOCUMENT_DIFF of the inputs the concrete differ was constructed with.
static std::pair< std::vector< std::unique_ptr< LIB_SYMBOL > >, SYMBOL_MAP > LoadLibrary(const wxString &aPath)
Convenience: load a .kicad_sym path into a SYMBOL_MAP using SCH_IO_KICAD_SEXPR::EnumerateSymbolLib.
std::map< wxString, const LIB_SYMBOL * > SYMBOL_MAP
Library content is a map of (canonical_name -> LIB_SYMBOL*).
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
void SetDefaultPenWidth(int aWidth)
void SetGapLengthRatio(double aRatio)
void SetDashLengthRatio(double aRatio)
Definition kiid.h:46
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:348
virtual KIWAY_PLAYER * Player(FRAME_T aFrameType, bool doCreate=true, wxTopLevelWindow *aParent=nullptr)
Return the KIWAY_PLAYER* given a FRAME_T.
Definition kiway.cpp:407
@ FACE_CVPCB
Definition kiway.h:357
void AsyncLoad()
Loads all available libraries for this adapter type in the background.
Define a library symbol object.
Definition lib_symbol.h:114
bool IsDerived() const
Definition lib_symbol.h:241
std::shared_ptr< LIB_SYMBOL > GetRootSymbol() const
Get the parent symbol that does not have another parent.
wxString GetName() const override
Definition lib_symbol.h:183
const std::vector< wxString > & GetBodyStyleNames() const
bool HasDeMorganBodyStyles() const override
int GetBodyStyleCount() const override
The body styles are a property of the drawings, which a derived symbol inherits from its root symbol ...
int GetUnitCount() const override
Instantiate the current locale within a scope in which you are expecting exceptions to be thrown.
Definition locale_io.h:37
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
Definition paths.cpp:470
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
The backing store for a PROJECT, in JSON format.
ERC_SETTINGS * m_ErcSettings
Eeschema params.
SCHEMATIC_SETTINGS * m_SchematicSettings
TEMPLATES m_TemplateFieldNames
Project and global field name templates shared by project editors.
bool Store() override
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
std::vector< TOP_LEVEL_SHEET_INFO > & GetTopLevelSheets()
static SYMBOL_LIBRARY_ADAPTER * SymbolLibAdapter(PROJECT *aProject)
Accessor for project symbol library manager adapter.
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
virtual void ApplyTextVars(const std::map< wxString, wxString > &aVarsMap)
Applies the given var map, it will create or update existing vars.
Definition project.cpp:229
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
These are loaded from Eeschema settings but then overwritten by the project settings.
Holds all the data relating to one schematic.
Definition schematic.h:155
void SetCurrentVariant(const wxString &aVariantName)
wxString GetVariantDescription(const wxString &aVariantName) const
Return the description for a variant.
void LoadVariants()
This is a throw away method for variant testing.
SCH_SHEET_LIST BuildSheetListSortedByPageNumbers() const
const std::vector< std::shared_ptr< BUS_ALIAS > > & GetAllBusAliases() const
Definition schematic.h:457
wxString GetFileName() const
Helper to retrieve the filename from the root sheet screen.
SCHEMATIC_SETTINGS & Settings() const
SCH_SHEET_LIST Hierarchy() const
Return the full schematic flattened hierarchical sheet list.
SCH_SHEET_LIST BuildUnorderedSheetList() const
PROJECT & Project() const
Return a reference to the project this schematic is part of.
Definition schematic.h:177
void SetProject(PROJECT *aPrj)
void DeleteVariant(const wxString &aVariantName, SCH_COMMIT *aCommit)
Delete all information for aVariantName.
wxString GetCurrentVariant() const
Return the current variant being edited.
SCH_SCREEN * RootScreen() const
Helper to retrieve the screen of the root sheet.
void SetTopLevelSheets(const std::vector< SCH_SHEET * > &aSheets)
Replace the top level sheets, rebuilding the hierarchy and connectivity around them.
const std::set< wxString > & GetVariantNames() const
Return the set of variant names (without the default placeholder).
Definition schematic.h:770
const std::map< wxString, wxString > * GetProperties()
Definition schematic.h:180
SCH_SHEET & Root() const
Definition schematic.h:282
std::vector< SCH_SHEET * > GetTopLevelSheets() const
Get the list of top-level sheets.
Commit for the schematic and symbol editors.
Definition sch_commit.h:54
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
SCH_DIFF_CANVAS_CONTEXT(WIDGET_DIFF_CANVAS *aBefore, WIDGET_DIFF_CANVAS *aAfter)
Schematic editor (Eeschema) main window.
SCHEMATIC & Schematic() const
A cache assistant for the KiCad s-expression symbol libraries.
void Save(const std::optional< bool > &aOpt=std::nullopt) override
Save the entire library to file m_libFileName;.
A SCH_IO derivation for loading schematic files using the new s-expression file format.
void EnumerateSymbolLib(wxArrayString &aSymbolNameList, const wxString &aLibraryPath, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Populate a list of LIB_SYMBOL alias names contained within the library aLibraryPath.
void SetFileName(const wxString &aFileName)
void SetModified(bool aModified=true)
virtual void AddSymbol(std::unique_ptr< LIB_SYMBOL > aSymbol)
static bool ConvertLibrary(std::map< std::string, UTF8 > *aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilepath, REPORTER *aReporter=nullptr)
Convert a schematic symbol library to the latest KiCad format.
static const wxString ShowType(SCH_FILE_T aFileType)
Return a brief name for a plugin, given aFileType enum.
static SCH_FILE_T GuessPluginTypeFromSchPath(const wxString &aSchematicPath, int aCtl=0)
Return a plugin type given a schematic using the file extension of aSchematicPath.
static SCH_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a symbol library using the file extension of aLibPath.
Base class for any item which can be embedded within the SCHEMATIC container class,...
Definition sch_item.h:170
Container to create a flattened list of symbols because in a complex hierarchy, a symbol can be used ...
int CheckAnnotation(ANNOTATION_ERROR_HANDLER aErrorHandler)
Check for annotations errors.
A helper to define a symbol's reference designator in a schematic.
void LoadColors(const COLOR_SETTINGS *aSettings) override
Container class that holds multiple SCH_SCREEN objects in a hierarchy.
Definition sch_screen.h:826
SCH_SCREEN * GetNext()
SCH_SCREEN * GetScreen(unsigned int aIndex) const
SCH_SCREEN * GetFirst()
size_t GetCount() const
Definition sch_screen.h:831
SCH_SHEET * GetSheet(unsigned int aIndex) const
const PAGE_INFO & GetPageSettings() const
Definition sch_screen.h:144
EE_RTREE & Items()
Get the full RTree, usually for iterating.
Definition sch_screen.h:122
const wxString & GetFileName() const
Definition sch_screen.h:157
int GetFileFormatVersionAtLoad() const
Definition sch_screen.h:142
TITLE_BLOCK & GetTitleBlock()
Definition sch_screen.h:168
A container for handling SCH_SHEET_PATH objects in a flattened hierarchy.
std::optional< SCH_SHEET_PATH > GetSheetPathByKIIDPath(const KIID_PATH &aPath, bool aIncludeLastSheet=true) const
Finds a SCH_SHEET_PATH that matches the provided KIID_PATH.
void GetSymbols(SCH_REFERENCE_LIST &aReferences, SYMBOL_FILTER aSymbolFilter, bool aForceIncludeOrphanSymbols=false) const
Add a SCH_REFERENCE object to aReferences for each symbol in the list of sheets.
Handle access to a stack of flattened SCH_SHEET objects by way of a path for creating a flattened sch...
Sheet symbol placed in a schematic, and is the entry point for a sub schematic.
Definition sch_sheet.h:50
void SetFileName(const wxString &aFilename)
Definition sch_sheet.h:434
wxString GetName() const
Definition sch_sheet.h:150
void SetName(const wxString &aName)
Definition sch_sheet.h:185
SCH_SCREEN * GetScreen() const
Definition sch_sheet.h:187
bool IsVirtualRootSheet() const
Schematic symbol object.
Definition sch_symbol.h:76
void GetFields(std::vector< SCH_FIELD * > &aVector, bool aVisibleOnly) const override
Populate a std::vector with SCH_FIELDs, sorted in ordinal order.
RAII class that sets an value at construction and resets it to the original value at destruction.
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only project.
bool IsProjectOpenNotDummy() const
Helper for checking if we have a project open that is not a dummy project.
bool LoadProject(const wxString &aFullPath, bool aSetActive=true, bool aOverrideLock=false)
Load a project or sets up a new project with a specified path.
void UpdateReferences(const SCH_REFERENCE_LIST &aRefs)
const SCH_REFERENCE_LIST & GetReferenceList() const
An interface to the global shared library manager that is schematic-specific and linked to one projec...
const std::vector< TEMPLATE_FIELDNAME > & GetResolvedTemplateFieldNames()
Return the resolved project and global template field name list for read only access.
GAL-backed canvas for visualizing a KICAD_DIFF::DIFF_SCENE.
wxString GetGeneratedFieldDisplayName(const wxString &aSource)
Returns any variables unexpanded, e.g.
Definition common.cpp:481
bool IsGeneratedField(const wxString &aFieldName)
Returns true if the entire string is generated, e.g is a single text var reference.
Definition common.cpp:494
wxString GetDefaultPlotExtension(PLOT_FORMAT aFormat)
Return the default plot extension for a format.
@ DROP
No equivalent, left out.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
#define DEFAULT_LINE_WIDTH_MILS
The default line width in mils. (can be changed in preference menu)
static bool empty(const wxTextEntryBase *aCtrl)
wxString DowngradeWxPath(const std::filesystem::path &aPath)
wxString DowngradeLibraryCopyPath(const wxString &aLibrary, const wxString &aOutputDirectory)
bool ValidateDowngradeLibrarySource(const wxString &aSource, wxString &aError)
bool ValidateDowngradeLibraryCopy(const wxString &aSource, const wxString &aDestination, wxString &aError)
bool ValidateFreshDowngradeOutput(const wxString &aOutput, wxString &aError)
bool CopyDowngradeLibraryDirectory(const wxString &aSource, const wxString &aDestination, DOWNGRADE_OUTPUT_DIRECTORIES &aDirectories, wxString &aError)
std::filesystem::path DowngradeNativePath(const wxString &aPath)
wxString DowngradeLibraryFilesInPlace(const wxString &aDir, const wxString &aGlob, int aStampVersion, const std::function< wxString(const wxString &)> &aFindForbidden, const std::function< DOWNGRADE_FILE_RESULT(const wxString &, const wxString &)> &aConvert, DOWNGRADE_FILE_TRANSACTION *aTransaction=nullptr, wxString *aRecoveryError=nullptr)
Downgrade every library file matching aGlob under aDir in place.
bool IsDowngradeWorkingArtifact(const wxString &aPath)
Editor working state (autosaves, local history, backups) holds current-format copies nothing downgrad...
DOWNGRADE_FILE_RESULT
What a per-file converter did with one library file.
@ CONVERTED
The temp file holds the downgraded copy.
bool VerifyDowngradedFile(const wxString &aPath, int aStampVersion, const std::function< wxString(const wxString &)> &aFindForbidden, wxString *aForbidden=nullptr)
Read back a downgraded output and require the target stamp plus a clean token scan.
const std::vector< DOWNGRADE_TARGET > & GetDowngradeTargets()
Supported downgrade targets, newest first.
const DOWNGRADE_TARGET * FindDowngradeTarget(const wxString &aNameOrId)
Match a user-supplied target string against name or stable id, case-insensitively.
wxString DowngradeTargetNames()
The valid target choices as one user-facing list, for error messages.
#define _(s)
EDA_UNITS
Definition eda_units.h:45
bool PrepareSaveAsFiles(SCHEMATIC &aSchematic, SCH_SCREENS &aScreens, const wxFileName &aOldRoot, const wxFileName &aNewRoot, bool aSaveCopy, bool aCopySubsheets, bool aIncludeExternSheets, std::unordered_map< SCH_SCREEN *, wxString > &aFilenameMap, wxString &aErrorMsg)
static int loadSchDiffSides(SETTINGS_MANAGER &aMgr, REPORTER &aReporter, const wxString &aFileA, const wxString &aFileB, SCH_DIFF_SIDES &aSides)
static wxString downgradeSymbolLibraries(const wxString &aDir, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate, DOWNGRADE_FILE_TRANSACTION *aTransaction=nullptr, wxString *aRecoveryError=nullptr)
static SCRATCH_DOC< SCHEMATIC > emptyScratchSchematic(SETTINGS_MANAGER &aMgr, const wxString &aTag)
static int loadSymbolLibrarySide(const wxString &aPath, std::vector< std::unique_ptr< LIB_SYMBOL > > &aOwners, KICAD_DIFF::SYM_LIB_DIFFER::SYMBOL_MAP &aMap, bool aAllowEmpty, REPORTER &aReporter)
static SCRATCH_DOC< SCHEMATIC > loadScratchSchematic(SETTINGS_MANAGER &aMgr, const wxString &aPath)
static void classifySymbolLibraries(const wxString &aDir, const DOWNGRADE_TARGET &aTarget, COMPATIBILITY_REPORT &aReport, bool aDropInsteadOfApproximate)
static KICAD_DIFF::DOCUMENT_GEOMETRY symbolLibraryGeometry(const KICAD_DIFF::SYM_LIB_DIFFER::SYMBOL_MAP &aMap, const KIGFX::COLOR4D &aColor)
ERCE_T
ERC error codes.
@ FRAME_SCH
Definition frame_type.h:30
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
static const std::string CadstarNetlistFileExtension
static const std::string NetlistFileExtension
static const std::string ReportFileExtension
static const std::string ProjectFileExtension
static const std::string JsonFileExtension
static const std::string XmlFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string OrCadPcb2NetlistFileExtension
static const std::string CsvFileExtension
static const std::string SpiceFileExtension
static const std::string SVGFileExtension
std::string source
std::map< wxString, wxString > GetBoardNetNameMap(const IMPORT_NET_MAP &aMap, REPORTER &aReporter)
Reduce the map to the board net renames it justifies.
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
wxString DefaultImportOutputPath(const wxString &aInputFile, const wxString &aKiCadExt)
Build the default output path for an import by swapping the input file's extension for the given KiCa...
bool WriteImportReport(REPORTER *aReporter, IMPORT_REPORT_FORMAT aFormat, const wxString &aReportFile, const IMPORT_REPORT_DATA &aData)
Emit an import report in the requested format to aReportFile, or to aReporter (at INFO severity) when...
#define KICAD_FONT_NAME
KIID niluuid(0)
#define KICTL_NONKICAD_ONLY
chosen file is non-KiCad according to user
@ LAYER_SCHEMATIC_DRAWINGSHEET
Definition layer_ids.h:527
@ LAYER_SCHEMATIC_PAGE_LIMITS
Definition layer_ids.h:528
static std::vector< PENDING_PROPERTY > plan(const EDA_ITEM &aSource, const EDA_ITEM &aTarget, const std::set< wxString > &aEnabledKeys)
Target properties to write, paired with values read off the source.
static const int ERR_ARGS
Definition exit_codes.h:31
static const int OK
Definition exit_codes.h:30
static const int ERR_RC_VIOLATIONS
Rules check violation count was greater than 0.
Definition exit_codes.h:37
static const int ERR_CANCELLED
The user cancelled the operation.
Definition exit_codes.h:45
static const int ERR_INVALID_INPUT_FILE
Definition exit_codes.h:33
static const int SUCCESS
Definition exit_codes.h:29
static const int ERR_INVALID_OUTPUT_CONFLICT
Definition exit_codes.h:34
static const int ERR_UNKNOWN_FILE_FORMAT
No plugin for the requested face recognized the input file format.
Definition exit_codes.h:42
static const int ERR_UNKNOWN
Definition exit_codes.h:32
const wxString DOC_PROP_ERC_SEVERITIES
void SettleLibraryMerges(MERGE_PLAN &aPlan, const std::function< bool(const KIID_PATH &)> &aCanCombine, const std::function< std::set< wxString >(const KIID_PATH &)> &aEditedNames)
Settle the MERGE_PROPS of a library merge, where an item is combined whole or not at all.
std::vector< CONFLICT_LIST_ENTRY > BuildConflictList(const MERGE_PLAN &aPlan)
void CollectChangeBBoxes(const DOCUMENT_DIFF &aDiff, std::map< KIID_PATH, BOX2I > &aOut)
Walk a DOCUMENT_DIFF and populate a (KIID_PATH → BOX2I) map with each changed item's bbox,...
DOCUMENT_GEOMETRY ExtractSymbolGeometry(const LIB_SYMBOL &aSymbol, const KIGFX::COLOR4D &aColor, int aUnit, int aBodyStyle)
Extract coarse drawable context from a library symbol for visual symbol diffs.
void ConfigureSchDiffCanvasContext(WIDGET_DIFF_CANVAS &aCanvas, SCHEMATIC *aReference, SCHEMATIC *aComparison, const KIGFX::COLOR4D &aColor, const std::map< KIID, KIGFX::COLOR4D > &aOverrides, const std::vector< KIGFX::VIEW_ITEM * > &aExtraItems, const std::map< KIID, KICAD_DIFF::CATEGORY > &aCategories, SCH_SCREEN *aReferenceScreen, SCH_SCREEN *aComparisonScreen, std::shared_ptr< const void > aOwner)
DOCUMENT_GEOMETRY ExtractSchematicGeometry(const SCHEMATIC &aSchematic, const KIGFX::COLOR4D &aColor, const std::map< KIID, KIGFX::COLOR4D > &aOverrides, bool aOnlyOverrides)
Extract a coarse outline of a SCHEMATIC into a DOCUMENT_GEOMETRY for use as background context in DIF...
wxString OlderFormatNotice(int aAncestorVersion, int aOursVersion, int aTheirsVersion, int aCurrentVersion)
Empty when every side is already in the current file format.
void AppendGeometry(DOCUMENT_GEOMETRY &aDst, DOCUMENT_GEOMETRY &&aSrc)
Move all primitives from aSrc into aDst.
DIFF_EMIT_OPTIONS MakeEmitOptions(const JOB_DIFF_BASE &aJob, const wxString &aLabelA, const wxString &aLabelB)
Build a DIFF_EMIT_OPTIONS pre-filled from the job's format, resolved output path and the supplied per...
const wxString DOC_PROP_DRAWING_SHEET
DOC_KIND
Document type a diff/merge entry point should route to, derived from a file path's extension.
int EmitDiffResult(const DOCUMENT_DIFF &aResult, const DIFF_EMIT_OPTIONS &aOptions, int aDiffExitCode, REPORTER &aReporter)
Emit a computed DOCUMENT_DIFF in the requested format.
std::unique_ptr< KIGFX::PAINTER > MakeSchDiffContextPainter(KIGFX::GAL *aGal, SCHEMATIC *aSchematic, const KIGFX::COLOR4D &aColor, std::map< KIID, KIGFX::COLOR4D > aOverrides)
std::unique_ptr< LIB_SYMBOL > CombineSymbolEdits(const LIB_SYMBOL &aAncestor, const LIB_SYMBOL &aOurs, const LIB_SYMBOL &aTheirs, const ITEM_CHANGE &aOurChange, const ITEM_CHANGE &aTheirChange)
Combine two edits of one library symbol when neither can lose anything.
void ShowSymbolPair(WIDGET_DIFF_CANVAS &aCanvas, const SYM_LIB_DIFFER::SYMBOL_MAP &aBefore, const SYM_LIB_DIFFER::SYMBOL_MAP &aAfter, const wxString &aName)
Draw the symbol aName as it is in aBefore and aAfter.
std::map< KIID_PATH, const ITEM_CHANGE * > IndexChangesByKiid(const DOCUMENT_DIFF &aDiff)
Flatten a DOCUMENT_DIFF's ITEM_CHANGE tree into a KIID_PATH -> ITEM_CHANGE* map, recursing into child...
std::function< std::set< wxString >(const KIID_PATH &)> EditedNamesIn(const DOCUMENT_DIFF &aOurs, const DOCUMENT_DIFF &aTheirs)
What either side edits in an item, for SettleLibraryMerges. Both diffs must outlive the result.
LIB_MERGE_APPLIER< LIB_SYMBOL > SYM_LIB_MERGE_APPLIER
Symbol-library 3-way merge applier. See LIB_MERGE_APPLIER for behavior.
bool ApplyProjectFilePatches(const wxString &aOutputProPath, const nlohmann::json &aSource, const std::set< wxString > &aDocProps, DOC_KIND aKind)
Higher-level orchestrator: load the existing aOutputProPath as JSON (or start from aSource if the fil...
int DiffExitCode(const DOCUMENT_DIFF &aResult)
Map a computed diff onto its CLI exit code – SUCCESS when empty, otherwise ERR_RC_VIOLATIONS.
@ GNL_OPT_BOM
static int plotJob(JOB_EXPORT_PCB_PLOT *aJob, PCB_PLOTTER &aPlotter, const LSEQ &aLayersToPlot, const wxString &aOutPath, bool aSingleOutput, bool aUseVarOverrides, bool aForceAllLayersToOnePage=false)
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
PLOT_FORMAT
The set of supported output plot formats.
Definition plotter.h:65
Plotting engines similar to ps (PostScript, Gerber, svg)
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
@ RPT_SEVERITY_ACTION
#define SKIP_CONNECTIVITY
Definition sch_commit.h:41
#define DELETE_REMOVED_ITEMS
Definition sch_commit.h:43
#define SKIP_UNDO
Definition sch_commit.h:38
COMPATIBILITY_REPORT ClassifySchematicStructureForDowngrade(const SCHEMATIC &aSchematic, const DOWNGRADE_TARGET &aTarget)
Schematic-wide structure the per-screen rules cannot see. Does not modify it.
void DowngradeScreenInPlace(SCH_SCREEN *aScreen, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Approximate or remove, in place, what the target cannot represent.
bool FlattenSchematicVariant(SCHEMATIC &aSchematic, const wxString &aVariantName, wxString *aConflict)
Bake a variant into the base attributes of every symbol and sheet.
void SaveSymbolLibraryForTarget(const std::vector< LIB_SYMBOL * > &aSymbols, const wxString &aPath, const DOWNGRADE_TARGET &aTarget)
Save a .kicad_sym library stamped for the target.
COMPATIBILITY_REPORT ClassifyLibSymbolForDowngrade(const LIB_SYMBOL *aSymbol, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Report what a library symbol would lose if exported to an older KiCad. Does not modify it.
void DowngradeLibSymbolInPlace(LIB_SYMBOL *aSymbol, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Symbol-scoped downgrade for standalone .kicad_sym files the screen pass never sees.
void SaveSchematicForTarget(SCH_SHEET *aSheet, SCHEMATIC *aSchematic, const wxString &aPath, const DOWNGRADE_TARGET &aTarget)
Save a schematic sheet file stamped for the target, using the writer for that version.
COMPATIBILITY_REPORT ClassifyScreenForDowngrade(const SCH_SCREEN *aScreen, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Report what a schematic screen would lose if exported to an older KiCad.
constexpr int SCH_VER_VARIANTS
Format dates for rules the jobs handler applies at schematic scope.
constexpr int SCH_VER_NET_CHAINS
#define SEXPR_SYMBOL_LIB_FILE_VERSION
This file contains the file format version information for the s-expression schematic and symbol libr...
#define SEXPR_SCHEMATIC_FILE_VERSION
Schematic file version.
bool PlotSymbolToSVG(LIB_SYMBOL &aDrawSymbol, LIB_SYMBOL &aFieldsSymbol, int aUnit, int aBodyStyle, const BOX2I &aBBox, SCH_RENDER_SETTINGS &aRenderSettings, bool aBlackAndWhite, const wxString &aFileName, REPORTER *aReporter)
Plot a single symbol variant (unit and body style) to an SVG file.
BOX2I GetSymbolPlotBBox(const LIB_SYMBOL &aSymbol, int aUnit, int aBodyStyle, bool aIncludeHiddenFields)
Compute the bounding box used to size a symbol SVG plot.
@ PAGE_SIZE_AUTO
Definition sch_plotter.h:47
@ PAGE_SIZE_A
Definition sch_plotter.h:49
@ PAGE_SIZE_A4
Definition sch_plotter.h:48
Definition of the SCH_SHEET_PATH and SCH_SHEET_LIST classes for Eeschema.
@ SYMBOL_FILTER_NON_POWER
@ GLOBAL_CLEANUP
Definition schematic.h:101
SCRATCH_DOC< DOC > LoadScratchDoc(SETTINGS_MANAGER &aMgr, const wxString &aDocPath, Loader aLoader, ClearFn aClearFn)
Construct a SCRATCH_DOC by loading a project non-active and then handing it to the caller's document ...
COLOR_SETTINGS * GetColorSettings(const wxString &aName)
T * GetAppSettings(const char *aFilename)
std::vector< FAB_LAYER_COLOR > dummy
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
wxString label
wxString name
wxString fieldDelimiter
bool includeByteOrderMark
static std::vector< BOM_FMT_PRESET > BuiltInPresets()
wxString stringDelimiter
wxString refRangeDelimiter
wxString refDelimiter
Phase 8 context for the conflict canvas.
wxString formatNotice
Shown with the instructions when the merge cannot keep a side's file format.
std::function< void(WIDGET_DIFF_CANVAS &, SIDE, const std::optional< KIID_PATH > &)> drawSide
Draw a side on the canvas with the editor's own painter.
std::function< wxString(const KIID_PATH &)> describeItem
Name an item the way the editor would, so a conflict can be told from its neighbours.
An older KiCad release we can export a project back to.
int m_schVersion
SEXPR_SCHEMATIC_FILE_VERSION for the target.
int m_symLibVersion
SEXPR_SYMBOL_LIB_FILE_VERSION for the target.
wxString m_name
User-facing name, e.g. "KiCad 10.0".
std::vector< BOM_PRESET > m_BomPresets
std::vector< BOM_FMT_PRESET > m_BomFmtPresets
Import provenance, held only for the lifetime of the importing SCHEMATIC.
Diff colors with defaults for light backgrounds.
Definition diff_scene.h:278
KIGFX::COLOR4D reference
Default color for source-document context geometry.
Definition diff_scene.h:292
Describes how a computed DOCUMENT_DIFF should be emitted by a diff job.
std::function< DOCUMENT_GEOMETRY(const KIGFX::COLOR4D &)> comparisonGeometry
DOC_KIND docKind
Source document type, propagated onto the scene so the PNG/SVG renderer sizes its viewport with the m...
std::function< DOCUMENT_GEOMETRY(const KIGFX::COLOR4D &)> referenceGeometry
The full set of changes between two parsed documents of one type.
Aggregate of background geometry extracted from one source document.
Definition diff_scene.h:163
One change record on a single item.
std::optional< wxString > refdes
Result of planning a 3-way merge.
std::size_t ConflictCount() const
std::vector< KIID_PATH > unresolved
bool projectFileTouched
True iff the applier resolved state that lives in the .kicad_pro.
std::size_t sheetActionsSkipped
Number of actions skipped because they targeted a SCH_SHEET.
VALIDATION_REPORT validation
Post-apply validator pipeline result.
Outcome of a single validator run.
std::vector< VALIDATION_FAILURE > failures
SCRATCH_DOC< SCHEMATIC > emptyA
KICAD_DIFF::DOCUMENT_DIFF diff
SCRATCH_DOC< SCHEMATIC > b
SCRATCH_DOC< SCHEMATIC > a
SCRATCH_DOC< SCHEMATIC > emptyB
std::vector< wxString > m_plotPages
Definition sch_plotter.h:57
wxString m_theme
Definition sch_plotter.h:69
DXF_UNITS m_DXF_File_Unit
Definition sch_plotter.h:76
bool m_PDFPropertyPopups
Definition sch_plotter.h:66
wxString m_outputDirectory
Definition sch_plotter.h:71
std::optional< SCH_SHEET_PATH > m_sheetPath
Definition sch_plotter.h:60
bool m_pngAntialias
Definition sch_plotter.h:79
wxString m_outputFile
Definition sch_plotter.h:72
bool m_blackAndWhite
Definition sch_plotter.h:63
wxString m_variant
Definition sch_plotter.h:73
bool m_PDFHierarchicalLinks
Definition sch_plotter.h:67
bool m_useBackgroundColor
Definition sch_plotter.h:65
bool m_plotDrawingSheet
Definition sch_plotter.h:56
Move-only RAII wrapper for "load a KiCad document into a non-active scratch PROJECT and clean up afte...
PROJECT * project
std::unique_ptr< DOC > doc
Hold a name of a symbol's field, field value, and default visibility.
Information about a top-level schematic sheet.
SYMBOL_IMPORT_RECONCILE_RESULT ReconcileImportedSymbols(SCH_IO &aPlugin, SCHEMATIC &aSchematic, PROJECT &aProject, const wxString &aSchematicPath, const std::map< std::string, UTF8 > *aProperties, REPORTER &aReporter)
Reconcile aSchematic against the definitions aPlugin retained while loading it.
std::map< wxString, LIB_SYMBOL *, LibSymbolMapSort > LIB_SYMBOL_MAP
Symbol library map sorted by the symbol name.
wxString GetDefaultFieldName(FIELD_T aFieldId, TRANSLATION aTranslation)
Return a default symbol field name for a mandatory field type.
#define MANDATORY_FIELDS
FIELD_T
The set of all field indices assuming an array like sequence that a SCH_COMPONENT or LIB_PART can hol...
@ UNTRANSLATED
@ TRANSLATED
struct DROP_TABLE cs
nanodbc::result res
std::string path
wxString result
Test unit parsing edge cases and error handling.
@ SCH_SYMBOL_T
Definition typeinfo.h:168
@ SCH_SHEET_T
Definition typeinfo.h:171
Definition of file extensions used in Kicad.