KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pcbnew_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
21#include <import_net_names.h>
23#include <richio.h>
24#include <string_utils.h>
25#include <wx/crt.h>
26#include <wx/dir.h>
27#include <wx/zipstrm.h>
28#include <wx/filename.h>
29#include <wx/tokenzr.h>
30#include <wx/wfstream.h>
31
32#include <nlohmann/json.hpp>
33
34#include "pcbnew_jobs_handler.h"
35#include <board_loader.h>
36#include <jobs/scratch_doc.h>
37#include <board_commit.h>
44#include <trace_helpers.h>
46#include <pcb_drill_chart.h>
47#include <drc/drc_engine.h>
49#include <drc/drc_item.h>
50#include <drc/drc_report.h>
53#include <footprint.h>
55#include <jobs/job_export_bom.h>
57#include <jobs/job_fp_upgrade.h>
77#include <jobs/job_pcb_render.h>
78#include <jobs/job_pcb_drc.h>
79#include <jobs/job_pcb_import.h>
85#include <downgrade_scan.h>
86#include <downgrade_copy.h>
87#include <eda_units.h>
89#include <lset.h>
90#include <cli/exit_codes.h>
96#include <tool/tool_manager.h>
97#include <tools/drc_tool.h>
98#include <filename_resolver.h>
103#include <kiface_base.h>
104#include <macros.h>
105#include <pad.h>
106#include <pcb_marker.h>
107#include <project/project_file.h>
108#include <exporters/export_idf.h>
111#include <kiface_services.h>
114#include <pcbnew_settings.h>
115#include <pcbplot.h>
116#include <pcb_plotter.h>
117#include <pcb_edit_frame.h>
118#include <pcb_track.h>
119#include <pgm_base.h>
122#include <project_pcb.h>
125#include <reporter.h>
126#include <scoped_set_reset.h>
127#include <progress_reporter.h>
129#include <export_vrml.h>
130#include <kiplatform/io.h>
141#include <dialogs/dialog_plot.h>
149#include <api/api_pcb_utils.h>
150#include <api/board/board.pb.h>
151#include <google/protobuf/util/json_util.h>
152#include <fstream>
153#include <paths.h>
154#include <streamwrapper.h>
155
158
159#include <locale_io.h>
160#include <confirm.h>
161
162
163#ifdef _WIN32
164#ifdef TRANSPARENT
165#undef TRANSPARENT
166#endif
167#endif
168
169
171 JOB_DISPATCHER( aKiway ),
172 m_cliBoard( nullptr ),
173 m_toolManager( nullptr )
174{
175 Register( "bom", std::bind( &PCBNEW_JOBS_HANDLER::JobExportBom, this, std::placeholders::_1 ),
176 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
177 {
178 JOB_EXPORT_BOM* bomJob = dynamic_cast<JOB_EXPORT_BOM*>( job );
179
180 PCB_EDIT_FRAME* editFrame = static_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
181
182 wxCHECK( bomJob && editFrame, false );
183
184 DIALOG_FOOTPRINT_FIELDS_TABLE dlg( editFrame, bomJob );
185
186 if( dlg.WasAborted() )
187 return false;
188
189 return dlg.ShowModal() == wxID_OK;
190 } );
191 Register( "3d", std::bind( &PCBNEW_JOBS_HANDLER::JobExportStep, this, std::placeholders::_1 ),
192 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
193 {
194 JOB_EXPORT_PCB_3D* svgJob = dynamic_cast<JOB_EXPORT_PCB_3D*>( job );
195
196 PCB_EDIT_FRAME* editFrame =
197 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
198
199 wxCHECK( svgJob && editFrame, false );
200
201 DIALOG_EXPORT_STEP dlg( editFrame, aParent, "", svgJob );
202 return dlg.ShowModal() == wxID_OK;
203 } );
204 Register( "render", std::bind( &PCBNEW_JOBS_HANDLER::JobExportRender, this, std::placeholders::_1 ),
205 []( JOB* job, wxWindow* aParent ) -> bool
206 {
207 JOB_PCB_RENDER* renderJob = dynamic_cast<JOB_PCB_RENDER*>( job );
208
209 wxCHECK( renderJob, false );
210
211 DIALOG_RENDER_JOB dlg( aParent, renderJob );
212 return dlg.ShowModal() == wxID_OK;
213 } );
214 Register( "upgrade", std::bind( &PCBNEW_JOBS_HANDLER::JobUpgrade, this, std::placeholders::_1 ),
215 []( JOB* job, wxWindow* aParent ) -> bool
216 {
217 return true;
218 } );
219 Register( "downgrade", std::bind( &PCBNEW_JOBS_HANDLER::JobDowngrade, this, std::placeholders::_1 ),
220 []( JOB* job, wxWindow* aParent ) -> bool
221 {
222 return true;
223 } );
224 Register( "pcb_import", std::bind( &PCBNEW_JOBS_HANDLER::JobImport, this, std::placeholders::_1 ),
225 []( JOB* job, wxWindow* aParent ) -> bool
226 {
227 return true;
228 } );
229 Register( "svg", std::bind( &PCBNEW_JOBS_HANDLER::JobExportSvg, this, std::placeholders::_1 ),
230 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
231 {
232 JOB_EXPORT_PCB_SVG* svgJob = dynamic_cast<JOB_EXPORT_PCB_SVG*>( job );
233
234 PCB_EDIT_FRAME* editFrame =
235 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
236
237 wxCHECK( svgJob && editFrame, false );
238
239 DIALOG_PLOT dlg( editFrame, aParent, svgJob );
240 return dlg.ShowModal() == wxID_OK;
241 } );
242 Register( "gencad", std::bind( &PCBNEW_JOBS_HANDLER::JobExportGencad, this, std::placeholders::_1 ),
243 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
244 {
245 JOB_EXPORT_PCB_GENCAD* gencadJob = dynamic_cast<JOB_EXPORT_PCB_GENCAD*>( job );
246
247 PCB_EDIT_FRAME* editFrame =
248 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
249
250 wxCHECK( gencadJob && editFrame, false );
251
252 DIALOG_GENCAD_EXPORT_OPTIONS dlg( editFrame, gencadJob->GetSettingsDialogTitle(), gencadJob );
253 return dlg.ShowModal() == wxID_OK;
254 } );
255 Register( "specctra_dsn",
256 std::bind( &PCBNEW_JOBS_HANDLER::JobExportSpecctraDsn, this, std::placeholders::_1 ),
257 []( JOB* job, wxWindow* aParent ) -> bool
258 {
259 return true;
260 } );
261 Register( "dxf", std::bind( &PCBNEW_JOBS_HANDLER::JobExportDxf, this, std::placeholders::_1 ),
262 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
263 {
264 JOB_EXPORT_PCB_DXF* dxfJob = dynamic_cast<JOB_EXPORT_PCB_DXF*>( job );
265
266 PCB_EDIT_FRAME* editFrame =
267 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
268
269 wxCHECK( dxfJob && editFrame, false );
270
271 DIALOG_PLOT dlg( editFrame, aParent, dxfJob );
272 return dlg.ShowModal() == wxID_OK;
273 } );
274 Register( "pdf", std::bind( &PCBNEW_JOBS_HANDLER::JobExportPdf, this, std::placeholders::_1 ),
275 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
276 {
277 JOB_EXPORT_PCB_PDF* pdfJob = dynamic_cast<JOB_EXPORT_PCB_PDF*>( job );
278
279 PCB_EDIT_FRAME* editFrame =
280 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
281
282 wxCHECK( pdfJob && editFrame, false );
283
284 DIALOG_PLOT dlg( editFrame, aParent, pdfJob );
285 return dlg.ShowModal() == wxID_OK;
286 } );
287 Register( "png", std::bind( &PCBNEW_JOBS_HANDLER::JobExportPng, this, std::placeholders::_1 ),
288 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
289 {
290 JOB_EXPORT_PCB_PNG* pngJob = dynamic_cast<JOB_EXPORT_PCB_PNG*>( job );
291
292 PCB_EDIT_FRAME* editFrame =
293 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
294
295 wxCHECK( pngJob && editFrame, false );
296
297 DIALOG_PLOT dlg( editFrame, aParent, pngJob );
298 return dlg.ShowModal() == wxID_OK;
299 } );
300 Register( "ps", std::bind( &PCBNEW_JOBS_HANDLER::JobExportPs, this, std::placeholders::_1 ),
301 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
302 {
303 JOB_EXPORT_PCB_PS* psJob = dynamic_cast<JOB_EXPORT_PCB_PS*>( job );
304
305 PCB_EDIT_FRAME* editFrame =
306 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
307
308 wxCHECK( psJob && editFrame, false );
309
310 DIALOG_PLOT dlg( editFrame, aParent, psJob );
311 return dlg.ShowModal() == wxID_OK;
312 } );
313 Register( "stats", std::bind( &PCBNEW_JOBS_HANDLER::JobExportStats, this, std::placeholders::_1 ),
314 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
315 {
316 JOB_EXPORT_PCB_STATS* statsJob = dynamic_cast<JOB_EXPORT_PCB_STATS*>( job );
317
318 PCB_EDIT_FRAME* editFrame =
319 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
320
321 wxCHECK( statsJob && editFrame, false );
322
323 if( statsJob->m_filename.IsEmpty() && editFrame->GetBoard() )
324 {
325 wxFileName boardName = editFrame->GetBoard()->GetFileName();
326 statsJob->m_filename = boardName.GetFullPath();
327 }
328
329 wxWindow* parent = aParent ? aParent : static_cast<wxWindow*>( editFrame );
330
331 DIALOG_BOARD_STATS_JOB dlg( parent, statsJob );
332
333 return dlg.ShowModal() == wxID_OK;
334 } );
335 Register( "stackup", std::bind( &PCBNEW_JOBS_HANDLER::JobExportStackup, this, std::placeholders::_1 ),
336 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
337 {
338 JOB_EXPORT_PCB_STACKUP* stackupJob = dynamic_cast<JOB_EXPORT_PCB_STACKUP*>( job );
339
340 PCB_EDIT_FRAME* editFrame =
341 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
342
343 wxCHECK( stackupJob && editFrame, false );
344
345 if( stackupJob->m_filename.IsEmpty() && editFrame->GetBoard() )
346 {
347 wxFileName boardName = editFrame->GetBoard()->GetFileName();
348 stackupJob->m_filename = boardName.GetFullPath();
349 }
350
351 wxWindow* parent = aParent ? aParent : static_cast<wxWindow*>( editFrame );
352
353 DIALOG_BOARD_STACKUP_JOB dlg( parent, stackupJob );
354
355 return dlg.ShowModal() == wxID_OK;
356 } );
357 Register( "gerber", std::bind( &PCBNEW_JOBS_HANDLER::JobExportGerber, this, std::placeholders::_1 ),
358 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
359 {
360 JOB_EXPORT_PCB_GERBER* gJob = dynamic_cast<JOB_EXPORT_PCB_GERBER*>( job );
361
362 PCB_EDIT_FRAME* editFrame =
363 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
364
365 wxCHECK( gJob && editFrame, false );
366
367 DIALOG_PLOT dlg( editFrame, aParent, gJob );
368 return dlg.ShowModal() == wxID_OK;
369 } );
370 Register( "gerbers", std::bind( &PCBNEW_JOBS_HANDLER::JobExportGerbers, this, std::placeholders::_1 ),
371 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
372 {
373 JOB_EXPORT_PCB_GERBERS* gJob = dynamic_cast<JOB_EXPORT_PCB_GERBERS*>( job );
374
375 PCB_EDIT_FRAME* editFrame =
376 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
377
378 wxCHECK( gJob && editFrame, false );
379
380 DIALOG_PLOT dlg( editFrame, aParent, gJob );
381 return dlg.ShowModal() == wxID_OK;
382 } );
383 Register(
384 "hpgl",
385 [&]( JOB* aJob )
386 {
387 m_reporter->Report( _( "Plotting to HPGL is no longer supported as of KiCad 10.0.\n" ),
390 },
391 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
392 {
393 PCB_EDIT_FRAME* editFrame = dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
394
395 wxCHECK( editFrame, false );
396
397 DisplayErrorMessage( editFrame, _( "Plotting to HPGL is no longer supported as of KiCad 10.0." ) );
398 return false;
399 } );
400 Register( "drill", std::bind( &PCBNEW_JOBS_HANDLER::JobExportDrill, this, std::placeholders::_1 ),
401 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
402 {
403 JOB_EXPORT_PCB_DRILL* drillJob = dynamic_cast<JOB_EXPORT_PCB_DRILL*>( job );
404
405 PCB_EDIT_FRAME* editFrame =
406 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
407
408 wxCHECK( drillJob && editFrame, false );
409
410 DIALOG_GENDRILL dlg( editFrame, drillJob, aParent );
411 return dlg.ShowModal() == wxID_OK;
412 } );
413 Register( "pos", std::bind( &PCBNEW_JOBS_HANDLER::JobExportPos, this, std::placeholders::_1 ),
414 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
415 {
416 JOB_EXPORT_PCB_POS* posJob = dynamic_cast<JOB_EXPORT_PCB_POS*>( job );
417
418 PCB_EDIT_FRAME* editFrame =
419 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
420
421 wxCHECK( posJob && editFrame, false );
422
423 DIALOG_GEN_FOOTPRINT_POSITION dlg( posJob, editFrame, aParent );
424 return dlg.ShowModal() == wxID_OK;
425 } );
426 Register( "fpupgrade", std::bind( &PCBNEW_JOBS_HANDLER::JobExportFpUpgrade, this, std::placeholders::_1 ),
427 []( JOB* job, wxWindow* aParent ) -> bool
428 {
429 return true;
430 } );
431 Register( "fpdowngrade", std::bind( &PCBNEW_JOBS_HANDLER::JobFpDowngrade, this, std::placeholders::_1 ),
432 []( JOB* job, wxWindow* aParent ) -> bool
433 {
434 return true;
435 } );
436 Register( "fpsvg", std::bind( &PCBNEW_JOBS_HANDLER::JobExportFpSvg, this, std::placeholders::_1 ),
437 []( JOB* job, wxWindow* aParent ) -> bool
438 {
439 return true;
440 } );
441 Register( "pcb_diff", std::bind( &PCBNEW_JOBS_HANDLER::JobDiff, this, std::placeholders::_1 ),
442 []( JOB* job, wxWindow* aParent ) -> bool
443 {
444 return true;
445 } );
446 Register( "fp_diff", std::bind( &PCBNEW_JOBS_HANDLER::JobFpDiff, this, std::placeholders::_1 ),
447 []( JOB* job, wxWindow* aParent ) -> bool
448 {
449 return true;
450 } );
451 Register( "drc", std::bind( &PCBNEW_JOBS_HANDLER::JobExportDrc, this, std::placeholders::_1 ),
452 []( JOB* job, wxWindow* aParent ) -> bool
453 {
454 JOB_PCB_DRC* drcJob = dynamic_cast<JOB_PCB_DRC*>( job );
455
456 wxCHECK( drcJob, false );
457
458 DIALOG_DRC_JOB_CONFIG dlg( aParent, drcJob );
459 return dlg.ShowModal() == wxID_OK;
460 } );
461 Register( "ipc2581", std::bind( &PCBNEW_JOBS_HANDLER::JobExportIpc2581, this, std::placeholders::_1 ),
462 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
463 {
464 JOB_EXPORT_PCB_IPC2581* ipcJob = dynamic_cast<JOB_EXPORT_PCB_IPC2581*>( job );
465
466 PCB_EDIT_FRAME* editFrame =
467 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
468
469 wxCHECK( ipcJob && editFrame, false );
470
471 DIALOG_EXPORT_2581 dlg( ipcJob, editFrame, aParent );
472 return dlg.ShowModal() == wxID_OK;
473 } );
474 Register( "ipcd356", std::bind( &PCBNEW_JOBS_HANDLER::JobExportIpcD356, this, std::placeholders::_1 ),
475 []( JOB* job, wxWindow* aParent ) -> bool
476 {
477 return true;
478 } );
479 Register( "odb", std::bind( &PCBNEW_JOBS_HANDLER::JobExportOdb, this, std::placeholders::_1 ),
480 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
481 {
482 JOB_EXPORT_PCB_ODB* odbJob = dynamic_cast<JOB_EXPORT_PCB_ODB*>( job );
483
484 PCB_EDIT_FRAME* editFrame =
485 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
486
487 wxCHECK( odbJob && editFrame, false );
488
489 DIALOG_EXPORT_ODBPP dlg( odbJob, editFrame, aParent );
490 return dlg.ShowModal() == wxID_OK;
491 } );
492 Register( "idf", std::bind( &PCBNEW_JOBS_HANDLER::JobExportIdf, this, std::placeholders::_1 ),
493 [aKiway]( JOB* job, wxWindow* aParent ) -> bool
494 {
495 JOB_EXPORT_PCB_IDF* idfJob = dynamic_cast<JOB_EXPORT_PCB_IDF*>( job );
496
497 PCB_EDIT_FRAME* editFrame =
498 dynamic_cast<PCB_EDIT_FRAME*>( aKiway->Player( FRAME_PCB_EDITOR, false ) );
499
500 wxCHECK( idfJob && editFrame, false );
501
502 DIALOG_EXPORT_IDF3 dlg( idfJob, editFrame, aParent );
503 return dlg.ShowModal() == wxID_OK;
504 } );
505}
506
507
511
512
514{
515 m_cliBoard.reset();
516 m_toolManager.reset();
517}
518
519
521{
522 TOOL_MANAGER* toolManager = nullptr;
523 if( Pgm().IsGUI() )
524 {
525 // we assume the PCB we are working on here is the one in the frame
526 // so use the frame's tool manager
527 PCB_EDIT_FRAME* editFrame = (PCB_EDIT_FRAME*) m_kiway->Player( FRAME_PCB_EDITOR, false );
528 if( editFrame )
529 toolManager = editFrame->GetToolManager();
530 }
531 else
532 {
533 if( m_toolManager == nullptr )
534 {
535 m_toolManager = std::make_unique<TOOL_MANAGER>();
536 }
537
538 toolManager = m_toolManager.get();
539
540 toolManager->SetEnvironment( aBrd, nullptr, nullptr, Kiface().KifaceSettings(), nullptr );
541 }
542 return toolManager;
543}
544
545
546BOARD* PCBNEW_JOBS_HANDLER::getBoard( const wxString& aPath )
547{
548 BOARD* brd = nullptr;
549 SETTINGS_MANAGER& settingsManager = Pgm().GetSettingsManager();
550 wxString loadError;
551
552 auto getProjectForBoard = [&]( const wxString& aBoardPath ) -> PROJECT*
553 {
554 wxFileName pro = aBoardPath;
555 pro.SetExt( FILEEXT::ProjectFileExtension );
556 pro.MakeAbsolute();
557
558 PROJECT* project = settingsManager.GetProject( pro.GetFullPath() );
559
560 if( !project )
561 {
562 settingsManager.LoadProject( pro.GetFullPath(), true );
563 project = settingsManager.GetProject( pro.GetFullPath() );
564 }
565
566 return project;
567 };
568
569 auto loadBoardFromPath = [&]( const wxString& aBoardPath ) -> BOARD*
570 {
571 PROJECT* project = getProjectForBoard( aBoardPath );
572
574
575 if( !project || pluginType == PCB_IO_MGR::FILE_TYPE_NONE )
576 return nullptr;
577
578 try
579 {
580 std::unique_ptr<BOARD> loadedBoard = BOARD_LOADER::Load( aBoardPath, pluginType, project );
581 return loadedBoard.release();
582 }
583 catch( const IO_ERROR& ioe )
584 {
585 loadError = ioe.What();
586 return nullptr;
587 }
588 catch( ... )
589 {
590 return nullptr;
591 }
592 };
593
594 if( !Pgm().IsGUI() && Pgm().GetSettingsManager().IsProjectOpen() )
595 {
596 wxString pcbPath = aPath;
597
598 if( pcbPath.IsEmpty() )
599 {
600 wxFileName path = Pgm().GetSettingsManager().Prj().GetProjectFullName();
602 path.MakeAbsolute();
603 pcbPath = path.GetFullPath();
604 }
605
606 if( !m_cliBoard )
607 m_cliBoard.reset( loadBoardFromPath( pcbPath ) );
608
609 brd = m_cliBoard.get();
610 }
611 else if( Pgm().IsGUI() && Pgm().GetSettingsManager().IsProjectOpen() )
612 {
613 PCB_EDIT_FRAME* editFrame = (PCB_EDIT_FRAME*) m_kiway->Player( FRAME_PCB_EDITOR, false );
614
615 if( editFrame )
616 brd = editFrame->GetBoard();
617 }
618 else
619 {
620 m_cliBoard.reset( loadBoardFromPath( aPath ) );
621 brd = m_cliBoard.get();
622 }
623
624 if( !brd )
625 {
626 wxString msg = _( "Failed to load board" );
627
628 if( !loadError.IsEmpty() )
629 msg += wxString::Format( wxS( ": %s" ), loadError );
630
631 m_reporter->Report( msg + '\n', RPT_SEVERITY_ERROR );
632 }
633
634 return brd;
635}
636
637
638LSEQ PCBNEW_JOBS_HANDLER::convertLayerArg( wxString& aLayerString, BOARD* aBoard ) const
639{
640 std::map<wxString, LSET> layerUserMasks;
641 std::map<wxString, LSET> layerMasks;
642 std::map<wxString, LSET> layerGuiMasks;
643
644 // Build list of layer names and their layer mask:
645 for( PCB_LAYER_ID layer : LSET::AllLayersMask() )
646 {
647 // Add user layer name
648 if( aBoard )
649 layerUserMasks[aBoard->GetLayerName( layer )] = LSET( { layer } );
650
651 // Add layer name used in pcb files
652 layerMasks[LSET::Name( layer )] = LSET( { layer } );
653 // Add layer name using GUI canonical layer name
654 layerGuiMasks[LayerName( layer )] = LSET( { layer } );
655 }
656
657 // Add list of grouped layer names used in pcb files
658 layerMasks[wxT( "*" )] = LSET::AllLayersMask();
659 layerMasks[wxT( "*.Cu" )] = LSET::AllCuMask();
660 layerMasks[wxT( "*In.Cu" )] = LSET::InternalCuMask();
661 layerMasks[wxT( "F&B.Cu" )] = LSET( { F_Cu, B_Cu } );
662 layerMasks[wxT( "*.Adhes" )] = LSET( { B_Adhes, F_Adhes } );
663 layerMasks[wxT( "*.Paste" )] = LSET( { B_Paste, F_Paste } );
664 layerMasks[wxT( "*.Mask" )] = LSET( { B_Mask, F_Mask } );
665 layerMasks[wxT( "*.SilkS" )] = LSET( { B_SilkS, F_SilkS } );
666 layerMasks[wxT( "*.Fab" )] = LSET( { B_Fab, F_Fab } );
667 layerMasks[wxT( "*.CrtYd" )] = LSET( { B_CrtYd, F_CrtYd } );
668
669 // Add list of grouped layer names using GUI canonical layer names
670 layerGuiMasks[wxT( "*.Adhesive" )] = LSET( { B_Adhes, F_Adhes } );
671 layerGuiMasks[wxT( "*.Silkscreen" )] = LSET( { B_SilkS, F_SilkS } );
672 layerGuiMasks[wxT( "*.Courtyard" )] = LSET( { B_CrtYd, F_CrtYd } );
673
674 LSEQ layerMask;
675
676 auto pushLayers = [&]( const LSET& layerSet )
677 {
678 for( PCB_LAYER_ID layer : layerSet.Seq() )
679 layerMask.push_back( layer );
680 };
681
682 if( !aLayerString.IsEmpty() )
683 {
684 wxStringTokenizer layerTokens( aLayerString, "," );
685
686 while( layerTokens.HasMoreTokens() )
687 {
688 std::string token = TO_UTF8( layerTokens.GetNextToken().Trim( true ).Trim( false ) );
689
690 if( layerUserMasks.contains( token ) )
691 pushLayers( layerUserMasks.at( token ) );
692 else if( layerMasks.count( token ) )
693 pushLayers( layerMasks.at( token ) );
694 else if( layerGuiMasks.count( token ) )
695 pushLayers( layerGuiMasks.at( token ) );
696 else
697 m_reporter->Report( wxString::Format( _( "Invalid layer name '%s'\n" ), token ) );
698 }
699 }
700
701 return layerMask;
702}
703
704
706{
707 JOB_EXPORT_BOM* aBomJob = dynamic_cast<JOB_EXPORT_BOM*>( aJob );
708
709 wxCHECK( aBomJob, CLI::EXIT_CODES::ERR_UNKNOWN );
710
711 BOARD* board = getBoard( aBomJob->m_filename );
712
713 if( !board )
715
716 aJob->SetTitleBlock( board->GetTitleBlock() );
717 board->GetProject()->ApplyTextVars( aJob->GetVarOverrides() );
718
719 wxString currentVariant = aBomJob->GetSelectedVariant();
720
721 if( !currentVariant.IsEmpty() && currentVariant != wxS( "all" ) )
722 board->SetCurrentVariant( currentVariant );
723
724 FOOTPRINT_REFERENCE_LIST referenceList;
725
726 // Annotation warning check (and gather footprints for data model)
727 bool hasWarned = false;
728 for( FOOTPRINT* fp : board->Footprints() )
729 {
730 referenceList.push_back( FOOTPRINT_REF( *fp ) );
731
732 if( !fp->IsAnnotated() && !hasWarned )
733 {
734 m_reporter->Report( _( "Warning: board has unannotated footprints, please use the PCB "
735 "editor to annotate them\n" ),
737 hasWarned = true;
738 }
739 }
740
741 // Build our data model
742 FOOTPRINT_FIELDS_EDITOR_GRID_DATA_MODEL dataModel( referenceList );
743 dataModel.SetCurrentVariant( currentVariant );
744
745 // Mandatory fields first
746 for( FIELD_T fieldId : MANDATORY_FIELDS )
747 dataModel.AddColumn( GetDefaultFieldName( fieldId, UNTRANSLATED ),
748 GetDefaultFieldName( fieldId, TRANSLATED ), false );
749
750 // Generated/virtual fields (e.g. ${QUANTITY}, ${ITEM_NUMBER}) present only in the fields table
753 false );
756 false );
757
758 // Attribute fields (boolean flags on footprints)
759 dataModel.AddColumn( wxS( "${DNP}" ), GetGeneratedFieldDisplayName( wxS( "${DNP}" ) ), false );
760 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_BOM}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_BOM}" ) ),
761 false );
762 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_BOARD}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_BOARD}" ) ),
763 false );
764 dataModel.AddColumn( wxS( "${EXCLUDE_FROM_SIM}" ), GetGeneratedFieldDisplayName( wxS( "${EXCLUDE_FROM_SIM}" ) ),
765 false );
766
767 // User field names in footprints second
768 std::set<wxString> userFieldNames;
769
770 for( size_t i = 0; i < referenceList.size(); ++i )
771 {
772 FOOTPRINT& footprint = referenceList[i].GetFootprint();
773
774 for( PCB_FIELD* field : footprint.GetFields() )
775 {
776 if( !field->IsMandatory() && !field->IsPrivate() )
777 userFieldNames.insert( field->GetName() );
778 }
779 }
780
781 for( const wxString& fieldName : userFieldNames )
782 dataModel.AddColumn( fieldName, GetGeneratedFieldDisplayName( fieldName ), true );
783
784 // Add any templateFieldNames which aren't already present in the userFieldNames
785 // TODO: template field names not implemented in board editor
786
787 BOM_PRESET preset;
788
789 // Load a preset if one is specified
790 if( !aBomJob->m_bomPresetName.IsEmpty() )
791 {
792 // Find the preset
793 std::optional<BOM_PRESET> boardPreset;
794
795 for( const BOM_PRESET& p : BOM_PRESET::BuiltInPresets() )
796 {
797 if( p.name == aBomJob->m_bomPresetName )
798 {
799 boardPreset = p;
800 break;
801 }
802 }
803
804 for( const BOM_PRESET& p : board->GetDesignSettings().m_BomPresets )
805 {
806 if( p.name == aBomJob->m_bomPresetName )
807 {
808 boardPreset = p;
809 break;
810 }
811 }
812
813 if( !boardPreset )
814 {
815 m_reporter->Report(
816 wxString::Format( _( "BOM preset '%s' not found" ) + wxS( "\n" ), aBomJob->m_bomPresetName ),
818
820 }
821
822 preset = *boardPreset;
823 }
824 else
825 {
826 // Normalize field names so that bare generated-field tokens (e.g. "QUANTITY") are
827 // accepted alongside the canonical "${QUANTITY}" form. Shell expansion of ${VAR}
828 // inside double quotes silently produces an empty string, so this also guards against
829 // that common CLI pitfall.
830 auto normalizeFieldName = [&dataModel]( const wxString& aName ) -> wxString
831 {
832 if( aName.IsEmpty() )
833 return wxEmptyString;
834
835 if( IsGeneratedField( aName ) )
836 return aName;
837
838 wxString wrapped = wxS( "${" ) + aName + wxS( "}" );
839
840 if( IsGeneratedField( wrapped ) && dataModel.GetFieldNameCol( wrapped ) != -1 )
841 return wrapped;
842
843 return aName;
844 };
845
846 size_t i = 0;
847
848 for( const wxString& rawFieldName : aBomJob->m_fieldsOrdered )
849 {
850 wxString fieldName = normalizeFieldName( rawFieldName );
851
852 if( fieldName.IsEmpty() )
853 {
854 i++;
855 continue;
856 }
857
858 // Handle wildcard. We allow the wildcard anywhere in the list, but it needs to respect
859 // fields that come before and after the wildcard.
860 if( fieldName == wxS( "*" ) )
861 {
862 for( const BOM_FIELD& modelField : dataModel.GetFieldsOrdered() )
863 {
864 struct BOM_FIELD field;
865
866 field.name = modelField.name;
867 field.show = true;
868 field.groupBy = false;
869 field.label = field.name;
870
871 bool fieldAlreadyPresent = false;
872
873 for( BOM_FIELD& presetField : preset.fieldsOrdered )
874 {
875 if( presetField.name == field.name )
876 {
877 fieldAlreadyPresent = true;
878 break;
879 }
880 }
881
882 bool fieldLaterInList = false;
883
884 for( const wxString& fieldInList : aBomJob->m_fieldsOrdered )
885 {
886 if( normalizeFieldName( fieldInList ) == field.name )
887 {
888 fieldLaterInList = true;
889 break;
890 }
891 }
892
893 if( !fieldAlreadyPresent && !fieldLaterInList )
894 preset.fieldsOrdered.emplace_back( field );
895 }
896
897 continue;
898 }
899
900 struct BOM_FIELD field;
901
902 field.name = fieldName;
903 field.show = !fieldName.StartsWith( wxT( "__" ), &field.name );
904 field.name = normalizeFieldName( field.name );
905
906 if( ( aBomJob->m_fieldsLabels.size() > i ) && !aBomJob->m_fieldsLabels[i].IsEmpty() )
907 field.label = aBomJob->m_fieldsLabels[i];
908 else if( IsGeneratedField( field.name ) )
909 field.label = GetGeneratedFieldDisplayName( field.name );
910 else
911 field.label = field.name;
912
913 preset.fieldsOrdered.emplace_back( field );
914 i++;
915 }
916
917 for( const wxString& rawFieldName : aBomJob->m_fieldsGroupBy )
918 {
919 wxString fieldName = rawFieldName;
920 fieldName.StartsWith( wxT( "__" ), &fieldName );
921 fieldName = normalizeFieldName( fieldName );
922
923 if( fieldName.IsEmpty() )
924 continue;
925
926 bool fieldAlreadyPresent = false;
927
928 for( BOM_FIELD& field : preset.fieldsOrdered )
929 {
930 if( field.name == fieldName )
931 {
932 field.groupBy = true;
933 fieldAlreadyPresent = true;
934 break;
935 }
936 }
937
938 if( !fieldAlreadyPresent )
939 preset.fieldsOrdered.push_back( { fieldName, GetGeneratedFieldDisplayName( fieldName ), false, true } );
940 }
941
942 preset.sortAsc = aBomJob->m_sortAsc;
943 preset.sortField = normalizeFieldName( aBomJob->m_sortField );
944 preset.filterString = aBomJob->m_filterString;
945 preset.filterScope = aBomJob->m_filterScope;
946 preset.groupSymbols = aBomJob->m_groupSymbols;
947 preset.excludeDNP = aBomJob->m_excludeDNP;
948 }
949
950 BOM_FMT_PRESET fmt;
951
952 // Load a format preset if one is specified
953 if( !aBomJob->m_bomFmtPresetName.IsEmpty() )
954 {
955 std::optional<BOM_FMT_PRESET> boardFmtPreset;
956
958 {
959 if( p.name == aBomJob->m_bomFmtPresetName )
960 {
961 boardFmtPreset = p;
962 break;
963 }
964 }
965
966 for( const BOM_FMT_PRESET& p : board->GetDesignSettings().m_BomFmtPresets )
967 {
968 if( p.name == aBomJob->m_bomFmtPresetName )
969 {
970 boardFmtPreset = p;
971 break;
972 }
973 }
974
975 if( !boardFmtPreset )
976 {
977 m_reporter->Report( wxString::Format( _( "BOM format preset '%s' not found" ) + wxS( "\n" ),
978 aBomJob->m_bomFmtPresetName ),
980
982 }
983
984 fmt = *boardFmtPreset;
985 }
986 else
987 {
988 fmt.fieldDelimiter = aBomJob->m_fieldDelimiter;
989 fmt.stringDelimiter = aBomJob->m_stringDelimiter;
990 fmt.refDelimiter = aBomJob->m_refDelimiter;
992 fmt.keepTabs = aBomJob->m_keepTabs;
993 fmt.keepLineBreaks = aBomJob->m_keepLineBreaks;
995 }
996
997 if( aBomJob->GetConfiguredOutputPath().IsEmpty() )
998 {
999 wxFileName fn = board->GetFileName();
1000 fn.SetName( fn.GetName() );
1001 fn.SetExt( FILEEXT::CsvFileExtension );
1002
1003 aBomJob->SetConfiguredOutputPath( fn.GetFullName() );
1004 }
1005
1006 wxString configuredPath = aBomJob->GetConfiguredOutputPath();
1007 bool hasVariantPlaceholder = configuredPath.Contains( wxS( "${VARIANT}" ) );
1008
1009 // Determine which variants to process
1010 std::vector<wxString> variantsToProcess;
1011
1012 if( aBomJob->m_variantNames.size() > 1 && hasVariantPlaceholder )
1013 {
1014 variantsToProcess = aBomJob->m_variantNames;
1015 }
1016 else
1017 {
1018 variantsToProcess.push_back( currentVariant );
1019 }
1020
1021 for( const wxString& variantName : variantsToProcess )
1022 {
1023 std::vector<wxString> singleVariant = { variantName };
1024 dataModel.SetVariantNames( singleVariant );
1025 dataModel.SetCurrentVariant( variantName );
1026 dataModel.UpdateReferences( dataModel.GetReferenceList() );
1027 dataModel.ApplyBomPreset( preset );
1028
1029 wxString outPath;
1030
1031 if( hasVariantPlaceholder )
1032 {
1033 wxString variantPath = ExpandVariantOutputPath( configuredPath, variantName );
1034 aBomJob->SetConfiguredOutputPath( variantPath );
1035 outPath = aBomJob->GetFullOutputPath( board->GetProject() );
1036 aBomJob->SetConfiguredOutputPath( configuredPath );
1037 }
1038 else
1039 {
1040 outPath = aBomJob->GetFullOutputPath( board->GetProject() );
1041 }
1042
1043 if( !PATHS::EnsurePathExists( outPath, true ) )
1044 {
1045 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1047 }
1048
1049 wxFile f;
1050
1051 if( !f.Open( outPath, wxFile::write ) )
1052 {
1053 m_reporter->Report( wxString::Format( _( "Unable to open destination '%s'" ), outPath ),
1055
1057 }
1058
1059 bool res = f.Write( dataModel.Export( fmt ) );
1060
1061 if( !res )
1063
1064 aJob->AddOutput( outPath );
1065
1066 m_reporter->Report( wxString::Format( _( "Wrote bill of materials to '%s'." ), outPath ), RPT_SEVERITY_ACTION );
1067 }
1068
1069 return CLI::EXIT_CODES::OK;
1070}
1071
1072
1074{
1075 JOB_EXPORT_PCB_3D* aStepJob = dynamic_cast<JOB_EXPORT_PCB_3D*>( aJob );
1076
1077 if( aStepJob == nullptr )
1079
1080 BOARD* brd = getBoard( aStepJob->m_filename );
1081
1082 if( !brd )
1084
1085 if( !aStepJob->m_variant.IsEmpty() )
1086 brd->SetCurrentVariant( aStepJob->m_variant );
1087
1088 if( aStepJob->GetConfiguredOutputPath().IsEmpty() )
1089 {
1090 wxFileName fn = brd->GetFileName();
1091 fn.SetName( fn.GetName() );
1092
1093 switch( aStepJob->m_format )
1094 {
1104 default:
1105 m_reporter->Report( _( "Unknown export format" ), RPT_SEVERITY_ERROR );
1106 return CLI::EXIT_CODES::ERR_UNKNOWN; // shouldnt have gotten here
1107 }
1108
1109 aStepJob->SetWorkingOutputPath( fn.GetFullName() );
1110 }
1111
1112 wxString outPath = resolveJobOutputPath( aJob, brd );
1113
1114 if( !PATHS::EnsurePathExists( outPath, true ) )
1115 {
1116 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1118 }
1119
1120 if( aStepJob->m_format == JOB_EXPORT_PCB_3D::FORMAT::VRML )
1121 {
1122 double scale = 0.0;
1123 switch( aStepJob->m_vrmlUnits )
1124 {
1125 case JOB_EXPORT_PCB_3D::VRML_UNITS::MM: scale = 1.0; break;
1126 case JOB_EXPORT_PCB_3D::VRML_UNITS::METERS: scale = 0.001; break;
1127 case JOB_EXPORT_PCB_3D::VRML_UNITS::TENTHS: scale = 10.0 / 25.4; break;
1128 case JOB_EXPORT_PCB_3D::VRML_UNITS::INCH: scale = 1.0 / 25.4; break;
1129 }
1130
1131 EXPORTER_VRML vrmlExporter( brd );
1132 wxString messages;
1133
1134 double originX = pcbIUScale.IUTomm( aStepJob->m_3dparams.m_Origin.x );
1135 double originY = pcbIUScale.IUTomm( aStepJob->m_3dparams.m_Origin.y );
1136
1137 if( !aStepJob->m_hasUserOrigin )
1138 {
1139 BOX2I bbox = brd->ComputeBoundingBox( true, true );
1140 originX = pcbIUScale.IUTomm( bbox.GetCenter().x );
1141 originY = pcbIUScale.IUTomm( bbox.GetCenter().y );
1142 }
1143
1144 bool success = vrmlExporter.ExportVRML_File(
1145 brd->GetProject(), &messages, outPath, scale, aStepJob->m_3dparams.m_IncludeUnspecified,
1146 aStepJob->m_3dparams.m_IncludeDNP, !aStepJob->m_vrmlModelDir.IsEmpty(), aStepJob->m_vrmlRelativePaths,
1147 aStepJob->m_vrmlModelDir, originX, originY );
1148
1149 if( success )
1150 {
1151 m_reporter->Report( wxString::Format( _( "Successfully exported VRML to %s" ), outPath ),
1153 }
1154 else
1155 {
1156 m_reporter->Report( _( "Error exporting VRML" ), RPT_SEVERITY_ERROR );
1158 }
1159 }
1160 else
1161 {
1162 EXPORTER_STEP_PARAMS params = aStepJob->m_3dparams;
1163
1164 switch( aStepJob->m_format )
1165 {
1175 default:
1176 m_reporter->Report( _( "Unknown export format" ), RPT_SEVERITY_ERROR );
1177 return CLI::EXIT_CODES::ERR_UNKNOWN; // shouldnt have gotten here
1178 }
1179
1180 EXPORTER_STEP stepExporter( brd, params, m_reporter );
1181 stepExporter.m_outputFile = aStepJob->GetFullOutputPath( brd->GetProject() );
1182
1183 if( !stepExporter.Export() )
1185 }
1186
1187 return CLI::EXIT_CODES::OK;
1188}
1189
1190
1192{
1193 JOB_PCB_RENDER* aRenderJob = dynamic_cast<JOB_PCB_RENDER*>( aJob );
1194
1195 if( aRenderJob == nullptr )
1197
1198 // Reject width and height being invalid
1199 // Final bit of sanity because this can blow things up
1200 if( aRenderJob->m_width <= 0 || aRenderJob->m_height <= 0 )
1201 {
1202 m_reporter->Report( _( "Invalid image dimensions" ), RPT_SEVERITY_ERROR );
1204 }
1205
1206 BOARD* brd = getBoard( aRenderJob->m_filename );
1207
1208 if( !brd )
1210
1211 if( !aRenderJob->m_variant.IsEmpty() )
1212 brd->SetCurrentVariant( aRenderJob->m_variant );
1213
1214 if( aRenderJob->GetConfiguredOutputPath().IsEmpty() )
1215 {
1216 wxFileName fn = brd->GetFileName();
1217
1218 switch( aRenderJob->m_format )
1219 {
1222 default:
1223 m_reporter->Report( _( "Unknown export format" ), RPT_SEVERITY_ERROR );
1224 return CLI::EXIT_CODES::ERR_UNKNOWN; // shouldnt have gotten here
1225 }
1226
1227 // set the name to board name + "side", its lazy but its hard to generate anything truely unique
1228 // incase someone is doing this in a jobset with multiple jobs, they should be setting the output themselves
1229 // or we do a hash based on all the options
1230 fn.SetName( wxString::Format( "%s-%d", fn.GetName(), static_cast<int>( aRenderJob->m_side ) ) );
1231
1232 aRenderJob->SetWorkingOutputPath( fn.GetFullName() );
1233 }
1234
1235 wxString outPath = resolveJobOutputPath( aJob, brd );
1236
1237 if( !PATHS::EnsurePathExists( outPath, true ) )
1238 {
1239 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1241 }
1242
1243 BOARD_ADAPTER boardAdapter;
1244
1245 boardAdapter.SetBoard( brd );
1246 boardAdapter.m_IsBoardView = false;
1247
1249
1251 {
1252 cfg.m_Render = userCfg->m_Render;
1253 cfg.m_Camera = userCfg->m_Camera;
1254 cfg.m_LayerPresets = userCfg->m_LayerPresets;
1255 }
1256
1257 if( aRenderJob->m_appearancePreset.empty() )
1258 {
1259 // Force display 3D models
1261 cfg.m_Render.show_footprints_dnp = true;
1265 }
1266
1267 if( aRenderJob->m_quality == JOB_PCB_RENDER::QUALITY::BASIC )
1268 {
1269 // Silkscreen is pixelated without antialiasing
1271
1272 cfg.m_Render.raytrace_backfloor = aRenderJob->m_floor;
1273 cfg.m_Render.raytrace_post_processing = aRenderJob->m_floor;
1274
1276 cfg.m_Render.raytrace_reflections = false;
1277 cfg.m_Render.raytrace_shadows = aRenderJob->m_floor;
1278
1279 // Better colors
1281
1282 // Tracks below soldermask are not visible without refractions
1283 cfg.m_Render.raytrace_refractions = true;
1285 }
1286 else if( aRenderJob->m_quality == JOB_PCB_RENDER::QUALITY::HIGH )
1287 {
1289 cfg.m_Render.raytrace_backfloor = true;
1292 cfg.m_Render.raytrace_reflections = true;
1293 cfg.m_Render.raytrace_shadows = true;
1294 cfg.m_Render.raytrace_refractions = true;
1296 }
1297 else if( aRenderJob->m_quality == JOB_PCB_RENDER::QUALITY::JOB_SETTINGS )
1298 {
1300 cfg.m_Render.raytrace_backfloor = aRenderJob->m_floor;
1303 }
1304
1306 aRenderJob->m_lightTopIntensity.z, 1.0 );
1307
1309 COLOR4D( aRenderJob->m_lightBottomIntensity.x, aRenderJob->m_lightBottomIntensity.y,
1310 aRenderJob->m_lightBottomIntensity.z, 1.0 );
1311
1313 COLOR4D( aRenderJob->m_lightCameraIntensity.x, aRenderJob->m_lightCameraIntensity.y,
1314 aRenderJob->m_lightCameraIntensity.z, 1.0 );
1315
1316 COLOR4D lightColor( aRenderJob->m_lightSideIntensity.x, aRenderJob->m_lightSideIntensity.y,
1317 aRenderJob->m_lightSideIntensity.z, 1.0 );
1318
1320 lightColor, lightColor, lightColor, lightColor, lightColor, lightColor, lightColor, lightColor,
1321 };
1322
1323 int sideElevation = aRenderJob->m_lightSideElevation;
1324
1326 sideElevation, sideElevation, sideElevation, sideElevation,
1327 -sideElevation, -sideElevation, -sideElevation, -sideElevation,
1328 };
1329
1331 45, 135, 225, 315, 45, 135, 225, 315,
1332 };
1333
1334 cfg.m_CurrentPreset = aRenderJob->m_appearancePreset;
1336 boardAdapter.m_Cfg = &cfg;
1337
1338 // Apply the preset's layer visibility and colors to the render settings
1339 if( !aRenderJob->m_appearancePreset.empty() )
1340 {
1341 wxString presetName = wxString::FromUTF8( aRenderJob->m_appearancePreset );
1342
1343 if( presetName == FOLLOW_PCB || presetName == FOLLOW_PLOT_SETTINGS )
1344 {
1345 boardAdapter.SetVisibleLayers( boardAdapter.GetVisibleLayers() );
1346 }
1347 else if( LAYER_PRESET_3D* preset = cfg.FindPreset( presetName ) )
1348 {
1349 boardAdapter.SetVisibleLayers( preset->layers );
1350 boardAdapter.SetLayerColors( preset->colors );
1351
1352 if( preset->name.Lower() == _( "legacy colors" ) )
1353 cfg.m_UseStackupColors = false;
1354 }
1355 }
1356
1359 && aRenderJob->m_format == JOB_PCB_RENDER::FORMAT::PNG ) )
1360 {
1361 boardAdapter.m_ColorOverrides[LAYER_3D_BACKGROUND_TOP] = COLOR4D( 1.0, 1.0, 1.0, 0.0 );
1362 boardAdapter.m_ColorOverrides[LAYER_3D_BACKGROUND_BOTTOM] = COLOR4D( 1.0, 1.0, 1.0, 0.0 );
1363 }
1364
1366
1367 static std::map<JOB_PCB_RENDER::SIDE, VIEW3D_TYPE> s_viewCmdMap = {
1374 };
1375
1377
1378 wxSize windowSize( aRenderJob->m_width, aRenderJob->m_height );
1379 TRACK_BALL camera( 2 * RANGE_SCALE_3D );
1380
1381 camera.SetProjection( projection );
1382 camera.SetCurWindowSize( windowSize );
1383
1384 RENDER_3D_RAYTRACE_RAM raytrace( boardAdapter, camera );
1385 raytrace.SetCurWindowSize( windowSize );
1386
1387 std::shared_ptr<REPORTER> reporter( m_reporter, []( REPORTER* ) {} );
1388 raytrace.SetReporters( reporter, reporter );
1389
1390 for( bool first = true; raytrace.Redraw( false ); first = false )
1391 {
1392 if( first )
1393 {
1394 const float cmTo3D = boardAdapter.BiuTo3dUnits() * pcbIUScale.mmToIU( 10.0 );
1395
1396 // First redraw resets lookat point to the board center, so set up the camera here
1397 camera.ViewCommand_T1( s_viewCmdMap[aRenderJob->m_side] );
1398
1399 camera.SetLookAtPos_T1( camera.GetLookAtPos_T1()
1400 + SFVEC3F( aRenderJob->m_pivot.x, aRenderJob->m_pivot.y, aRenderJob->m_pivot.z )
1401 * cmTo3D );
1402
1403 camera.Pan_T1( SFVEC3F( aRenderJob->m_pan.x, aRenderJob->m_pan.y, aRenderJob->m_pan.z ) );
1404
1405 camera.Zoom_T1( aRenderJob->m_zoom );
1406
1407 camera.RotateX_T1( DEG2RAD( aRenderJob->m_rotation.x ) );
1408 camera.RotateY_T1( DEG2RAD( aRenderJob->m_rotation.y ) );
1409 camera.RotateZ_T1( DEG2RAD( aRenderJob->m_rotation.z ) );
1410
1411 camera.Interpolate( 1.0f );
1412 camera.SetT0_and_T1_current_T();
1413 camera.ParametersChanged();
1414 }
1415 }
1416
1417 uint8_t* rgbaBuffer = raytrace.GetBuffer();
1418 wxSize realSize = raytrace.GetRealBufferSize();
1419 bool success = !!rgbaBuffer;
1420
1421 if( rgbaBuffer )
1422 {
1423 const unsigned int wxh = realSize.x * realSize.y;
1424
1425 unsigned char* rgbBuffer = (unsigned char*) malloc( wxh * 3 );
1426 unsigned char* alphaBuffer = (unsigned char*) malloc( wxh );
1427
1428 unsigned char* rgbaPtr = rgbaBuffer;
1429 unsigned char* rgbPtr = rgbBuffer;
1430 unsigned char* alphaPtr = alphaBuffer;
1431
1432 for( int y = 0; y < realSize.y; y++ )
1433 {
1434 for( int x = 0; x < realSize.x; x++ )
1435 {
1436 rgbPtr[0] = rgbaPtr[0];
1437 rgbPtr[1] = rgbaPtr[1];
1438 rgbPtr[2] = rgbaPtr[2];
1439 alphaPtr[0] = rgbaPtr[3];
1440
1441 rgbaPtr += 4;
1442 rgbPtr += 3;
1443 alphaPtr += 1;
1444 }
1445 }
1446
1447 wxImage image( realSize );
1448 image.SetData( rgbBuffer );
1449 image.SetAlpha( alphaBuffer );
1450 image = image.Mirror( false );
1451
1452 image.SetOption( wxIMAGE_OPTION_QUALITY, 90 );
1453 image.SaveFile( outPath, aRenderJob->m_format == JOB_PCB_RENDER::FORMAT::PNG ? wxBITMAP_TYPE_PNG
1454 : wxBITMAP_TYPE_JPEG );
1455 }
1456
1457 if( success )
1458 {
1459 m_reporter->Report( _( "Successfully created 3D render image" ) + wxS( "\n" ), RPT_SEVERITY_INFO );
1460 return CLI::EXIT_CODES::OK;
1461 }
1462 else
1463 {
1464 m_reporter->Report( _( "Error creating 3D render image" ) + wxS( "\n" ), RPT_SEVERITY_ERROR );
1466 }
1467}
1468
1469
1471 TOOL_MANAGER* aToolManager, LSEQ& aLayersToPlot )
1472{
1473 if( aJob->m_checkZonesBeforePlot )
1474 {
1475 if( !aToolManager->FindTool( ZONE_FILLER_TOOL_NAME ) )
1476 aToolManager->RegisterTool( new ZONE_FILLER_TOOL );
1477
1478 aToolManager->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, m_progressReporter, true );
1479 }
1480
1481 if( aJob->m_argLayers )
1482 aJob->m_plotLayerSequence = convertLayerArg( aJob->m_argLayers.value(), aBoard );
1483
1484 if( aJob->m_argCommonLayers )
1485 aJob->m_plotOnAllLayersSequence = convertLayerArg( aJob->m_argCommonLayers.value(), aBoard );
1486
1487 aLayersToPlot = aJob->ResolvePlotLayers( aBoard->GetEnabledLayers() );
1488
1489 if( aLayersToPlot.empty() )
1490 {
1491 m_reporter->Report( _( "At least one layer must be specified\n" ), RPT_SEVERITY_ERROR );
1492 return false;
1493 }
1494
1495 return true;
1496}
1497
1498
1500 PLOT_FORMAT aFormat, bool aSingleOutput )
1501{
1502 if( aSingleOutput && aJob->GetConfiguredOutputPath().IsEmpty() )
1503 {
1504 wxFileName fn = aBoard->GetFileName();
1505 fn.SetExt( GetDefaultPlotExtension( aFormat ) );
1506 aJob->SetWorkingOutputPath( fn.GetFullName() );
1507 }
1508
1509 return resolveJobOutputPath( aJob, aBoard, &aJob->m_drawingSheet );
1510}
1511
1512
1513// PDF single-document output need not use overrides; PNG never uses them.
1514static int plotJob( JOB_EXPORT_PCB_PLOT* aJob, PCB_PLOTTER& aPlotter, const LSEQ& aLayersToPlot,
1515 const wxString& aOutPath, bool aSingleOutput, bool aUseVarOverrides,
1516 bool aForceAllLayersToOnePage = false )
1517{
1518 std::optional<wxString> layerName;
1519 std::optional<wxString> sheetName;
1520 std::optional<wxString> sheetPath;
1521
1522 if( aUseVarOverrides )
1523 {
1524 if( aJob->GetVarOverrides().contains( wxT( "LAYER" ) ) )
1525 layerName = aJob->GetVarOverrides().at( wxT( "LAYER" ) );
1526
1527 if( aJob->GetVarOverrides().contains( wxT( "SHEETNAME" ) ) )
1528 sheetName = aJob->GetVarOverrides().at( wxT( "SHEETNAME" ) );
1529
1530 if( aJob->GetVarOverrides().contains( wxT( "SHEETPATH" ) ) )
1531 sheetPath = aJob->GetVarOverrides().at( wxT( "SHEETPATH" ) );
1532 }
1533
1534 bool useGerberFileExtensions = false;
1535 std::vector<wxString> outputPaths;
1536
1537 if( !aPlotter.Plot( aOutPath, aLayersToPlot, aJob->m_plotOnAllLayersSequence, useGerberFileExtensions,
1538 aSingleOutput, aForceAllLayersToOnePage, layerName, sheetName, sheetPath, &outputPaths ) )
1539 {
1541 }
1542
1543 for( const wxString& outputPath : outputPaths )
1544 aJob->AddOutput( outputPath );
1545
1546 return CLI::EXIT_CODES::OK;
1547}
1548
1549
1551{
1552 JOB_EXPORT_PCB_SVG* aSvgJob = dynamic_cast<JOB_EXPORT_PCB_SVG*>( aJob );
1553
1554 if( aSvgJob == nullptr )
1556
1557 BOARD* brd = getBoard( aSvgJob->m_filename );
1558 TOOL_MANAGER* toolManager = getToolManager( brd );
1559
1560 if( !brd )
1562
1563 if( !aSvgJob->m_variant.IsEmpty() )
1564 brd->SetCurrentVariant( aSvgJob->m_variant );
1565
1566 const bool isSingle = aSvgJob->m_genMode == JOB_EXPORT_PCB_SVG::GEN_MODE::SINGLE;
1567 const bool useVarOverrides = isSingle;
1568
1569 wxString outPath = resolvePlotOutputPath( aSvgJob, brd, PLOT_FORMAT::SVG, isSingle );
1570
1571 if( !PATHS::EnsurePathExists( outPath, isSingle ) )
1572 {
1573 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1575 }
1576
1577 LSEQ layersToPlot;
1578
1579 if( !preparePlotLayers( aSvgJob, brd, toolManager, layersToPlot ) )
1581
1582 PCB_PLOT_PARAMS plotOpts;
1583 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, aSvgJob, *m_reporter );
1584
1585 PCB_PLOTTER plotter( brd, m_reporter, plotOpts );
1586
1587 return plotJob( aSvgJob, plotter, layersToPlot, outPath, isSingle, useVarOverrides );
1588}
1589
1590
1592{
1593 JOB_EXPORT_PCB_DXF* aDxfJob = dynamic_cast<JOB_EXPORT_PCB_DXF*>( aJob );
1594
1595 if( aDxfJob == nullptr )
1597
1598 BOARD* brd = getBoard( aDxfJob->m_filename );
1599
1600 if( !brd )
1602
1603 if( !aDxfJob->m_variant.IsEmpty() )
1604 brd->SetCurrentVariant( aDxfJob->m_variant );
1605
1606 TOOL_MANAGER* toolManager = getToolManager( brd );
1607
1608 LSEQ layersToPlot;
1609
1610 if( !preparePlotLayers( aDxfJob, brd, toolManager, layersToPlot ) )
1612
1613 const bool isSingle = aDxfJob->m_genMode == JOB_EXPORT_PCB_DXF::GEN_MODE::SINGLE;
1614 const bool useVarOverrides = isSingle;
1615
1616 wxString outPath = resolvePlotOutputPath( aDxfJob, brd, PLOT_FORMAT::DXF, isSingle );
1617
1618 if( !PATHS::EnsurePathExists( outPath, isSingle ) )
1619 {
1620 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1622 }
1623
1624 PCB_PLOT_PARAMS plotOpts;
1625 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, aDxfJob, *m_reporter );
1626
1627 PCB_PLOTTER plotter( brd, m_reporter, plotOpts );
1628
1629 return plotJob( aDxfJob, plotter, layersToPlot, outPath, isSingle, useVarOverrides );
1630}
1631
1632
1634{
1635 JOB_EXPORT_PCB_PDF* pdfJob = dynamic_cast<JOB_EXPORT_PCB_PDF*>( aJob );
1636
1637 if( pdfJob == nullptr )
1639
1640 BOARD* brd = getBoard( pdfJob->m_filename );
1641
1642 if( !brd )
1644
1645 if( !pdfJob->m_variant.IsEmpty() )
1646 brd->SetCurrentVariant( pdfJob->m_variant );
1647
1648 TOOL_MANAGER* toolManager = getToolManager( brd );
1649
1650 LSEQ layersToPlot;
1651
1652 if( !preparePlotLayers( pdfJob, brd, toolManager, layersToPlot ) )
1654
1655 bool outputIsSingle = pdfJob->m_pdfSingle;
1656 bool useVarOverrides = outputIsSingle;
1657 bool forceAllLayersToOnePage = false;
1658
1659 // This mode is deprecated, but for now it exports all layers to a single page (instead of
1660 // all layers to a single file, with one page per layer).
1662 {
1663 outputIsSingle = true;
1664 useVarOverrides = true;
1665 forceAllLayersToOnePage = true;
1666 }
1667
1668 wxString outPath = resolvePlotOutputPath( pdfJob, brd, PLOT_FORMAT::PDF, outputIsSingle );
1669
1670 PCB_PLOT_PARAMS plotOpts;
1671 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, pdfJob, *m_reporter );
1672
1673 PCB_PLOTTER pcbPlotter( brd, m_reporter, plotOpts );
1674
1675 if( !PATHS::EnsurePathExists( outPath, outputIsSingle ) )
1676 {
1677 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1679 }
1680
1681 return plotJob( pdfJob, pcbPlotter, layersToPlot, outPath, outputIsSingle, useVarOverrides,
1682 forceAllLayersToOnePage );
1683}
1684
1685
1687{
1688 JOB_EXPORT_PCB_PNG* pngJob = dynamic_cast<JOB_EXPORT_PCB_PNG*>( aJob );
1689
1690 if( pngJob == nullptr )
1692
1693 BOARD* brd = getBoard( pngJob->m_filename );
1694
1695 if( !brd )
1697
1698 if( !pngJob->m_variant.IsEmpty() )
1699 brd->SetCurrentVariant( pngJob->m_variant );
1700
1701 TOOL_MANAGER* toolManager = getToolManager( brd );
1702
1703 LSEQ layersToPlot;
1704
1705 if( !preparePlotLayers( pngJob, brd, toolManager, layersToPlot ) )
1707
1708 bool isSingle = pngJob->m_genMode == JOB_EXPORT_PCB_PNG::GEN_MODE::SINGLE;
1709 bool useVarOverrides = isSingle;
1710
1711 wxString outPath = resolvePlotOutputPath( pngJob, brd, PLOT_FORMAT::PNG, isSingle );
1712
1713 PCB_PLOT_PARAMS plotOpts;
1714 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, pngJob, *m_reporter );
1715
1716 PCB_PLOTTER pcbPlotter( brd, m_reporter, plotOpts );
1717
1718 if( !PATHS::EnsurePathExists( outPath, isSingle ) )
1719 {
1720 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1722 }
1723
1724 return plotJob( pngJob, pcbPlotter, layersToPlot, outPath, isSingle, useVarOverrides );
1725}
1726
1727
1729{
1730 JOB_EXPORT_PCB_PS* psJob = dynamic_cast<JOB_EXPORT_PCB_PS*>( aJob );
1731
1732 if( psJob == nullptr )
1734
1735 BOARD* brd = getBoard( psJob->m_filename );
1736
1737 if( !brd )
1739
1740 if( !psJob->m_variant.IsEmpty() )
1741 brd->SetCurrentVariant( psJob->m_variant );
1742
1743 TOOL_MANAGER* toolManager = getToolManager( brd );
1744
1745 LSEQ layersToPlot;
1746
1747 if( !preparePlotLayers( psJob, brd, toolManager, layersToPlot ) )
1749
1750 bool isSingle = psJob->m_genMode == JOB_EXPORT_PCB_PS::GEN_MODE::SINGLE;
1751 bool useVarOverrides = isSingle;
1752
1753 wxString outPath = resolvePlotOutputPath( psJob, brd, PLOT_FORMAT::POST, isSingle );
1754
1755 if( !PATHS::EnsurePathExists( outPath, isSingle ) )
1756 {
1757 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1759 }
1760
1761 PCB_PLOT_PARAMS plotOpts;
1762 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, psJob, *m_reporter );
1763
1764 PCB_PLOTTER pcbPlotter( brd, m_reporter, plotOpts );
1765
1766 return plotJob( psJob, pcbPlotter, layersToPlot, outPath, isSingle, useVarOverrides );
1767}
1768
1769
1771{
1772 int exitCode = CLI::EXIT_CODES::OK;
1773 JOB_EXPORT_PCB_GERBERS* aGerberJob = dynamic_cast<JOB_EXPORT_PCB_GERBERS*>( aJob );
1774
1775 if( aGerberJob == nullptr )
1777
1778 BOARD* brd = getBoard( aGerberJob->m_filename );
1779
1780 if( !brd )
1782
1783 if( !aGerberJob->m_variant.IsEmpty() )
1784 brd->SetCurrentVariant( aGerberJob->m_variant );
1785
1786 wxString outPath = resolveJobOutputPath( aJob, brd, &aGerberJob->m_drawingSheet );
1787
1788 if( !PATHS::EnsurePathExists( outPath, false ) )
1789 {
1790 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1792 }
1793
1794 TOOL_MANAGER* toolManager = getToolManager( brd );
1795
1796 if( aGerberJob->m_checkZonesBeforePlot )
1797 {
1798 if( !toolManager->FindTool( ZONE_FILLER_TOOL_NAME ) )
1799 toolManager->RegisterTool( new ZONE_FILLER_TOOL );
1800
1801 toolManager->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, m_progressReporter, true );
1802 }
1803
1804 bool hasLayerListSpecified = false; // will be true if the user layer list is not empty
1805
1806 if( aGerberJob->m_argLayers )
1807 {
1808 if( !aGerberJob->m_argLayers.value().empty() )
1809 {
1810 aGerberJob->m_plotLayerSequence = convertLayerArg( aGerberJob->m_argLayers.value(), brd );
1811 hasLayerListSpecified = true;
1812 }
1813 else
1814 {
1816 }
1817 }
1818
1819 if( aGerberJob->m_argCommonLayers )
1820 aGerberJob->m_plotOnAllLayersSequence = convertLayerArg( aGerberJob->m_argCommonLayers.value(), brd );
1821
1822 PCB_PLOT_PARAMS boardPlotOptions = brd->GetPlotOptions();
1823 GERBER_JOBFILE_WRITER jobfile_writer( brd );
1824
1825 wxString fileExt;
1826
1827 if( aGerberJob->m_useBoardPlotParams )
1828 {
1829 // The board plot options are saved with all copper layers enabled, even those that don't
1830 // exist in the current stackup. This is done so the layers are automatically enabled in the plot
1831 // dialog when the user enables them. We need to filter out these not-enabled layers here so
1832 // we don't plot 32 layers when we only have 4, etc.
1833 LSET plotLayers = ( boardPlotOptions.GetLayerSelection() & LSET::AllNonCuMask() )
1834 | ( brd->GetEnabledLayers() & LSET::AllCuMask() );
1835 aGerberJob->m_plotLayerSequence = plotLayers.SeqStackupForPlotting();
1836 aGerberJob->m_plotOnAllLayersSequence = boardPlotOptions.GetPlotOnAllLayersSequence();
1837 }
1838 else
1839 {
1840 // default to the board enabled layers, but only if the user has not specifed a layer list
1841 // ( m_plotLayerSequence can be empty with a broken user layer list)
1842 if( aGerberJob->m_plotLayerSequence.empty() && !hasLayerListSpecified
1843 && !aGerberJob->m_plotAllCopperLayers )
1844 {
1846 }
1847 }
1848
1849 // Ensure layers to plot are restricted to enabled layers of the board to plot
1850 LSET layersToPlot = LSET( aGerberJob->ResolvePlotLayers( brd->GetEnabledLayers() ) ) & brd->GetEnabledLayers();
1851
1852 // Once for the run, not per file, so an update rebuilds each chart once
1853 RefreshGeneratedTables( *brd );
1854
1855 for( PCB_LAYER_ID layer : layersToPlot.UIOrder() )
1856 {
1857 LSEQ plotSequence;
1858
1859 // Base layer always gets plotted first.
1860 plotSequence.push_back( layer );
1861
1862 // Now all the "include on all" layers
1863 for( PCB_LAYER_ID layer_all : aGerberJob->m_plotOnAllLayersSequence )
1864 {
1865 // Don't plot the same layer more than once;
1866 if( find( plotSequence.begin(), plotSequence.end(), layer_all ) != plotSequence.end() )
1867 continue;
1868
1869 plotSequence.push_back( layer_all );
1870 }
1871
1872 // Pick the basename from the board file
1873 wxFileName fn( brd->GetFileName() );
1874 wxString layerName = brd->GetLayerName( layer );
1875 wxString sheetName;
1876 wxString sheetPath;
1877 PCB_PLOT_PARAMS plotOpts;
1878
1879 if( aGerberJob->m_useBoardPlotParams )
1880 plotOpts = boardPlotOptions;
1881 else
1882 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, aGerberJob, *m_reporter );
1883
1884 if( plotOpts.GetUseGerberProtelExtensions() )
1885 fileExt = GetGerberProtelExtension( layer );
1886 else
1888
1889 PCB_PLOTTER::BuildPlotFileName( &fn, outPath, layerName, fileExt );
1890 wxString fullname = fn.GetFullName();
1891
1892 if( m_progressReporter )
1893 {
1894 m_progressReporter->AdvancePhase( wxString::Format( _( "Exporting %s" ), fullname ) );
1895 m_progressReporter->KeepRefreshing();
1896 }
1897
1898 jobfile_writer.AddGbrFile( layer, fullname );
1899
1900 if( aJob->GetVarOverrides().contains( wxT( "LAYER" ) ) )
1901 layerName = aJob->GetVarOverrides().at( wxT( "LAYER" ) );
1902
1903 if( aJob->GetVarOverrides().contains( wxT( "SHEETNAME" ) ) )
1904 sheetName = aJob->GetVarOverrides().at( wxT( "SHEETNAME" ) );
1905
1906 if( aJob->GetVarOverrides().contains( wxT( "SHEETPATH" ) ) )
1907 sheetPath = aJob->GetVarOverrides().at( wxT( "SHEETPATH" ) );
1908
1909 // We are feeding it one layer at the start here to silence a logic check
1910 GERBER_PLOTTER* plotter;
1911 plotter = (GERBER_PLOTTER*) StartPlotBoard( brd, &plotOpts, layer, layerName, fn.GetFullPath(), sheetName,
1912 sheetPath );
1913
1914 if( plotter )
1915 {
1916 m_reporter->Report( wxString::Format( _( "Plotted to '%s'.\n" ), fn.GetFullPath() ), RPT_SEVERITY_ACTION );
1917
1918 PlotBoardLayers( brd, plotter, plotSequence, plotOpts );
1919 plotter->EndPlot();
1920 aJob->AddOutput( fn.GetFullPath() );
1921 }
1922 else
1923 {
1924 m_reporter->Report( wxString::Format( _( "Failed to plot to '%s'.\n" ), fn.GetFullPath() ),
1927 }
1928
1929 delete plotter;
1930 }
1931
1932 if( aGerberJob->m_createJobsFile )
1933 {
1934 wxFileName fn( brd->GetFileName() );
1935
1936 // Build gerber job file from basename
1938 jobfile_writer.CreateJobFile( fn.GetFullPath() );
1939 aJob->AddOutput( fn.GetFullPath() );
1940 }
1941
1942 return exitCode;
1943}
1944
1945
1947{
1948 JOB_EXPORT_PCB_GENCAD* aGencadJob = dynamic_cast<JOB_EXPORT_PCB_GENCAD*>( aJob );
1949
1950 if( aGencadJob == nullptr )
1952
1953 BOARD* brd = getBoard( aGencadJob->m_filename );
1954
1955 if( !brd )
1957
1958 GENCAD_EXPORTER exporter( brd );
1959
1960 VECTOR2I GencadOffset;
1961 VECTOR2I auxOrigin = brd->GetDesignSettings().GetAuxOrigin();
1962 GencadOffset.x = aGencadJob->m_useDrillOrigin ? auxOrigin.x : 0;
1963 GencadOffset.y = aGencadJob->m_useDrillOrigin ? auxOrigin.y : 0;
1964
1965 exporter.FlipBottomPads( aGencadJob->m_flipBottomPads );
1966 exporter.UsePinNamesUnique( aGencadJob->m_useUniquePins );
1967 exporter.UseIndividualShapes( aGencadJob->m_useIndividualShapes );
1968 exporter.SetPlotOffet( GencadOffset );
1969 exporter.StoreOriginCoordsInFile( aGencadJob->m_storeOriginCoords );
1970
1971 if( aGencadJob->GetConfiguredOutputPath().IsEmpty() )
1972 {
1973 wxFileName fn = brd->GetFileName();
1974 fn.SetName( fn.GetName() );
1975 fn.SetExt( FILEEXT::GencadFileExtension );
1976
1977 aGencadJob->SetWorkingOutputPath( fn.GetFullName() );
1978 }
1979
1980 wxString outPath = resolveJobOutputPath( aJob, brd );
1981
1982 if( !PATHS::EnsurePathExists( outPath, true ) )
1983 {
1984 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
1986 }
1987
1988 if( !exporter.WriteFile( outPath ) )
1989 {
1990 m_reporter->Report( wxString::Format( _( "Failed to create file '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
1991
1993 }
1994
1995 aJob->AddOutput( outPath );
1996 m_reporter->Report( _( "Successfully created genCAD file\n" ), RPT_SEVERITY_INFO );
1997
1998 return CLI::EXIT_CODES::OK;
1999}
2000
2001
2003{
2004 JOB_EXPORT_PCB_SPECCTRA_DSN* specctraJob = dynamic_cast<JOB_EXPORT_PCB_SPECCTRA_DSN*>( aJob );
2005
2006 if( !specctraJob )
2008
2009 BOARD* brd = getBoard( specctraJob->m_filename );
2010
2011 if( !brd )
2013
2014 if( specctraJob->GetConfiguredOutputPath().IsEmpty() )
2015 {
2016 wxFileName fn = brd->GetFileName();
2018
2019 specctraJob->SetWorkingOutputPath( fn.GetFullName() );
2020 }
2021
2022 wxString outPath = resolveJobOutputPath( aJob, brd );
2023
2024 if( !PATHS::EnsurePathExists( outPath, true ) )
2025 {
2026 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2028 }
2029
2030 try
2031 {
2033 }
2034 catch( const IO_ERROR& ioe )
2035 {
2036 m_reporter->Report( wxString::Format( _( "Export failed: %s\n" ), ioe.What() ),
2039 }
2040
2041 aJob->AddOutput( outPath );
2042 m_reporter->Report( _( "Successfully created Specctra DSN file\n" ), RPT_SEVERITY_INFO );
2043
2044 return CLI::EXIT_CODES::OK;
2045}
2046
2047
2049{
2050 JOB_EXPORT_PCB_STATS* statsJob = dynamic_cast<JOB_EXPORT_PCB_STATS*>( aJob );
2051
2052 if( statsJob == nullptr )
2054
2055 BOARD* brd = getBoard( statsJob->m_filename );
2056
2057 if( !brd )
2059
2062
2067
2068 ComputeBoardStatistics( brd, options, data );
2069
2070 wxString projectName;
2071
2072 if( brd->GetProject() )
2073 projectName = brd->GetProject()->GetProjectName();
2074
2075 wxFileName boardFile = brd->GetFileName();
2076
2077 if( boardFile.GetName().IsEmpty() )
2078 boardFile = wxFileName( statsJob->m_filename );
2079
2081 UNITS_PROVIDER unitsProvider( pcbIUScale, unitsForReport );
2082
2083 wxString report;
2084
2086 report = FormatBoardStatisticsJson( data, brd, unitsProvider, projectName, boardFile.GetName() );
2087 else
2088 report = FormatBoardStatisticsReport( data, brd, unitsProvider, projectName, boardFile.GetName() );
2089
2090 if( statsJob->GetConfiguredOutputPath().IsEmpty() && statsJob->GetWorkingOutputPath().IsEmpty() )
2091 statsJob->SetDefaultOutputPath( boardFile.GetFullPath() );
2092
2093 wxString outPath = resolveJobOutputPath( aJob, brd );
2094
2095 if( !PATHS::EnsurePathExists( outPath, true ) )
2096 {
2097 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2099 }
2100
2101 FILE* outFile = wxFopen( outPath, wxS( "wt" ) );
2102
2103 if( !outFile )
2104 {
2105 m_reporter->Report( wxString::Format( _( "Failed to create file '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
2107 }
2108
2109 if( fprintf( outFile, "%s", TO_UTF8( report ) ) < 0 )
2110 {
2111 fclose( outFile );
2112 m_reporter->Report( wxString::Format( _( "Error writing file '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
2114 }
2115
2116 fclose( outFile );
2117
2118 m_reporter->Report( wxString::Format( _( "Wrote board statistics to '%s'.\n" ), outPath ), RPT_SEVERITY_ACTION );
2119
2120 statsJob->AddOutput( outPath );
2121
2122 return CLI::EXIT_CODES::OK;
2123}
2124
2125
2127{
2128 JOB_EXPORT_PCB_STACKUP* stackupJob = dynamic_cast<JOB_EXPORT_PCB_STACKUP*>( aJob );
2129
2130 if( stackupJob == nullptr )
2132
2133 BOARD* brd = getBoard( stackupJob->m_filename );
2134
2135 if( !brd )
2137
2138 wxFileName boardFile = brd->GetFileName();
2139
2140 if( boardFile.GetName().IsEmpty() )
2141 boardFile = wxFileName( stackupJob->m_filename );
2142
2143 wxString output;
2144
2145 switch( stackupJob->m_format )
2146 {
2148 {
2149 kiapi::board::BoardStackup stackupMsg;
2150 kiapi::board::PackBoardStackup( *brd, stackupMsg );
2151
2152 google::protobuf::util::JsonPrintOptions jsonOptions;
2153 jsonOptions.add_whitespace = true;
2154
2155 std::string json;
2156
2157 if( !google::protobuf::util::MessageToJsonString( stackupMsg, &json, jsonOptions ).ok() )
2158 {
2159 m_reporter->Report( _( "Failed to serialize board stackup\n" ), RPT_SEVERITY_ERROR );
2161 }
2162
2163 output = wxString::FromUTF8( json );
2164 break;
2165 }
2166
2168 {
2170 BOARD_STACKUP stackup = bds.GetStackupDescriptor();
2171 stackup.SynchronizeWithBoard( &bds );
2172
2173 for( BOARD_STACKUP_ITEM* item : stackup.GetList() )
2174 {
2175 if( item->GetBrdLayerId() != UNDEFINED_LAYER )
2176 item->SetLayerName( brd->GetLayerName( item->GetBrdLayerId() ) );
2177 }
2178
2179 EDA_UNITS unitsForReport = stackupJob->m_units == JOB_EXPORT_PCB_STACKUP::UNITS::MM ? EDA_UNITS::MM
2181
2182 STACKUP_CSV_OPTIONS options;
2183 options.includeColor = stackupJob->m_includeColor;
2184 options.includeMaterial = stackupJob->m_includeMaterial;
2185 options.includeThickness = stackupJob->m_includeThickness;
2186 options.includeEpsilonR = stackupJob->m_includeEpsilonR;
2187 options.includeLossTangent = stackupJob->m_includeLossTangent;
2188 options.includeFinish = stackupJob->m_includeFinish;
2189 options.includeBoardOptions = stackupJob->m_includeBoardOptions;
2190
2191 output = BuildStackupCsv( stackup, unitsForReport, options );
2192 break;
2193 }
2194 }
2195
2196 if( stackupJob->GetConfiguredOutputPath().IsEmpty() && stackupJob->GetWorkingOutputPath().IsEmpty() )
2197 stackupJob->SetDefaultOutputPath( boardFile.GetFullPath() );
2198
2199 wxString outPath = resolveJobOutputPath( aJob, brd );
2200
2201 if( !PATHS::EnsurePathExists( outPath, true ) )
2202 {
2203 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2205 }
2206
2207 OPEN_OSTREAM( outFile, TO_UTF8( outPath ) );
2208
2209 if( !outFile )
2210 {
2211 m_reporter->Report( wxString::Format( _( "Failed to create file '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
2213 }
2214
2215 outFile << TO_UTF8( output );
2216
2217 const bool writeOk = static_cast<bool>( outFile );
2218 CLOSE_STREAM( outFile );
2219
2220 if( !writeOk )
2221 {
2222 m_reporter->Report( wxString::Format( _( "Error writing file '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
2224 }
2225
2226 m_reporter->Report( wxString::Format( _( "Wrote board stackup to '%s'.\n" ), outPath ), RPT_SEVERITY_ACTION );
2227
2228 stackupJob->AddOutput( outPath );
2229
2230 return CLI::EXIT_CODES::OK;
2231}
2232
2233
2235{
2236 int exitCode = CLI::EXIT_CODES::OK;
2237 JOB_EXPORT_PCB_GERBER* aGerberJob = dynamic_cast<JOB_EXPORT_PCB_GERBER*>( aJob );
2238
2239 if( aGerberJob == nullptr )
2241
2242 BOARD* brd = getBoard( aGerberJob->m_filename );
2243
2244 if( !brd )
2246
2247 if( !aGerberJob->m_variant.IsEmpty() )
2248 brd->SetCurrentVariant( aGerberJob->m_variant );
2249
2250 TOOL_MANAGER* toolManager = getToolManager( brd );
2251
2252 if( aGerberJob->m_argLayers )
2253 aGerberJob->m_plotLayerSequence = convertLayerArg( aGerberJob->m_argLayers.value(), brd );
2254
2255 if( aGerberJob->m_argCommonLayers )
2256 aGerberJob->m_plotOnAllLayersSequence = convertLayerArg( aGerberJob->m_argCommonLayers.value(), brd );
2257
2258 if( aGerberJob->m_plotLayerSequence.size() < 1 )
2259 {
2260 m_reporter->Report( _( "At least one layer must be specified\n" ), RPT_SEVERITY_ERROR );
2262 }
2263
2264 if( aGerberJob->GetConfiguredOutputPath().IsEmpty() )
2265 {
2266 wxFileName fn = brd->GetFileName();
2267 fn.SetName( fn.GetName() );
2269
2270 aGerberJob->SetWorkingOutputPath( fn.GetFullName() );
2271 }
2272
2273 wxString outPath = resolveJobOutputPath( aJob, brd, &aGerberJob->m_drawingSheet );
2274
2275 if( aGerberJob->m_checkZonesBeforePlot )
2276 {
2277 if( !toolManager->FindTool( ZONE_FILLER_TOOL_NAME ) )
2278 toolManager->RegisterTool( new ZONE_FILLER_TOOL );
2279
2280 toolManager->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, m_progressReporter, true );
2281 }
2282
2283 PCB_PLOT_PARAMS plotOpts;
2284 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, aGerberJob, *m_reporter );
2285 plotOpts.SetLayerSelection( aGerberJob->m_plotLayerSequence );
2287
2289 wxString layerName;
2290 wxString sheetName;
2291 wxString sheetPath;
2292
2293 // The first layer will be treated as the layer name for the gerber header,
2294 // the other layers will be treated equivalent to the "Plot on All Layers" option
2295 // in the GUI
2296 if( aGerberJob->m_plotLayerSequence.size() >= 1 )
2297 {
2298 layer = aGerberJob->m_plotLayerSequence.front();
2299 layerName = brd->GetLayerName( layer );
2300 }
2301
2302 if( aJob->GetVarOverrides().contains( wxT( "LAYER" ) ) )
2303 layerName = aJob->GetVarOverrides().at( wxT( "LAYER" ) );
2304
2305 if( aJob->GetVarOverrides().contains( wxT( "SHEETNAME" ) ) )
2306 sheetName = aJob->GetVarOverrides().at( wxT( "SHEETNAME" ) );
2307
2308 if( aJob->GetVarOverrides().contains( wxT( "SHEETPATH" ) ) )
2309 sheetPath = aJob->GetVarOverrides().at( wxT( "SHEETPATH" ) );
2310
2311 // We are feeding it one layer at the start here to silence a logic check
2312
2313 // It drives StartPlotBoard directly rather than PCB_PLOTTER::Plot, so it refreshes on its own
2314 RefreshGeneratedTables( *brd );
2315
2316 PLOTTER* plotter = StartPlotBoard( brd, &plotOpts, layer, layerName, outPath, sheetName, sheetPath );
2317 bool success = false;
2318
2319 if( plotter )
2320 {
2321 PlotBoardLayers( brd, plotter, aGerberJob->m_plotLayerSequence, plotOpts );
2322 success = plotter->EndPlot();
2323 }
2324
2325 if( !success )
2326 {
2327 m_reporter->Report( wxString::Format( _( "Failed to plot to '%s'.\n" ), outPath ), RPT_SEVERITY_ERROR );
2329 }
2330
2331 delete plotter;
2332
2333 return exitCode;
2334}
2335
2338
2339
2341{
2342 JOB_EXPORT_PCB_DRILL* aDrillJob = dynamic_cast<JOB_EXPORT_PCB_DRILL*>( aJob );
2343
2344 if( aDrillJob == nullptr )
2346
2347 BOARD* brd = getBoard( aDrillJob->m_filename );
2348
2349 if( !brd )
2351
2352 wxString outPath = resolveJobOutputPath( aJob, brd );
2353
2354 if( !PATHS::EnsurePathExists( outPath ) )
2355 {
2356 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2358 }
2359
2360 std::unique_ptr<GENDRILL_WRITER_BASE> drillWriter;
2361
2363 drillWriter = std::make_unique<EXCELLON_WRITER>( brd );
2364 else
2365 drillWriter = std::make_unique<GERBER_WRITER>( brd );
2366
2367 VECTOR2I offset;
2368
2370 offset = VECTOR2I( 0, 0 );
2371 else
2372 offset = brd->GetDesignSettings().GetAuxOrigin();
2373
2374 PLOT_FORMAT mapFormat = PLOT_FORMAT::PDF;
2375
2376 switch( aDrillJob->m_mapFormat )
2377 {
2382 default:
2384 }
2385
2386
2387 wxString reportPathSetting = aDrillJob->m_reportPath;
2388
2389 // Keep the generated default out of the job so it is not saved into the jobset
2390 if( aDrillJob->m_generateReport && reportPathSetting.IsEmpty() )
2391 {
2392 wxFileName fn = wxFileName::DirName( outPath );
2393 fn.SetFullName( brd->GetFileName() );
2394 fn.SetName( fn.GetName() + "-drill" );
2395 fn.SetExt( FILEEXT::ReportFileExtension );
2396
2397 reportPathSetting = fn.GetFullPath();
2398 }
2399
2401 {
2403
2404 switch( aDrillJob->m_zeroFormat )
2405 {
2407
2409
2411
2413 default: zeroFmt = EXCELLON_WRITER::DECIMAL_FORMAT; break;
2414 }
2415
2416 DRILL_PRECISION precision;
2417
2419 precision = precisionListForInches;
2420 else
2421 precision = precisionListForMetric;
2422
2423 EXCELLON_WRITER* excellonWriter = dynamic_cast<EXCELLON_WRITER*>( drillWriter.get() );
2424
2425 if( excellonWriter == nullptr )
2427
2428 excellonWriter->SetFormat( aDrillJob->m_drillUnits == JOB_EXPORT_PCB_DRILL::DRILL_UNITS::MM, zeroFmt,
2429 precision.m_Lhs, precision.m_Rhs );
2430 excellonWriter->SetOptions( aDrillJob->m_excellonMirrorY, aDrillJob->m_excellonMinimalHeader, offset,
2431 aDrillJob->m_excellonCombinePTHNPTH );
2432 excellonWriter->SetRouteModeForOvalHoles( aDrillJob->m_excellonOvalDrillRoute );
2433 excellonWriter->SetMapFileFormat( mapFormat );
2434
2435 if( !excellonWriter->CreateDrillandMapFilesSet( outPath, true, aDrillJob->m_generateMap, m_reporter ) )
2436 {
2438 }
2439
2440 for( const wxString& outputFile : drillWriter->GetCreatedFiles() )
2441 aDrillJob->AddOutput( outputFile );
2442
2443 if( aDrillJob->m_generateReport )
2444 {
2445 wxString reportPath = aDrillJob->ResolveOutputPath( reportPathSetting, false, brd->GetProject() );
2446
2447 if( !excellonWriter->GenDrillReportFile( reportPath ) )
2448 {
2450 }
2451
2452 aDrillJob->AddOutput( reportPath );
2453 }
2454 }
2456 {
2457 GERBER_WRITER* gerberWriter = dynamic_cast<GERBER_WRITER*>( drillWriter.get() );
2458
2459 if( gerberWriter == nullptr )
2461
2462 // Set gerber precision: only 5 or 6 digits for mantissa are allowed
2463 // (SetFormat() accept 5 or 6, and any other value set the precision to 5)
2464 // the integer part precision is always 4, and units always mm
2465 gerberWriter->SetFormat( aDrillJob->m_gerberPrecision );
2466 gerberWriter->SetOptions( offset );
2467 gerberWriter->SetMapFileFormat( mapFormat );
2468
2469 if( !gerberWriter->CreateDrillandMapFilesSet( outPath, true, aDrillJob->m_generateMap,
2470 aDrillJob->m_generateTenting, m_reporter ) )
2471 {
2473 }
2474
2475 for( const wxString& outputFile : drillWriter->GetCreatedFiles() )
2476 aDrillJob->AddOutput( outputFile );
2477
2478 if( aDrillJob->m_generateReport )
2479 {
2480 wxString reportPath = aDrillJob->ResolveOutputPath( reportPathSetting, false, brd->GetProject() );
2481
2482 if( !gerberWriter->GenDrillReportFile( reportPath ) )
2483 {
2485 }
2486
2487 aDrillJob->AddOutput( reportPath );
2488 }
2489 }
2490
2491 return CLI::EXIT_CODES::OK;
2492}
2493
2494
2496{
2497 JOB_EXPORT_PCB_POS* aPosJob = dynamic_cast<JOB_EXPORT_PCB_POS*>( aJob );
2498
2499 if( aPosJob == nullptr )
2501
2502 BOARD* brd = getBoard( aPosJob->m_filename );
2503
2504 if( !brd )
2506
2507 if( aPosJob->GetConfiguredOutputPath().IsEmpty() )
2508 {
2509 wxFileName fn = brd->GetFileName();
2510 fn.SetName( fn.GetName() );
2511
2514 else if( aPosJob->m_format == JOB_EXPORT_PCB_POS::FORMAT::CSV )
2515 fn.SetExt( FILEEXT::CsvFileExtension );
2516 else if( aPosJob->m_format == JOB_EXPORT_PCB_POS::FORMAT::GERBER )
2517 fn.SetExt( FILEEXT::GerberFileExtension );
2518
2519 aPosJob->SetWorkingOutputPath( fn.GetFullName() );
2520 }
2521
2522 wxString outPath = resolveJobOutputPath( aJob, brd );
2523
2524 if( !PATHS::EnsurePathExists( outPath, true ) )
2525 {
2526 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2528 }
2529
2531 {
2532 wxFileName fn( outPath );
2533 wxString baseName = fn.GetName();
2534
2535 auto exportPlaceFile = [&]( bool frontSide, bool backSide, const wxString& curr_outPath ) -> bool
2536 {
2537 FILE* file = wxFopen( curr_outPath, wxS( "wt" ) );
2538 wxCHECK( file, false );
2539
2540 PLACE_FILE_EXPORTER exporter( brd, aPosJob->m_units == JOB_EXPORT_PCB_POS::UNITS::MM, aPosJob->m_smdOnly,
2541 aPosJob->m_excludeFootprintsWithTh, aPosJob->m_excludeDNP,
2542 aPosJob->m_excludeBOM, frontSide, backSide,
2544 aPosJob->m_useDrillPlaceFileOrigin, aPosJob->m_negateBottomX );
2545
2546 // Set variant for variant-aware DNP/BOM/position file filtering
2547 exporter.SetVariant( aPosJob->m_variant );
2548
2549 std::string data = exporter.GenPositionData();
2550 fputs( data.c_str(), file );
2551 fclose( file );
2552
2553 return true;
2554 };
2555
2556 if( aPosJob->m_side == JOB_EXPORT_PCB_POS::SIDE::BOTH && !aPosJob->m_singleFile )
2557 {
2558 fn.SetName( PLACE_FILE_EXPORTER::DecorateFilename( baseName, true, false ) );
2559
2560 if( aPosJob->m_format == JOB_EXPORT_PCB_POS::FORMAT::CSV && !aPosJob->m_nakedFilename )
2561 fn.SetName( fn.GetName() + wxT( "-" ) + FILEEXT::FootprintPlaceFileExtension );
2562
2563 if( exportPlaceFile( true, false, fn.GetFullPath() ) )
2564 {
2565 m_reporter->Report( wxString::Format( _( "Wrote front position data to '%s'.\n" ), fn.GetFullPath() ),
2567
2568 aPosJob->AddOutput( fn.GetFullPath() );
2569 }
2570 else
2571 {
2573 }
2574
2575 fn.SetName( PLACE_FILE_EXPORTER::DecorateFilename( baseName, false, true ) );
2576
2577 if( aPosJob->m_format == JOB_EXPORT_PCB_POS::FORMAT::CSV && !aPosJob->m_nakedFilename )
2578 fn.SetName( fn.GetName() + wxT( "-" ) + FILEEXT::FootprintPlaceFileExtension );
2579
2580 if( exportPlaceFile( false, true, fn.GetFullPath() ) )
2581 {
2582 m_reporter->Report( wxString::Format( _( "Wrote back position data to '%s'.\n" ), fn.GetFullPath() ),
2584
2585 aPosJob->AddOutput( fn.GetFullPath() );
2586 }
2587 else
2588 {
2590 }
2591 }
2592 else
2593 {
2594 bool front = aPosJob->m_side == JOB_EXPORT_PCB_POS::SIDE::FRONT
2596
2597 bool back = aPosJob->m_side == JOB_EXPORT_PCB_POS::SIDE::BACK
2599
2600 if( !aPosJob->m_nakedFilename )
2601 {
2602 fn.SetName( PLACE_FILE_EXPORTER::DecorateFilename( fn.GetName(), front, back ) );
2603
2605 fn.SetName( fn.GetName() + wxT( "-" ) + FILEEXT::FootprintPlaceFileExtension );
2606 }
2607
2608 if( exportPlaceFile( front, back, fn.GetFullPath() ) )
2609 {
2610 m_reporter->Report( wxString::Format( _( "Wrote position data to '%s'.\n" ), fn.GetFullPath() ),
2612
2613 aPosJob->AddOutput( fn.GetFullPath() );
2614 }
2615 else
2616 {
2618 }
2619 }
2620 }
2621 else if( aPosJob->m_format == JOB_EXPORT_PCB_POS::FORMAT::GERBER )
2622 {
2623 PLACEFILE_GERBER_WRITER exporter( brd );
2624
2625 // Set variant for variant-aware DNP/BOM/position file filtering
2626 exporter.SetVariant( aPosJob->m_variant );
2627
2628 PCB_LAYER_ID gbrLayer = F_Cu;
2629 wxString outPath_base = outPath;
2630
2632 {
2633 if( aPosJob->m_side == JOB_EXPORT_PCB_POS::SIDE::BOTH || !aPosJob->m_nakedFilename )
2634 outPath = exporter.GetPlaceFileName( outPath, gbrLayer );
2635
2636 if( exporter.CreatePlaceFile( outPath, gbrLayer, aPosJob->m_gerberBoardEdge, aPosJob->m_excludeDNP,
2637 aPosJob->m_excludeBOM )
2638 >= 0 )
2639 {
2640 m_reporter->Report( wxString::Format( _( "Wrote front position data to '%s'.\n" ), outPath ),
2642
2643 aPosJob->AddOutput( outPath );
2644 }
2645 else
2646 {
2648 }
2649 }
2650
2652 {
2653 gbrLayer = B_Cu;
2654
2655 outPath = outPath_base;
2656
2657 if( aPosJob->m_side == JOB_EXPORT_PCB_POS::SIDE::BOTH || !aPosJob->m_nakedFilename )
2658 outPath = exporter.GetPlaceFileName( outPath, gbrLayer );
2659
2660 if( exporter.CreatePlaceFile( outPath, gbrLayer, aPosJob->m_gerberBoardEdge, aPosJob->m_excludeDNP,
2661 aPosJob->m_excludeBOM )
2662 >= 0 )
2663 {
2664 m_reporter->Report( wxString::Format( _( "Wrote back position data to '%s'.\n" ), outPath ),
2666
2667 aPosJob->AddOutput( outPath );
2668 }
2669 else
2670 {
2672 }
2673 }
2674 }
2675
2676 return CLI::EXIT_CODES::OK;
2677}
2678
2679
2681{
2682 JOB_FP_UPGRADE* upgradeJob = dynamic_cast<JOB_FP_UPGRADE*>( aJob );
2683
2684 if( upgradeJob == nullptr )
2686
2688
2689 if( !upgradeJob->m_outputLibraryPath.IsEmpty() )
2690 {
2691 if( wxFile::Exists( upgradeJob->m_outputLibraryPath ) || wxDir::Exists( upgradeJob->m_outputLibraryPath ) )
2692 {
2693 m_reporter->Report( _( "Output path must not conflict with existing path\n" ), RPT_SEVERITY_ERROR );
2695 }
2696 }
2697 else if( fileType != PCB_IO_MGR::KICAD_SEXP )
2698 {
2699 m_reporter->Report( _( "Output path must be specified to convert legacy and non-KiCad libraries\n" ),
2701
2703 }
2704
2706 {
2707 if( !wxDir::Exists( upgradeJob->m_libraryPath ) )
2708 {
2709 m_reporter->Report( _( "Footprint library path does not exist or is not accessible\n" ),
2712 }
2713
2715 FP_CACHE fpLib( &pcb_io, upgradeJob->m_libraryPath );
2716
2717 try
2718 {
2719 fpLib.Load();
2720 }
2721 catch( ... )
2722 {
2723 m_reporter->Report( _( "Unable to load library\n" ), RPT_SEVERITY_ERROR );
2725 }
2726
2727 if( m_progressReporter )
2728 m_progressReporter->KeepRefreshing();
2729
2730 bool shouldSave = upgradeJob->m_force;
2731
2732 for( const auto& footprint : fpLib.GetFootprints() )
2733 {
2734 if( footprint.second->GetFootprint()->GetFileFormatVersionAtLoad() < SEXPR_FOOTPRINT_LIB_FILE_VERSION )
2735 shouldSave = true;
2736 }
2737
2738 if( shouldSave )
2739 {
2740 try
2741 {
2742 if( !upgradeJob->m_outputLibraryPath.IsEmpty() )
2743 fpLib.SetPath( upgradeJob->m_outputLibraryPath );
2744
2745 fpLib.Save();
2746 }
2747 catch( ... )
2748 {
2749 m_reporter->Report( _( "Unable to save library\n" ), RPT_SEVERITY_ERROR );
2751 }
2752 }
2753 else
2754 {
2755 m_reporter->Report( _( "Footprint library was not updated\n" ), RPT_SEVERITY_ERROR );
2756 }
2757 }
2758 else
2759 {
2760 if( !PCB_IO_MGR::ConvertLibrary( {}, upgradeJob->m_libraryPath, upgradeJob->m_outputLibraryPath,
2761 nullptr /* REPORTER */ ) )
2762 {
2763 m_reporter->Report( ( "Unable to convert library\n" ), RPT_SEVERITY_ERROR );
2765 }
2766 }
2767
2768 return CLI::EXIT_CODES::OK;
2769}
2770
2771
2773{
2774 JOB_FP_EXPORT_SVG* svgJob = dynamic_cast<JOB_FP_EXPORT_SVG*>( aJob );
2775
2776 if( svgJob == nullptr )
2778
2780 FP_CACHE fpLib( &pcb_io, svgJob->m_libraryPath );
2781
2782 if( svgJob->m_argLayers )
2783 {
2784 if( !svgJob->m_argLayers.value().empty() )
2785 svgJob->m_plotLayerSequence = convertLayerArg( svgJob->m_argLayers.value(), nullptr );
2786 else
2788 }
2789
2790 try
2791 {
2792 fpLib.Load();
2793 }
2794 catch( ... )
2795 {
2796 m_reporter->Report( _( "Unable to load library\n" ), RPT_SEVERITY_ERROR );
2798 }
2799
2800 wxString outPath = svgJob->GetFullOutputPath( nullptr );
2801
2802 if( !PATHS::EnsurePathExists( outPath, true ) )
2803 {
2804 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2806 }
2807
2808 int exitCode = CLI::EXIT_CODES::OK;
2809 bool singleFpPlotted = false;
2810
2811 for( const auto& [fpName, fpCacheEntry] : fpLib.GetFootprints() )
2812 {
2813 if( m_progressReporter )
2814 {
2815 m_progressReporter->AdvancePhase( wxString::Format( _( "Exporting %s" ), fpName ) );
2816 m_progressReporter->KeepRefreshing();
2817 }
2818
2819 if( !svgJob->m_footprint.IsEmpty() )
2820 {
2821 // skip until we find the right footprint
2822 if( fpName != svgJob->m_footprint )
2823 continue;
2824 else
2825 singleFpPlotted = true;
2826 }
2827
2828 exitCode = doFpExportSvg( svgJob, fpCacheEntry->GetFootprint().get() );
2829
2830 if( exitCode != CLI::EXIT_CODES::OK )
2831 break;
2832 }
2833
2834 if( !svgJob->m_footprint.IsEmpty() && !singleFpPlotted )
2835 {
2836 m_reporter->Report( _( "The given footprint could not be found to export." ) + wxS( "\n" ),
2838 }
2839
2840 return CLI::EXIT_CODES::OK;
2841}
2842
2843
2845{
2846 wxFileName outputFile;
2847 outputFile.SetPath( aSvgJob->GetFullOutputPath( nullptr ) );
2848 outputFile.SetName( aFootprint->GetFPID().GetLibItemName().wx_str() );
2849 outputFile.SetExt( FILEEXT::SVGFileExtension );
2850
2851 m_reporter->Report( wxString::Format( _( "Plotting footprint '%s' to '%s'\n" ),
2852 aFootprint->GetFPID().GetLibItemName().wx_str(), outputFile.GetFullPath() ),
2854
2855 PCB_PLOT_PARAMS plotOpts;
2856 PCB_PLOTTER::PlotJobToPlotOpts( plotOpts, aSvgJob, *m_reporter );
2857
2858 if( !PlotFootprintToSVG( *aFootprint, *Pgm().GetSettingsManager().GetProject( "" ), &aSvgJob->GetVarOverrides(),
2859 plotOpts, aSvgJob->m_plotLayerSequence, aSvgJob->m_plotOnAllLayersSequence,
2860 outputFile.GetFullPath(), m_reporter ) )
2861 {
2862 m_reporter->Report( _( "Error creating svg file" ) + wxS( "\n" ), RPT_SEVERITY_ERROR );
2864 }
2865
2866 aSvgJob->AddOutput( outputFile.GetFullPath() );
2867
2868 return CLI::EXIT_CODES::OK;
2869}
2870
2871
2873{
2874 JOB_PCB_DRC* drcJob = dynamic_cast<JOB_PCB_DRC*>( aJob );
2875
2876 if( drcJob == nullptr )
2878
2879 BOARD* brd = getBoard( drcJob->m_filename );
2880
2881 if( !brd )
2883
2884 // Running DRC requires libraries be loaded, so make sure they have been
2886 adapter->AsyncLoad();
2887 adapter->BlockUntilLoaded();
2888
2889 if( drcJob->GetConfiguredOutputPath().IsEmpty() )
2890 {
2891 wxFileName fn = brd->GetFileName();
2892 fn.SetName( fn.GetName() + wxS( "-drc" ) );
2893
2895 fn.SetExt( FILEEXT::JsonFileExtension );
2896 else
2897 fn.SetExt( FILEEXT::ReportFileExtension );
2898
2899 drcJob->SetWorkingOutputPath( fn.GetFullName() );
2900 }
2901
2902 wxString outPath = resolveJobOutputPath( aJob, brd );
2903
2904 if( !PATHS::EnsurePathExists( outPath, true ) )
2905 {
2906 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
2908 }
2909
2910 EDA_UNITS units;
2911
2912 switch( drcJob->m_units )
2913 {
2914 case JOB_PCB_DRC::UNITS::INCH: units = EDA_UNITS::INCH; break;
2915 case JOB_PCB_DRC::UNITS::MILS: units = EDA_UNITS::MILS; break;
2916 case JOB_PCB_DRC::UNITS::MM: units = EDA_UNITS::MM; break;
2917 default: units = EDA_UNITS::MM; break;
2918 }
2919
2920 std::shared_ptr<DRC_ENGINE> drcEngine = brd->GetDesignSettings().m_DRCEngine;
2921 std::unique_ptr<NETLIST> netlist = std::make_unique<NETLIST>();
2922
2923 if( !drcEngine->RulesValid() )
2924 {
2925 try
2926 {
2927 drcEngine->InitEngine( brd->GetDesignRulesPath() );
2928 }
2929 catch( const PARSE_ERROR& error )
2930 {
2931 m_reporter->Report( _( "DRC incomplete: could not compile custom design rules." )
2932 + wxS( "\n" ) + error.What() + wxS( "\n" ),
2935 }
2936 }
2937
2938 drcEngine->SetDrawingSheet( getDrawingSheetProxyView( brd ) );
2939
2940 // BOARD_COMMIT uses TOOL_MANAGER to grab the board internally so we must give it one
2941 TOOL_MANAGER* toolManager = getToolManager( brd );
2942
2943 BOARD_COMMIT commit( toolManager );
2944 bool checkParity = drcJob->m_parity;
2945 std::string netlist_str;
2946
2947 if( checkParity )
2948 {
2949 wxString annotateMsg = _( "Schematic parity tests require a fully annotated schematic." );
2950 netlist_str = annotateMsg;
2951
2952 // The KIFACE_NETLIST_SCHEMATIC function has some broken-ness that the schematic
2953 // frame's version does not, but it is the only one that works in CLI, so we use it
2954 // if we don't have the sch frame open.
2955 // TODO: clean this up, see https://gitlab.com/kicad/code/kicad/-/issues/19929
2956 if( m_kiway->Player( FRAME_SCH, false ) )
2957 {
2958 m_kiway->ExpressMail( FRAME_SCH, MAIL_SCH_GET_NETLIST, netlist_str );
2959 }
2960 else
2961 {
2962 wxFileName schematicPath( drcJob->m_filename );
2963 schematicPath.MakeAbsolute();
2964 schematicPath.SetExt( FILEEXT::KiCadSchematicFileExtension );
2965
2966 if( !schematicPath.Exists() )
2967 schematicPath.SetExt( FILEEXT::LegacySchematicFileExtension );
2968
2969 if( !schematicPath.Exists() )
2970 {
2971 m_reporter->Report( _( "Failed to fetch schematic netlist for parity tests.\n" ), RPT_SEVERITY_ERROR );
2972 checkParity = false;
2973 }
2974 else
2975 {
2978
2979 if( netlister )
2980 ( *netlister )( schematicPath.GetFullPath(), netlist_str, m_kiway );
2981 }
2982 }
2983
2984 if( netlist_str == MAIL_SCH_GET_NETLIST_CANCELLED )
2985 {
2986 checkParity = false;
2987 }
2988 else if( netlist_str == annotateMsg )
2989 {
2990 m_reporter->Report( annotateMsg + wxT( "\n" ), RPT_SEVERITY_ERROR );
2991 checkParity = false;
2992 }
2993 }
2994
2995 if( checkParity )
2996 {
2997 try
2998 {
2999 STRING_LINE_READER* lineReader = new STRING_LINE_READER( netlist_str, _( "Eeschema netlist" ) );
3000 KICAD_NETLIST_READER netlistReader( lineReader, netlist.get() );
3001
3002 netlistReader.LoadNetlist();
3003 }
3004 catch( const IO_ERROR& )
3005 {
3006 m_reporter->Report( _( "Failed to fetch schematic netlist for parity tests.\n" ), RPT_SEVERITY_ERROR );
3007 checkParity = false;
3008 }
3009
3010 drcEngine->SetSchematicNetlist( netlist.get() );
3011 }
3012
3013 if( drcJob->m_refillZones )
3014 {
3015 if( !toolManager->FindTool( ZONE_FILLER_TOOL_NAME ) )
3016 toolManager->RegisterTool( new ZONE_FILLER_TOOL );
3017
3018 toolManager->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, m_progressReporter, true );
3019 }
3020
3021 drcEngine->SetProgressReporter( m_progressReporter );
3022 drcEngine->SetViolationHandler(
3023 [&]( const std::shared_ptr<DRC_ITEM>& aItem, const VECTOR2I& aPos, int aLayer,
3024 const std::function<void( PCB_MARKER* )>& aPathGenerator )
3025 {
3026 PCB_MARKER* marker = new PCB_MARKER( aItem, aPos, aLayer );
3027 aPathGenerator( marker );
3028 commit.Add( marker );
3029 } );
3030
3031 brd->RecordDRCExclusions();
3032 brd->DeleteMARKERs( true, true );
3033 drcEngine->RunTests( units, drcJob->m_reportAllTrackErrors, checkParity );
3034 drcEngine->ClearViolationHandler();
3035
3036 commit.Push( _( "DRC" ), SKIP_UNDO | SKIP_SET_DIRTY );
3037
3038 // Update the exclusion status on any excluded markers that still exist.
3039 brd->ResolveDRCExclusions( false );
3040
3041 std::shared_ptr<DRC_ITEMS_PROVIDER> markersProvider =
3042 std::make_shared<DRC_ITEMS_PROVIDER>( brd, MARKER_BASE::MARKER_DRC, MARKER_BASE::MARKER_DRAWING_SHEET );
3043
3044 std::shared_ptr<DRC_ITEMS_PROVIDER> ratsnestProvider =
3045 std::make_shared<DRC_ITEMS_PROVIDER>( brd, MARKER_BASE::MARKER_RATSNEST );
3046
3047 std::shared_ptr<DRC_ITEMS_PROVIDER> fpWarningsProvider =
3048 std::make_shared<DRC_ITEMS_PROVIDER>( brd, MARKER_BASE::MARKER_PARITY );
3049
3050 markersProvider->SetSeverities( drcJob->m_severity );
3051 ratsnestProvider->SetSeverities( drcJob->m_severity );
3052 fpWarningsProvider->SetSeverities( drcJob->m_severity );
3053
3054 m_reporter->Report( wxString::Format( _( "Found %d violations\n" ), markersProvider->GetCount() ),
3056 m_reporter->Report( wxString::Format( _( "Found %d unconnected items\n" ), ratsnestProvider->GetCount() ),
3058
3059 if( checkParity )
3060 {
3061 m_reporter->Report(
3062 wxString::Format( _( "Found %d schematic parity issues\n" ), fpWarningsProvider->GetCount() ),
3064 }
3065
3066 DRC_REPORT reportWriter( brd, units, markersProvider, ratsnestProvider, fpWarningsProvider );
3067
3068 bool wroteReport = false;
3069
3071 wroteReport = reportWriter.WriteJsonReport( outPath );
3072 else
3073 wroteReport = reportWriter.WriteTextReport( outPath );
3074
3075 if( !wroteReport )
3076 {
3077 m_reporter->Report( wxString::Format( _( "Unable to save DRC report to %s\n" ), outPath ), RPT_SEVERITY_ERROR );
3079 }
3080
3081 drcJob->AddOutput( outPath );
3082
3083 m_reporter->Report( wxString::Format( _( "Saved DRC Report to %s\n" ), outPath ), RPT_SEVERITY_ACTION );
3084
3085 if( drcJob->m_refillZones && drcJob->m_saveBoard )
3086 {
3087 if( BOARD_LOADER::SaveBoard( drcJob->m_filename, *brd ) )
3088 {
3089 m_reporter->Report( _( "Saved board\n" ), RPT_SEVERITY_ACTION );
3090 }
3091 else
3092 {
3093 m_reporter->Report( _( "Failed to save board.\n" ), RPT_SEVERITY_ERROR );
3094
3096 }
3097 }
3098
3099 if( drcJob->m_exitCodeViolations )
3100 {
3101 if( markersProvider->GetCount() > 0 || ratsnestProvider->GetCount() > 0 || fpWarningsProvider->GetCount() > 0 )
3102 {
3104 }
3105 }
3106
3108}
3109
3110
3112{
3113 if( !aJob.m_checkZonesBeforeExport )
3114 {
3115 return;
3116 }
3117
3118 TOOL_MANAGER* toolManager = getToolManager( aBoard );
3119
3120 if( !toolManager->FindTool( ZONE_FILLER_TOOL_NAME ) )
3121 {
3122 toolManager->RegisterTool( new ZONE_FILLER_TOOL );
3123 }
3124
3125 toolManager->GetTool<ZONE_FILLER_TOOL>()->FillAllZones( nullptr, m_progressReporter, true );
3126}
3127
3128
3130{
3131 JOB_EXPORT_PCB_IPC2581* job = dynamic_cast<JOB_EXPORT_PCB_IPC2581*>( aJob );
3132
3133 if( job == nullptr )
3135
3136 BOARD* brd = getBoard( job->m_filename );
3137
3138 if( !brd )
3140
3141 struct VARIANT_RESTORE
3142 {
3143 BOARD* m_board;
3144 wxString m_variant;
3145
3146 ~VARIANT_RESTORE() { m_board->SetCurrentVariant( m_variant ); }
3147 } restore{ brd, brd->GetCurrentVariant() };
3148
3149 if( !job->m_variantNames.empty() )
3150 brd->SetCurrentVariant( job->m_variantNames.front() );
3151
3152 if( job->GetConfiguredOutputPath().IsEmpty() )
3153 {
3154 wxFileName fn = brd->GetFileName();
3155 fn.SetExt( job->m_compress ? std::string( "zip" ) : FILEEXT::Ipc2581FileExtension );
3156
3157 job->SetWorkingOutputPath( fn.GetFullName() );
3158 }
3159
3160 wxString outPath = resolveJobOutputPath( aJob, brd );
3161
3162 if( !PATHS::EnsurePathExists( outPath, true ) )
3163 {
3164 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
3166 }
3167
3168 refillFabZones( *job, brd );
3169
3172
3174}
3175
3176
3178{
3179 JOB_EXPORT_PCB_IPCD356* job = dynamic_cast<JOB_EXPORT_PCB_IPCD356*>( aJob );
3180
3181 if( job == nullptr )
3183
3184 BOARD* brd = getBoard( job->m_filename );
3185
3186 if( !brd )
3188
3189 if( job->GetConfiguredOutputPath().IsEmpty() )
3190 {
3191 wxFileName fn = brd->GetFileName();
3192 fn.SetName( fn.GetName() );
3193 fn.SetExt( FILEEXT::IpcD356FileExtension );
3194
3195 job->SetWorkingOutputPath( fn.GetFullName() );
3196 }
3197
3198 wxString outPath = resolveJobOutputPath( aJob, brd );
3199
3200 if( !PATHS::EnsurePathExists( outPath, true ) )
3201 {
3202 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
3204 }
3205
3206 IPC356D_WRITER exporter( brd );
3207
3208 bool success = exporter.Write( outPath );
3209
3210 if( success )
3211 {
3212 aJob->AddOutput( outPath );
3213 m_reporter->Report( _( "Successfully created IPC-D-356 file\n" ), RPT_SEVERITY_INFO );
3215 }
3216 else
3217 {
3218 m_reporter->Report( _( "Failed to create IPC-D-356 file\n" ), RPT_SEVERITY_ERROR );
3220 }
3221}
3222
3223
3225{
3226 JOB_EXPORT_PCB_IDF* job = dynamic_cast<JOB_EXPORT_PCB_IDF*>( aJob );
3227
3228 if( job == nullptr )
3230
3231 BOARD* brd = getBoard( job->m_filename );
3232
3233 if( !brd )
3235
3236 if( job->GetConfiguredOutputPath().IsEmpty() )
3237 {
3238 wxFileName fn = brd->GetFileName();
3240
3241 job->SetWorkingOutputPath( fn.GetFullName() );
3242 }
3243
3244 wxString outPath = resolveJobOutputPath( job, brd );
3245
3246 if( !PATHS::EnsurePathExists( outPath, true ) )
3247 {
3248 m_reporter->Report( _( "Failed to create output directory\n" ), RPT_SEVERITY_ERROR );
3250 }
3251
3253
3254 if( !resolver )
3255 {
3256 m_reporter->Report( _( "Internal error\n" ), RPT_SEVERITY_ERROR );
3258 }
3259
3260 IDF_EXPORTER exporter( brd, resolver, job, m_reporter );
3261
3262 if( !exporter.Export( outPath ) )
3264
3265 m_reporter->Report( _( "Successfully created IDFv3 files\n" ), RPT_SEVERITY_INFO );
3266
3268}
3269
3270
3272{
3273 JOB_EXPORT_PCB_ODB* job = dynamic_cast<JOB_EXPORT_PCB_ODB*>( aJob );
3274
3275 if( job == nullptr )
3277
3278 BOARD* brd = getBoard( job->m_filename );
3279
3280 if( !brd )
3282
3283 if( job->GetConfiguredOutputPath().IsEmpty() )
3284 {
3286 {
3287 // just basic folder name
3288 job->SetWorkingOutputPath( "odb" );
3289 }
3290 else
3291 {
3292 wxFileName fn( brd->GetFileName() );
3293 fn.SetName( fn.GetName() + wxS( "-odb" ) );
3294
3295 switch( job->m_compressionMode )
3296 {
3298
3299 case JOB_EXPORT_PCB_ODB::ODB_COMPRESSION::TGZ: fn.SetExt( "tgz" ); break;
3300
3301 default: break;
3302 };
3303
3304 job->SetWorkingOutputPath( fn.GetFullName() );
3305 }
3306 }
3307
3308 resolveJobOutputPath( job, brd );
3309
3310 // The helper handles output path creation, so hand it a job that already has fully-resolved
3311 // token context (title block and project overrides applied above).
3312 refillFabZones( *job, brd );
3313
3315
3316 if( result.m_ok )
3317 {
3318 for( const wxString& path : result.m_outputs )
3319 aJob->AddOutput( path );
3320 }
3321
3322 if( !result.m_ok || m_reporter->HasMessageOfSeverity( RPT_SEVERITY_ERROR ) )
3324
3326}
3327
3329{
3330 JOB_PCB_UPGRADE* job = dynamic_cast<JOB_PCB_UPGRADE*>( aJob );
3331
3332 if( job == nullptr )
3334
3335 bool shouldSave = job->m_force;
3336
3337 try
3338 {
3340 BOARD* brd = getBoard( job->m_filename );
3341
3342 if( !brd )
3344
3346 shouldSave = true;
3347
3348 // A chart is derived data, so the upgrade brings every one up to date and saves if
3349 // that changed anything
3350 if( RefreshGeneratedTables( *brd ) > 0 )
3351 shouldSave = true;
3352
3353 if( shouldSave )
3354 {
3355 pi->SaveBoard( brd->GetFileName(), *brd );
3356 m_reporter->Report( _( "Successfully saved board file using the latest format\n" ), RPT_SEVERITY_INFO );
3357 }
3358 else
3359 {
3360 m_reporter->Report( _( "Board file was not updated\n" ), RPT_SEVERITY_ERROR );
3361 }
3362 }
3363 catch( const IO_ERROR& ioe )
3364 {
3365 wxString msg =
3366 wxString::Format( _( "Error saving board file '%s'.\n%s" ), job->m_filename, ioe.What().GetData() );
3367 m_reporter->Report( msg, RPT_SEVERITY_ERROR );
3369 }
3370
3372}
3373
3374
3375// Classify library footprints so their losses appear in the report.
3376static void classifyFootprintLibraries( const wxString& aDir, const DOWNGRADE_TARGET& aTarget,
3377 COMPATIBILITY_REPORT& aReport, bool aDropInsteadOfApproximate )
3378{
3379 wxArrayString files;
3380 wxDir::GetAllFiles( aDir, &files, wxT( "*.kicad_mod" ) );
3381
3382 for( const wxString& file : files )
3383 {
3384 if( IsDowngradeWorkingArtifact( file ) )
3385 continue;
3386
3387 try
3388 {
3389 PCB_IO_KICAD_SEXPR loader;
3390 wxString nameOut;
3391 std::unique_ptr<FOOTPRINT> fp = loader.ImportFootprint( file, nameOut );
3392
3393 if( !fp )
3394 continue;
3395
3396 BOARD scratch;
3397 scratch.Add( fp.release() );
3398
3399 aReport.Merge( ClassifyBoardForDowngrade( &scratch, aTarget, aDropInsteadOfApproximate ) );
3400 }
3401 catch( const IO_ERROR& )
3402 {
3403 // A footprint that fails to load is caught later by the downgrade pass itself.
3404 }
3405 }
3406}
3407
3408
3409// Downgrade every .kicad_mod under the folder in place. Returns the first file the target could
3410// not open, or empty when all are safe.
3411static wxString downgradeFootprintLibraries( const wxString& aDir, const DOWNGRADE_TARGET& aTarget,
3412 bool aDropInsteadOfApproximate,
3413 DOWNGRADE_FILE_TRANSACTION* aTransaction = nullptr,
3414 wxString* aRecoveryError = nullptr )
3415{
3416 auto convert = [&]( const wxString& aFile, const wxString& aTmp ) -> DOWNGRADE_FILE_RESULT
3417 {
3418 return DowngradeFootprintFileToTemp( aFile, aTmp, aTarget, aDropInsteadOfApproximate );
3419 };
3420
3422 aDir, wxT( "*.kicad_mod" ), aTarget.m_boardVersion,
3423 [&]( const wxString& aText )
3424 {
3425 return FindUnsupportedBoardToken( aText, aTarget );
3426 },
3427 convert, aTransaction, aRecoveryError );
3428}
3429
3430
3431static wxString footprintRefusedMessage( const wxString& aFile, const DOWNGRADE_TARGET& aTarget )
3432{
3433 return wxString::Format( _( "Cannot export: footprint '%s' uses a feature %s cannot open.\n" ), aFile,
3434 aTarget.m_name );
3435}
3436
3437
3439{
3440 JOB_PCB_DOWNGRADE* job = dynamic_cast<JOB_PCB_DOWNGRADE*>( aJob );
3441
3442 if( job == nullptr )
3444
3445 const DOWNGRADE_TARGET* target =
3446 job->m_target.IsEmpty() ? &GetDowngradeTargets().front() : FindDowngradeTarget( job->m_target );
3447
3448 if( target == nullptr )
3449 {
3450 m_reporter->Report( wxString::Format( _( "Unknown target version '%s'. Valid targets: %s\n" ), job->m_target,
3454 }
3455
3456 if( !job->m_libraryDir.IsEmpty() && !wxDirExists( job->m_libraryDir ) )
3457 {
3458 m_reporter->Report( wxString::Format( _( "The library folder '%s' does not exist.\n" ), job->m_libraryDir ),
3461 }
3462
3463 if( !job->m_variant.IsEmpty() && target->m_boardVersion >= FIRST_PCB_VARIANTS )
3464 {
3465 m_reporter->Report( _( "The target supports variants, so there is nothing to flatten.\n" ),
3468 }
3469
3470 wxString pathError;
3471 wxString libraryCopy;
3472
3473 if( !job->m_libraryDir.IsEmpty() && !ValidateDowngradeLibrarySource( job->m_libraryDir, pathError ) )
3474 {
3475 m_reporter->Report( pathError + wxT( "\n" ), RPT_SEVERITY_ERROR );
3477 }
3478
3479 if( !job->m_inPlace && !job->m_dryRun )
3480 {
3481 wxFileName output( job->m_outputFile );
3482
3483 if( !job->m_outputFile.IsEmpty() && output.MakeAbsolute() )
3484 job->m_outputFile = output.GetFullPath();
3485
3486 if( !ValidateFreshDowngradeOutput( job->m_outputFile, pathError ) )
3487 {
3488 m_reporter->Report( pathError + wxT( "\n" ), RPT_SEVERITY_ERROR );
3490 }
3491
3492 if( !job->m_libraryDir.IsEmpty() )
3493 {
3494 libraryCopy = DowngradeLibraryCopyPath( job->m_libraryDir, output.GetPath() );
3495
3496 if( libraryCopy.IsEmpty() || !ValidateDowngradeLibraryCopy( job->m_libraryDir, libraryCopy, pathError ) )
3497 {
3498 m_reporter->Report( pathError + wxT( "\n" ), RPT_SEVERITY_ERROR );
3500 }
3501 }
3502 }
3503
3504 try
3505 {
3506 if( !job->m_filename.IsEmpty() )
3507 {
3508 // Load a private copy, never the live editor board.
3509 PCB_IO_KICAD_SEXPR loader;
3510 std::unique_ptr<BOARD> brd( loader.LoadBoard( job->m_filename, nullptr ) );
3511
3512 if( !brd )
3514
3515 if( !job->m_variant.IsEmpty() )
3516 {
3517 const std::vector<wxString>& names = brd->GetVariantNames();
3518
3519 if( names.empty() )
3520 {
3521 // A board only learns variants from the netlist updater. Without any, the
3522 // flatten is vacuous, so a project export must not fail here after the
3523 // schematic side accepted the name.
3524 m_reporter->Report( _( "The board has no variant data. The base board is exported.\n" ),
3526 }
3527 else if( std::find( names.begin(), names.end(), job->m_variant ) == names.end() )
3528 {
3529 m_reporter->Report(
3530 wxString::Format( _( "The board has no variant named '%s'.\n" ), job->m_variant ),
3533 }
3534 else
3535 {
3536 FlattenBoardVariant( brd.get(), job->m_variant );
3537 }
3538 }
3539
3540 COMPATIBILITY_REPORT report =
3541 ClassifyBoardForDowngrade( brd.get(), *target, job->m_dropInsteadOfApproximate );
3542
3543 // Library losses belong in the report the user approves too.
3544 if( !job->m_libraryDir.IsEmpty() )
3546
3547 job->m_report = report;
3548
3549 report.Print( m_reporter );
3550
3551 if( job->m_dryRun )
3553
3554 if( report.IsBlocked() )
3555 {
3556 m_reporter->Report( _( "Cannot export: the board uses features the target cannot represent.\n" ),
3559 }
3560
3561 if( report.IsLossy() && !job->m_force )
3562 {
3563 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
3566 }
3567
3568 DOWNGRADE_OUTPUT_DIRECTORIES outputDirectories;
3569 wxString libraryDir = job->m_libraryDir;
3570
3571 if( !job->m_inPlace )
3572 {
3573 wxFileName output( job->m_outputFile );
3574 output.MakeAbsolute();
3575
3576 if( !outputDirectories.Create( output.GetPath() ) )
3577 {
3578 m_reporter->Report( _( "Could not create the output folder.\n" ), RPT_SEVERITY_ERROR );
3580 }
3581
3582 if( !libraryDir.IsEmpty() )
3583 {
3584 if( !CopyDowngradeLibraryDirectory( libraryDir, libraryCopy, outputDirectories, pathError ) )
3585 {
3586 m_reporter->Report( pathError + wxT( "\n" ), RPT_SEVERITY_ERROR );
3588 }
3589
3590 libraryDir = libraryCopy;
3591 }
3592 }
3593
3594 DOWNGRADE_FILE_TRANSACTION transaction;
3595 wxString stagedBoard = transaction.Stage( job->m_outputFile );
3596
3597 if( stagedBoard.IsEmpty() )
3598 {
3599 m_reporter->Report( _( "Could not export the downgraded board.\n" ), RPT_SEVERITY_ERROR );
3601 }
3602
3603 // The real export loads its own fresh copy and fails closed on any uncovered token.
3604 wxString badToken;
3605
3606 if( !ExportBoardToOlderVersion( job->m_filename, stagedBoard, *target, report, &badToken, job->m_variant,
3608 {
3609 if( !badToken.IsEmpty() )
3610 m_reporter->Report( wxString::Format( _( "Cannot export: the result still uses '%s', which %s "
3611 "cannot open. This feature has no downgrade rule yet.\n" ),
3612 badToken, target->m_name ),
3614 else
3615 m_reporter->Report( _( "Could not export the downgraded board.\n" ), RPT_SEVERITY_ERROR );
3616
3618 }
3619
3620 if( !job->m_libraryDir.IsEmpty() )
3621 {
3622 wxString badLib = downgradeFootprintLibraries( libraryDir, *target, job->m_dropInsteadOfApproximate,
3623 &transaction );
3624
3625 if( !badLib.IsEmpty() )
3626 {
3627 m_reporter->Report( footprintRefusedMessage( badLib, *target ), RPT_SEVERITY_ERROR );
3629 }
3630 }
3631
3632 wxString failedDestination = transaction.Commit();
3633
3634 if( !failedDestination.IsEmpty() )
3635 {
3636 m_reporter->Report( wxString::Format( _( "Could not replace '%s'.\n" ), failedDestination ),
3638
3639 if( !transaction.GetRecoveryError().IsEmpty() )
3640 m_reporter->Report( transaction.GetRecoveryError(), RPT_SEVERITY_ERROR );
3641
3643 }
3644
3645 outputDirectories.Commit();
3646 m_reporter->Report( wxString::Format( _( "Saved downgraded board to '%s'\n" ), job->m_outputFile ),
3648 }
3649 // Library-only mode. Fails closed if any library still uses a token the target cannot open.
3650 else if( !job->m_libraryDir.IsEmpty() )
3651 {
3652 if( !job->m_inPlace && !job->m_dryRun )
3653 {
3654 m_reporter->Report( _( "A board input is required for a library copy export.\n" ), RPT_SEVERITY_ERROR );
3656 }
3657
3658 if( !job->m_variant.IsEmpty() )
3659 {
3660 m_reporter->Report( _( "Variants do not apply to a library downgrade.\n" ), RPT_SEVERITY_ERROR );
3662 }
3663
3664 COMPATIBILITY_REPORT report;
3666 job->m_report = report;
3667 report.Print( m_reporter );
3668
3669 if( job->m_dryRun )
3671
3672 if( report.IsBlocked() )
3673 {
3674 m_reporter->Report( _( "Cannot export: the libraries use features the target cannot represent.\n" ),
3677 }
3678
3679 if( report.IsLossy() && !job->m_force )
3680 {
3681 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
3684 }
3685
3686 wxString recoveryError;
3687 wxString badLib = downgradeFootprintLibraries( job->m_libraryDir, *target, job->m_dropInsteadOfApproximate,
3688 nullptr, &recoveryError );
3689
3690 if( !badLib.IsEmpty() )
3691 {
3692 m_reporter->Report( footprintRefusedMessage( badLib, *target ), RPT_SEVERITY_ERROR );
3693
3694 if( !recoveryError.IsEmpty() )
3695 m_reporter->Report( recoveryError, RPT_SEVERITY_ERROR );
3696
3698 }
3699
3700 m_reporter->Report( _( "Downgraded footprint libraries\n" ), RPT_SEVERITY_INFO );
3701 }
3702 }
3703 catch( const IO_ERROR& ioe )
3704 {
3705 wxString where = job->m_filename.IsEmpty() ? _( "the footprint libraries" ) : job->m_filename;
3706
3707 m_reporter->Report( wxString::Format( _( "Error exporting '%s'.\n%s" ), where, ioe.What().GetData() ),
3710 }
3711
3713}
3714
3715
3717{
3718 JOB_FP_DOWNGRADE* job = dynamic_cast<JOB_FP_DOWNGRADE*>( aJob );
3719
3720 wxCHECK( job, CLI::EXIT_CODES::ERR_UNKNOWN );
3721
3722 const DOWNGRADE_TARGET* target =
3723 job->m_target.IsEmpty() ? &GetDowngradeTargets().front() : FindDowngradeTarget( job->m_target );
3724
3725 if( !target )
3726 {
3727 m_reporter->Report( wxString::Format( _( "Unknown target version '%s'. Valid targets: %s\n" ), job->m_target,
3731 }
3732
3733 if( !wxDirExists( job->m_libraryPath ) )
3734 {
3735 m_reporter->Report( wxString::Format( _( "The library folder '%s' does not exist.\n" ), job->m_libraryPath ),
3738 }
3739
3740 COMPATIBILITY_REPORT report;
3742 job->m_report = report;
3743 report.Print( m_reporter );
3744
3745 if( job->m_dryRun )
3747
3748 if( report.IsBlocked() )
3749 {
3750 m_reporter->Report( _( "Cannot export: the library uses features the target cannot represent.\n" ),
3753 }
3754
3755 if( report.IsLossy() && !job->m_force )
3756 {
3757 m_reporter->Report( _( "Export would lose data. Re-run with --force to export anyway.\n" ),
3760 }
3761
3762 wxString error;
3763 DOWNGRADE_OUTPUT_DIRECTORIES outputDirectories;
3764
3765 // The copy is validated, made and then converted, so a failure never reaches the original
3766 if( !CopyDowngradeLibraryDirectory( job->m_libraryPath, job->m_outputLibraryPath, outputDirectories, error ) )
3767 {
3768 m_reporter->Report( error + wxT( "\n" ), RPT_SEVERITY_ERROR );
3770 }
3771
3772 try
3773 {
3774 wxString recoveryError;
3775 wxString badLib = downgradeFootprintLibraries( job->m_outputLibraryPath, *target,
3776 job->m_dropInsteadOfApproximate, nullptr, &recoveryError );
3777
3778 if( !badLib.IsEmpty() )
3779 {
3780 m_reporter->Report( footprintRefusedMessage( badLib, *target ), RPT_SEVERITY_ERROR );
3781
3782 if( !recoveryError.IsEmpty() )
3783 m_reporter->Report( recoveryError, RPT_SEVERITY_ERROR );
3784
3786 }
3787 }
3788 catch( const IO_ERROR& ioe )
3789 {
3790 m_reporter->Report(
3791 wxString::Format( _( "Error exporting '%s'.\n%s" ), job->m_libraryPath, ioe.What().GetData() ),
3794 }
3795
3796 outputDirectories.Commit();
3797 m_reporter->Report( _( "Downgraded footprint library\n" ), RPT_SEVERITY_INFO );
3798
3800}
3801
3802
3803// Most job handlers need to align the running job with the board before resolving any
3804// output paths with variables in them like ${REVISION}.
3805wxString PCBNEW_JOBS_HANDLER::resolveJobOutputPath( JOB* aJob, BOARD* aBoard, const wxString* aDrawingSheet )
3806{
3807 aJob->SetTitleBlock( aBoard->GetTitleBlock() );
3808
3809 if( aDrawingSheet && !aDrawingSheet->IsEmpty() )
3810 loadOverrideDrawingSheet( aBoard, *aDrawingSheet );
3811
3812 PROJECT* project = aBoard->GetProject();
3813
3814 if( project )
3815 project->ApplyTextVars( aJob->GetVarOverrides() );
3816
3817 aBoard->SynchronizeProperties();
3818
3819 return aJob->GetFullOutputPath( project );
3820}
3821
3822
3824{
3825 DS_PROXY_VIEW_ITEM* drawingSheet = new DS_PROXY_VIEW_ITEM( pcbIUScale, &aBrd->GetPageSettings(), aBrd->GetProject(),
3826 &aBrd->GetTitleBlock(), &aBrd->GetProperties() );
3827
3828 drawingSheet->SetSheetName( std::string() );
3829 drawingSheet->SetSheetPath( std::string() );
3830 drawingSheet->SetIsFirstPage( true );
3831
3832 drawingSheet->SetFileName( TO_UTF8( aBrd->GetFileName() ) );
3833
3834 wxString currentVariant = aBrd->GetCurrentVariant();
3835 wxString variantDesc = aBrd->GetVariantDescription( currentVariant );
3836 drawingSheet->SetVariantName( TO_UTF8( currentVariant ) );
3837 drawingSheet->SetVariantDesc( TO_UTF8( variantDesc ) );
3838
3839 return drawingSheet;
3840}
3841
3842
3843void PCBNEW_JOBS_HANDLER::loadOverrideDrawingSheet( BOARD* aBrd, const wxString& aSheetPath )
3844{
3845 // dont bother attempting to load a empty path, if there was one
3846 if( aSheetPath.IsEmpty() )
3847 return;
3848
3849 auto loadSheet = [&]( const wxString& path ) -> bool
3850 {
3852 FILENAME_RESOLVER resolver;
3853 resolver.SetProject( aBrd->GetProject() );
3854 resolver.SetProgramBase( &Pgm() );
3855
3856 wxString filename = resolver.ResolvePath( BASE_SCREEN::m_DrawingSheetFileName,
3857 aBrd->GetProject()->GetProjectPath(), { aBrd->GetEmbeddedFiles() } );
3858 wxString msg;
3859
3860 if( !DS_DATA_MODEL::GetTheInstance().LoadDrawingSheet( filename, &msg ) )
3861 {
3862 m_reporter->Report( wxString::Format( _( "Error loading drawing sheet '%s'." ), path ) + wxS( "\n" ) + msg
3863 + wxS( "\n" ),
3865 return false;
3866 }
3867
3868 return true;
3869 };
3870
3871 if( loadSheet( aSheetPath ) )
3872 return;
3873
3874 // failed loading custom path, revert back to default
3875 loadSheet( aBrd->GetProject()->GetProjectFile().m_BoardDrawingSheetFile );
3876}
3877
3878
3879// Resolve a KiCad layer name (canonical board-file name such as "F.Cu", or the GUI display name)
3880// to its layer id. Returns UNDEFINED_LAYER when no layer matches.
3881static PCB_LAYER_ID resolveKiCadLayerName( const wxString& aName )
3882{
3883 for( PCB_LAYER_ID layer : LSET::AllLayersMask().Seq() )
3884 {
3885 if( LSET::Name( layer ) == aName || LayerName( layer ) == aName )
3886 return layer;
3887 }
3888
3889 return UNDEFINED_LAYER;
3890}
3891
3892
3894{
3895 JOB_PCB_IMPORT* job = dynamic_cast<JOB_PCB_IMPORT*>( aJob );
3896
3897 if( !job )
3899
3900 // Check that input file exists
3901 if( !wxFile::Exists( job->m_inputFile ) )
3902 {
3903 m_reporter->Report( wxString::Format( _( "Input file not found: '%s'\n" ), job->m_inputFile ),
3906 }
3907
3908 // Map job format to PCB_IO file type
3910
3911 switch( job->m_format )
3912 {
3915 break;
3916
3917 // "pads" names the vendor format, not the dialect: PADS writes both an ASCII export and a
3918 // binary PowerPCB database, and both use the .pcb extension. Resolve the dialect by content
3919 // so an explicit --format pads on a binary file imports it instead of handing it to the ASCII
3920 // reader, which parses nothing and silently yields an empty board.
3925 break;
3926
3935 }
3936
3937 // FindPluginTypeFromBoardPath returns FILE_TYPE_NONE (not PCB_FILE_UNKNOWN) when no plugin
3938 // claims the file. Quiet sentinel: lets the top-level `import` command try the schematic face.
3940 {
3941 m_reporter->Report( wxString::Format( _( "No PCB importer recognizes the file format of '%s'\n" ),
3942 job->m_inputFile ),
3945 }
3946
3947 if( job->m_probeOnly )
3948 {
3950
3951 if( !pi )
3952 {
3953 m_reporter->Report( wxString::Format( _( "No plugin found for file type '%s'\n" ),
3957 }
3958
3959 try
3960 {
3961 job->m_projectBoards = pi->EnumerateProjectBoards( job->m_inputFile );
3962 }
3963 catch( const IO_ERROR& ioe )
3964 {
3965 m_reporter->Report( wxString::Format( _( "Failed to inspect board project: %s\n" ), ioe.What() ),
3968 }
3969
3971 }
3972
3973
3974 // Determine output path
3975 wxString outputPath = job->GetConfiguredOutputPath();
3976
3977 if( outputPath.IsEmpty() )
3979
3980 // The generated footprint library and its table row belong to the *active* project, so an
3981 // import with no project loaded needs a transient active one at the output location (never
3982 // written to disk; LoadProject returns false yet still registers it, hence the GetProject()
3983 // check).
3985 PROJECT* projectPtr = nullptr;
3986 bool createdTransientProject = false;
3987
3988 if( mgr.IsProjectOpenNotDummy() )
3989 {
3990 projectPtr = &mgr.Prj();
3991 }
3992 else
3993 {
3994 wxFileName projectFn( outputPath );
3995 projectFn.SetExt( FILEEXT::ProjectFileExtension );
3996
3997 // PROJECT requires an absolute path; -o may be relative to the working directory
3998 projectFn.MakeAbsolute();
3999
4000 mgr.LoadProject( projectFn.GetFullPath(), true );
4001 projectPtr = mgr.GetProject( projectFn.GetFullPath() );
4002 createdTransientProject = ( projectPtr != nullptr );
4003 }
4004
4005 if( !projectPtr )
4006 {
4007 m_reporter->Report( _( "Could not establish a project for the import\n" ), RPT_SEVERITY_ERROR );
4009 }
4010
4011 // unloads the transient project on every exit path
4013 {
4014 SETTINGS_MANAGER& m_mgr;
4015 PROJECT* m_project;
4016 bool m_active;
4017
4019 {
4020 if( m_active )
4021 m_mgr.UnloadProject( m_project, false );
4022 }
4023 } transientProjectGuard{ mgr, projectPtr, createdTransientProject };
4024
4025 std::unique_ptr<BOARD> board;
4026
4027 struct BOARD_PROJECT_GUARD
4028 {
4029 std::unique_ptr<BOARD>& board;
4030
4031 ~BOARD_PROJECT_GUARD()
4032 {
4033 if( board )
4034 board->ClearProject();
4035 }
4036 } boardProjectGuard{ board };
4037
4038 wxString formatName = PCB_IO_MGR::ShowType( fileType );
4039 std::vector<wxString> warnings;
4040
4041 // Real source-to-KiCad layer decisions, captured by our mapping callback so the report can
4042 // show them and so explicit overrides can be validated.
4043 struct CAPTURED_LAYER
4044 {
4045 wxString m_source;
4046 PCB_LAYER_ID m_target;
4047 wxString m_method;
4048 };
4049
4050 std::vector<CAPTURED_LAYER> capturedLayers;
4051 std::set<wxString> seenSourceLayers;
4052 bool layersCaptured = false;
4053
4054 try
4055 {
4056 // Declared before the plugin so it outlives the plugin's pointer to it
4057 IMPORT_MESSAGE_COLLECTOR importMessages( *m_reporter );
4059
4060 if( !pi )
4061 {
4062 m_reporter->Report( wxString::Format( _( "No plugin found for file type '%s'\n" ), formatName ),
4065 }
4066
4067 // Without this the importer's warnings never reach the import report
4068 pi->SetReporter( &importMessages );
4069
4070 // Replace the plugin's default best-guess callback so we can apply explicit overrides and
4071 // capture the resulting mapping. Only mappable importers expose their source layers; for
4072 // others the report falls back to listing the imported board's enabled layers.
4073 if( LAYER_MAPPABLE_PLUGIN* mappable = dynamic_cast<LAYER_MAPPABLE_PLUGIN*>( pi.get() ) )
4074 {
4075 if( !job->m_layerMap.empty() || job->m_reportFormat != IMPORT_REPORT_FORMAT::NONE )
4076 {
4077 mappable->RegisterCallback(
4078 [&]( const std::vector<INPUT_LAYER_DESC>& aDescs )
4079 -> std::map<wxString, PCB_LAYER_ID>
4080 {
4081 std::map<wxString, PCB_LAYER_ID> result;
4082
4083 for( const INPUT_LAYER_DESC& desc : aDescs )
4084 {
4085 PCB_LAYER_ID target = desc.AutoMapLayer;
4086 wxString method = wxS( "auto" );
4087
4088 if( auto it = job->m_layerMap.find( desc.Name );
4089 it != job->m_layerMap.end() )
4090 {
4091 PCB_LAYER_ID resolved = resolveKiCadLayerName( it->second );
4092
4093 if( resolved == UNDEFINED_LAYER )
4094 {
4095 warnings.push_back( wxString::Format(
4096 _( "Layer map entry '%s' -> '%s' names an unknown "
4097 "KiCad layer; using automatic mapping instead" ),
4098 desc.Name, it->second ) );
4099 }
4100 else if( !desc.PermittedLayers.Contains( resolved ) )
4101 {
4102 warnings.push_back( wxString::Format(
4103 _( "Layer map entry '%s' -> '%s' is not a permitted "
4104 "target for this layer; using automatic mapping "
4105 "instead" ),
4106 desc.Name, it->second ) );
4107 }
4108 else
4109 {
4110 target = resolved;
4111 method = wxS( "explicit" );
4112 }
4113 }
4114
4115 if( desc.Required && target == UNDEFINED_LAYER )
4116 {
4117 warnings.push_back( wxString::Format(
4118 _( "No KiCad layer mapping for required source layer "
4119 "'%s'; its items will not be imported" ),
4120 desc.Name ) );
4121 }
4122
4123 result.emplace( desc.Name, target );
4124 capturedLayers.push_back( { desc.Name, target, method } );
4125 seenSourceLayers.insert( desc.Name );
4126 }
4127
4128 layersCaptured = true;
4129 return result;
4130 } );
4131 }
4132 }
4133 else if( !job->m_layerMap.empty() )
4134 {
4135 warnings.push_back( _( "A layer map was provided, but this importer does not support "
4136 "layer remapping; it will be ignored" ) );
4137 }
4138
4139 m_reporter->Report( wxString::Format( _( "Importing '%s' using %s format...\n" ),
4140 job->m_inputFile, formatName ),
4142
4143 // LoadBoard reports load failures and user cancellations by throwing.
4144 try
4145 {
4146 // pcb_id selects a board only within an EasyEDA Pro project. Other importers must
4147 // continue receiving no properties so their existing design-settings import paths remain
4148 // unchanged.
4149 const std::map<std::string, UTF8>* importProperties = nullptr;
4150 std::map<std::string, UTF8> importPropertyStorage;
4151
4153 {
4154 if( !job->m_importPcbId.empty() )
4155 {
4156 importPropertyStorage.emplace( "pcb_id", std::string( job->m_importPcbId.ToUTF8() ) );
4157 importProperties = &importPropertyStorage;
4158 }
4159 }
4160 else if( fileType == PCB_IO_MGR::EAGLE )
4161 {
4162 // PCB_IO_EAGLE uses these to center the BOARD
4163 PAGE_INFO defaultPaper;
4164 VECTOR2I pageSize = defaultPaper.GetSizeIU( pcbIUScale.IU_PER_MILS );
4165 importPropertyStorage["page_width"] = std::to_string( pageSize.x );
4166 importPropertyStorage["page_height"] = std::to_string( pageSize.y );
4167 importProperties = &importPropertyStorage;
4168 }
4169
4170
4171 board = pi->LoadBoard( job->m_inputFile, importProperties, projectPtr );
4172 }
4173 catch( const IO_CANCELLED& ioce )
4174 {
4175 // We should not be here, as the plugin should not have used an interactive dialog
4176 // in the CLI context.
4177 // But technically the file is not invalid
4178 m_reporter->Report( wxString::Format( _( "Unexpected cancellation: %s\n" ), ioce.What() ),
4181 }
4182 catch( const IO_ERROR& ioe )
4183 {
4184 m_reporter->Report( wxString::Format( _( "Failed to load board: %s\n" ), ioe.What() ), RPT_SEVERITY_ERROR );
4186 }
4187 board->SetProject( projectPtr, job->m_isPartOfMultiBoardProject );
4188
4189
4190
4191 if( !ApplyImportedNetNameMap( *board, job->m_netNameMap, *m_reporter ) )
4193
4194 // Extract a project footprint library and re-link FPIDs, as the board editor does.
4195 // Each EasyEDA Pro project board needs a distinct cache; using the archive name makes
4196 // every board compete to publish the same .pretty directory.
4198 {
4199 const wxString reconciliationPath = job->m_importPcbId.empty() ? job->m_inputFile : outputPath;
4200 ReconcileImportedFootprints( *pi, *board, *projectPtr, reconciliationPath, nullptr, *m_reporter );
4201 }
4202
4203 // Flag explicit map entries that never matched a source layer so typos do not pass silently.
4204 if( layersCaptured )
4205 {
4206 for( const auto& [source, target] : job->m_layerMap )
4207 {
4208 if( !seenSourceLayers.contains( source ) )
4209 {
4210 warnings.push_back( wxString::Format( _( "Layer map entry '%s' does not match any source layer "
4211 "in the imported file; it will be ignored" ),
4212 source ) );
4213 }
4214 }
4215 }
4216
4217 // Save as KiCad format
4218
4220 kicadPlugin->SaveBoard( outputPath, *board );
4221 wxString importedRules = pi->GetImportedDesignRules();
4222
4223 if( !importedRules.IsEmpty() )
4224 {
4225 wxFileName rulesPath( outputPath );
4226 rulesPath.SetExt( FILEEXT::DesignRulesFileExtension );
4227
4228 wxFile rulesFile( rulesPath.GetFullPath(), wxFile::write );
4229
4230 if( rulesFile.IsOpened() )
4231 {
4232 rulesFile.Write( importedRules );
4233 }
4234 else
4235 {
4236 m_reporter->Report( wxString::Format( _( "Could not write imported design rules to '%s'\n" ),
4237 rulesPath.GetFullPath() ),
4239 }
4240 }
4241
4242 m_reporter->Report( wxString::Format( _( "Successfully saved imported board to '%s'\n" ), outputPath ),
4244
4245 // Generate report if requested
4246 IMPORT_REPORT_DATA reportData;
4247 importMessages.Flush( job->m_reportFormat, reportData );
4248
4250 {
4251 reportData.m_sourceFile = wxFileName( job->m_inputFile ).GetFullName();
4252 reportData.m_sourceFormat = formatName;
4253 reportData.m_outputFile = wxFileName( outputPath ).GetFullName();
4254
4255 size_t trackCount = 0;
4256 size_t viaCount = 0;
4257
4258 for( PCB_TRACK* track : board->Tracks() )
4259 {
4260 if( track->Type() == PCB_VIA_T )
4261 viaCount++;
4262 else
4263 trackCount++;
4264 }
4265
4266 reportData.m_statistics = {
4267 { wxS( "footprints" ), board->Footprints().size() },
4268 { wxS( "tracks" ), trackCount },
4269 { wxS( "vias" ), viaCount },
4270 { wxS( "zones" ), board->Zones().size() }
4271 };
4272
4273 // Build layer mapping info, carried only in the JSON report. Prefer the real
4274 // source-to-KiCad decisions captured during load; fall back to the imported board's
4275 // enabled layers for importers that do not expose a mappable layer set.
4276 nlohmann::json layerMappings = nlohmann::json::object();
4277
4278 if( layersCaptured )
4279 {
4280 for( const CAPTURED_LAYER& mapped : capturedLayers )
4281 {
4282 std::string kicadLayer = mapped.m_target == UNDEFINED_LAYER
4283 ? std::string()
4284 : LSET::Name( mapped.m_target ).ToStdString();
4285
4286 layerMappings[mapped.m_source.ToStdString()] = {
4287 { "kicad_layer", kicadLayer },
4288 { "method", mapped.m_method.ToStdString() }
4289 };
4290 }
4291 }
4292 else
4293 {
4294 for( PCB_LAYER_ID layer : board->GetEnabledLayers().Seq() )
4295 {
4296 wxString layerName = board->GetLayerName( layer );
4297
4298 layerMappings[layerName.ToStdString()] = {
4299 { "kicad_layer", LSET::Name( layer ).ToStdString() },
4300 { "method", "auto" }
4301 };
4302 }
4303 }
4304
4305 reportData.m_extraJson["layer_mapping"] = layerMappings;
4306 reportData.m_warnings.insert( reportData.m_warnings.end(), warnings.begin(), warnings.end() );
4307
4308 if( !WriteImportReport( m_reporter, job->m_reportFormat, job->m_reportFile, reportData ) )
4310 }
4311 else
4312 {
4313 // No report requested, but explicit-mapping problems still need to surface.
4314 for( const wxString& warning : warnings )
4315 m_reporter->Report( warning + wxS( "\n" ), RPT_SEVERITY_WARNING );
4316 }
4317 }
4318 catch( const IO_ERROR& ioe )
4319 {
4320 m_reporter->Report( wxString::Format( _( "Error during import: %s\n" ), ioe.What() ), RPT_SEVERITY_ERROR );
4321
4323 }
4324
4326}
4327
4328
4329// ============================================================================
4330// JobDiff: pcb_diff implementation
4331// ============================================================================
4334#include <diff_merge/diff_scene.h>
4335#include <diff_merge/pcb_differ.h>
4337#include <jobs/job_pcb_diff.h>
4338
4339
4340// Load a board into a SCRATCH_DOC<BOARD> that keeps its project attached for
4341// the document's lifetime — the differ/applier read PROJECT_FILE-scoped fields
4342// (drawing-sheet path, DRC severities, net classes). The destructor severs the
4343// BOARD->project link in the right order. Used by every PCB diff/merge job.
4344static SCRATCH_DOC<BOARD> loadScratchBoard( SETTINGS_MANAGER& aMgr, const wxString& aPath,
4345 bool aInitializeAfterLoad = true )
4346{
4347 return LoadScratchDoc<BOARD>(
4348 aMgr, aPath,
4349 [aPath, aInitializeAfterLoad]( PROJECT* aProject ) -> std::unique_ptr<BOARD>
4350 {
4351 PCB_IO_MGR::PCB_FILE_T pluginType =
4353
4354 if( !aProject || pluginType == PCB_IO_MGR::FILE_TYPE_NONE )
4355 return nullptr;
4356
4358 opts.initialize_after_load = aInitializeAfterLoad;
4359
4360 try
4361 {
4362 return BOARD_LOADER::Load( aPath, pluginType, aProject, opts );
4363 }
4364 catch( ... )
4365 {
4366 return nullptr;
4367 }
4368 },
4369 []( BOARD* aBoard )
4370 {
4371 if( aBoard )
4372 aBoard->ClearProject();
4373 } );
4374}
4375
4376
4378{
4379 JOB_PCB_DIFF* diffJob = dynamic_cast<JOB_PCB_DIFF*>( aJob );
4380
4381 if( !diffJob )
4383
4384 // SCRATCH_DOC<BOARD> keeps each board's project attached for the lifetime
4385 // of the diff, which the differ needs to read project-file-scoped fields
4386 // (m_BoardDrawingSheetFile, etc). The previous loadStandaloneBoard +
4387 // ClearProject-up-front path would null those out before the differ ran.
4389
4390 SCRATCH_DOC<BOARD> aScratch = loadScratchBoard( diffMgr, diffJob->m_inputA );
4391 SCRATCH_DOC<BOARD> bScratch = loadScratchBoard( diffMgr, diffJob->m_inputB );
4392
4393 BOARD* boardA = aScratch.doc.get();
4394 BOARD* boardB = bScratch.doc.get();
4395
4396 if( !boardA )
4397 {
4398 m_reporter->Report( wxString::Format( _( "Failed to load %s\n" ), diffJob->m_inputA ), RPT_SEVERITY_ERROR );
4400 }
4401
4402 if( !boardB )
4403 {
4404 m_reporter->Report( wxString::Format( _( "Failed to load %s\n" ), diffJob->m_inputB ), RPT_SEVERITY_ERROR );
4406 }
4407
4408 KICAD_DIFF::PCB_DIFFER differ( boardA, boardB, diffJob->m_inputB );
4410
4411 int diffExitCode = KICAD_DIFF::DiffExitCode( result );
4412
4413 if( diffJob->m_exitCodeOnly )
4414 return diffExitCode;
4415
4416 // The board geometry rendered beneath the change overlay (PNG/SVG only)
4417 // matches what the interactive dialog draws.
4419 KICAD_DIFF::MakeEmitOptions( *diffJob, diffJob->m_inputA, diffJob->m_inputB );
4421 emitOpts.referenceGeometry = [&]( const KIGFX::COLOR4D& aColor )
4422 { return KICAD_DIFF::ExtractBoardGeometry( *boardA, aColor ); };
4423 emitOpts.comparisonGeometry = [&]( const KIGFX::COLOR4D& aColor )
4424 { return KICAD_DIFF::ExtractBoardGeometry( *boardB, aColor ); };
4425
4426 return KICAD_DIFF::EmitDiffResult( result, emitOpts, diffExitCode, *m_reporter );
4427}
4428
4429
4430// ============================================================================
4431// JobMerge: pcb_merge implementation
4432// ============================================================================
4440
4441
4442int PCBNEW_JOBS_HANDLER::RunMerge( KICAD_DIFF::DOC_KIND aKind, const wxString& aAncestor,
4443 const wxString& aOurs, const wxString& aTheirs,
4444 const wxString& aOutput, bool aInteractive, bool aSingleFile,
4445 REPORTER* aReporter )
4446{
4447 // Restore m_reporter on scope exit so a caller's transient (often
4448 // stack-local) reporter doesn't outlive this call as a dangling member.
4450 aReporter ? aReporter : m_reporter );
4451
4453 return runFpLibMerge( aAncestor, aOurs, aTheirs, aOutput, aInteractive, aSingleFile );
4454
4455 return runPcbMerge( aAncestor, aOurs, aTheirs, aOutput, aInteractive );
4456}
4457
4458
4459int PCBNEW_JOBS_HANDLER::runPcbMerge( const wxString& aAncestor, const wxString& aOurs,
4460 const wxString& aTheirs, const wxString& aOutput,
4461 bool aInteractive )
4462{
4463 // Use SCRATCH_DOC<BOARD> so each input keeps its project attached for the
4464 // life of the merge — necessary for any doc-level resolution that mutates
4465 // PROJECT_FILE-scoped state (DRC severities, net classes) and needs to be
4466 // saved as a sibling .kicad_pro. SCRATCH_DOC's destructor severs the
4467 // BOARD->project link in the right order and unloads the project from
4468 // the manager, avoiding the dangling-PROJECT_FILE::m_BoardSettings pointer
4469 // the previous up-front-ClearProject loadStandaloneBoard path had to
4470 // guard against.
4472
4473 SCRATCH_DOC<BOARD> ancestorScratch = loadScratchBoard( mgr, aAncestor );
4474 SCRATCH_DOC<BOARD> oursScratch = loadScratchBoard( mgr, aOurs );
4475 SCRATCH_DOC<BOARD> theirsScratch = loadScratchBoard( mgr, aTheirs );
4476
4477 BOARD* ancestor = ancestorScratch.doc.get();
4478 BOARD* ours = oursScratch.doc.get();
4479 BOARD* theirs = theirsScratch.doc.get();
4480
4481 if( !ancestor || !ours || !theirs )
4482 {
4483 m_reporter->Report( _( "Failed to load one or more input boards\n" ), RPT_SEVERITY_ERROR );
4485 }
4486
4487 const wxString formatNotice =
4490
4491 if( !formatNotice.IsEmpty() )
4492 m_reporter->Report( formatNotice + wxS( "\n" ), RPT_SEVERITY_WARNING );
4493
4494 KICAD_DIFF::PCB_DIFFER ourDiff( ancestor, ours );
4495 KICAD_DIFF::PCB_DIFFER theirDiff( ancestor, theirs );
4496
4497 KICAD_DIFF::DOCUMENT_DIFF ourDocDiff = ourDiff.Diff();
4498 KICAD_DIFF::DOCUMENT_DIFF theirDocDiff = theirDiff.Diff();
4499
4501 KICAD_DIFF::MERGE_PLAN plan = engine.Plan( ourDocDiff, theirDocDiff );
4502
4503 if( aInteractive && !KICAD_DIFF::BuildConflictList( plan ).empty() )
4504 {
4507
4508 // Geometry context so the conflict viewer can render the actual
4509 // boards behind the conflict bbox highlight.
4510 const KICAD_DIFF::DIFF_COLOR_THEME theme;
4512 ctx.formatNotice = formatNotice;
4516
4517 // Build per-side bbox lookups so a "moved on theirs" item highlights
4518 // at its theirs-side coordinates when the user previews Theirs.
4520 KICAD_DIFF::CollectChangeBBoxes( theirDocDiff, ctx.theirsBBoxes );
4521
4522 ctx.describeItem = [ours, theirs, ancestor]( const KIID_PATH& aId ) -> wxString
4523 {
4524 if( aId.empty() )
4525 return wxEmptyString;
4526
4528
4529 for( BOARD* board : { ours, theirs, ancestor } )
4530 {
4531 if( !board )
4532 continue;
4533
4534 if( BOARD_ITEM* item = board->ResolveItem( aId.back(), true ) )
4535 return item->GetItemDescription( &units, false );
4536 }
4537
4538 return wxEmptyString;
4539 };
4540
4541 ctx.drawSide = [ancestor, ours, theirs, theme]( WIDGET_DIFF_CANVAS& aCanvas,
4543 const std::optional<KIID_PATH>& )
4544 {
4545 BOARD* board = nullptr;
4546 KIGFX::COLOR4D colour = theme.reference;
4547
4548 switch( aSide )
4549 {
4550 case DIALOG_KICAD_MERGE_3WAY::SIDE::OURS: board = ours; break;
4551
4553 board = theirs;
4554 colour = theme.comparison;
4555 break;
4556
4557 case DIALOG_KICAD_MERGE_3WAY::SIDE::ANCESTOR: board = ancestor; break;
4558 }
4559
4560 if( board )
4561 KICAD_DIFF::ConfigurePcbDiffCanvasContext( aCanvas, board, nullptr, colour );
4562 };
4563
4564 DIALOG_KICAD_MERGE_3WAY dlg( wxTheApp->GetTopWindow(), plan, std::move( ctx ) );
4565
4566 // Cancelling leaves the conflicts unresolved and the files untouched.
4567 if( dlg.ShowModal() != wxID_APPLY )
4569
4570 plan = dlg.GetResolvedPlan();
4571 }
4572
4573 // Snapshot of the plan before the applier moves it; drives the
4574 // unresolved-conflict report below.
4575 const KICAD_DIFF::MERGE_PLAN planSnapshot = plan;
4576
4577 KICAD_DIFF::PCB_MERGE_APPLIER applier( ancestor, ours, theirs, std::move( plan ) );
4578 std::unique_ptr<BOARD> merged = applier.Apply();
4579
4580 if( !merged )
4581 {
4582 m_reporter->Report( _( "Merge applier failed to produce a board\n" ), RPT_SEVERITY_ERROR );
4584 }
4585
4586 // Serialize to the output path using the canonical PCB IO.
4587 PCB_IO_KICAD_SEXPR pcbIO;
4588
4589 try
4590 {
4591 pcbIO.SaveBoard( aOutput, *merged );
4592 }
4593 catch( const IO_ERROR& ioe )
4594 {
4595 m_reporter->Report( wxString::Format( _( "Failed to save merged board: %s\n" ), ioe.What() ),
4598 }
4599
4600 // BOARD_DESIGN_SETTINGS fields like m_DRCSeverities serialize to
4601 // .kicad_pro, not .kicad_pcb. Mirror only those specific fields onto
4602 // ancestor (still linked to its project via BOARD::SetProject) then
4603 // save ancestor's project alongside the merged board file. Whole-
4604 // BOARD_DESIGN_SETTINGS copy would alias shared_ptr<NET_SETTINGS>
4605 // across BOARDs and crash on ClearProject during SCRATCH_DOC release;
4606 // single-field mirror avoids that.
4607 if( applier.GetReport().projectFileTouched && ancestor && ancestor->GetProject() )
4608 {
4609 ancestor->GetDesignSettings().m_DRCSeverities = merged->GetDesignSettings().m_DRCSeverities;
4610
4611 // Mirror net settings (the applier copied them onto the result via
4612 // NET_SETTINGS::CopyFrom; do the same here to ancestor, which still
4613 // owns the project's nested-settings registration so SaveProjectCopy
4614 // walks the right entry).
4615 if( ancestor->GetDesignSettings().m_NetSettings && merged->GetDesignSettings().m_NetSettings )
4616 {
4617 ancestor->GetDesignSettings().m_NetSettings->CopyFrom( *merged->GetDesignSettings().m_NetSettings );
4618 }
4619
4620 // The applier stages drawing-sheet resolutions on the report (the
4621 // result BOARD is project-less). Mirror onto ancestor's project here
4622 // before SaveProjectCopy walks the PROJECT_FILE.
4623 if( applier.GetReport().drawingSheetFileSet )
4624 {
4626 }
4627
4628 wxFileName proFn( aOutput );
4629 proFn.SetExt( FILEEXT::ProjectFileExtension );
4630
4631 // JSON-patch path: flush ancestor's in-memory project to its JSON
4632 // cache, then patch only the diffed DOC_PROP fields onto the output
4633 // file. This preserves any non-diffed fields the user had at the
4634 // output path (text variables, last paths, layer presets etc.) that
4635 // a full SaveProjectCopy would silently overwrite.
4636 PROJECT_FILE& ancProj = ancestor->GetProject()->GetProjectFile();
4637 ancProj.Store();
4638
4639 const KICAD_DIFF::PCB_MERGE_APPLIER::REPORT& mergeReport = applier.GetReport();
4640
4641 // PROJECT_FILE::Store() flushes the project file's own params but not
4642 // its registered NESTED_SETTINGS. Flush only the nested settings the
4643 // merge resolved so the surgical patch does not overwrite unrelated
4644 // project subtrees.
4645 if( mergeReport.drcSeveritiesTouched )
4646 ancestor->GetDesignSettings().SaveToFile( wxEmptyString, true );
4647
4648 if( mergeReport.netClassesTouched && ancestor->GetDesignSettings().m_NetSettings )
4649 ancestor->GetDesignSettings().m_NetSettings->SaveToFile( wxEmptyString, true );
4650
4651 std::set<wxString> touched;
4652 if( mergeReport.drcSeveritiesTouched )
4653 touched.insert( KICAD_DIFF::DOC_PROP_DRC_SEVERITIES );
4654
4655 if( mergeReport.netClassesTouched )
4656 touched.insert( KICAD_DIFF::DOC_PROP_NET_CLASSES );
4657
4658 if( applier.GetReport().drawingSheetFileSet )
4659 touched.insert( KICAD_DIFF::DOC_PROP_DRAWING_SHEET );
4660
4661 if( !KICAD_DIFF::ApplyProjectFilePatches( proFn.GetFullPath(), *ancProj.Internals(), touched ) )
4662 {
4663 // Patch failed (existing output unparseable or write error).
4664 // Fall back to the legacy full-copy path so the user still gets
4665 // a project file even if it overwrites non-diffed customisations.
4666 if( !mgr.SaveProjectCopy( proFn.GetFullPath(), ancestor->GetProject() ) )
4667 {
4668 m_reporter->Report(
4669 wxString::Format( _( "Failed to save merged project file: %s\n" ), proFn.GetFullPath() ),
4672 }
4673 }
4674
4675 // Write a project-dir sibling file from staged report content. Empty
4676 // content removes the file so a TAKE_ANCESTOR resolution against an
4677 // ancestor with no file clears stale content at the output path.
4678 auto writeStagedFile = [&]( const wxString& aPath, const wxString& aContent, const wxString& aLabel ) -> bool
4679 {
4680 if( aContent.IsEmpty() )
4681 {
4682 if( wxFileExists( aPath ) )
4683 wxRemoveFile( aPath );
4684
4685 return true;
4686 }
4687
4688 wxFile out;
4689
4690 if( !out.Open( aPath, wxFile::write ) || !out.Write( aContent ) )
4691 {
4692 m_reporter->Report( wxString::Format( _( "Failed to save merged %s: %s\n" ), aLabel, aPath ),
4694 return false;
4695 }
4696
4697 return true;
4698 };
4699
4700 // Custom DRC rules: write the applier's staged content next to the
4701 // merged board so the chosen side's rules apply at next DRC run.
4702 if( applier.GetReport().customDrcRulesSet )
4703 {
4704 wxFileName druFn( aOutput );
4705 druFn.SetExt( FILEEXT::DesignRulesFileExtension );
4706
4707 if( !writeStagedFile( druFn.GetFullPath(), applier.GetReport().customDrcRules, _( "custom DRC rules" ) ) )
4708 {
4710 }
4711 }
4712
4713 // Footprint / symbol library tables: write into the merged project
4714 // directory. Both files have no extension.
4715 if( applier.GetReport().fpLibTableSet )
4716 {
4717 wxFileName fpFn( aOutput );
4718 fpFn.SetFullName( wxString::FromUTF8( FILEEXT::FootprintLibraryTableFileName ) );
4719
4720 if( !writeStagedFile( fpFn.GetFullPath(), applier.GetReport().fpLibTable, _( "footprint library table" ) ) )
4721 {
4723 }
4724 }
4725
4726 if( applier.GetReport().symLibTableSet )
4727 {
4728 wxFileName symFn( aOutput );
4729 symFn.SetFullName( wxString::FromUTF8( FILEEXT::SymbolLibraryTableFileName ) );
4730
4731 if( !writeStagedFile( symFn.GetFullPath(), applier.GetReport().symLibTable, _( "symbol library table" ) ) )
4732 {
4734 }
4735 }
4736 }
4737
4738 // Surface post-apply validator findings (refdes collisions, schema
4739 // mismatch, missed connectivity rebuild). Advisory — they do not change the
4740 // exit code, only the merge's resolved/unresolved status does.
4742 m_reporter->Report( wxString::Format( wxS( "%s: %s\n" ), f.validator, f.message ), f.severity );
4743
4744 // The merged board was written to m_outputPath above, so the output is
4745 // always a valid file. Unresolved conflicts are reported and signalled via
4746 // the exit code; the user resolves them with the interactive mergetool.
4747 if( !planSnapshot.Resolved() )
4748 {
4749 m_reporter->Report( wxString::Format( _( "Merge completed with %zu unresolved conflict(s) in %s\n" ),
4750 planSnapshot.ConflictCount(), aOutput ),
4753 }
4754
4756}
4757
4758
4759// ============================================================================
4760// JobFpDiff: fp_diff implementation
4761// ============================================================================
4763#include <jobs/job_fp_diff.h>
4764
4765
4766// Load one side of a footprint-library diff into its owner vector and name map.
4767// When aAllowEmpty is set an empty path resolves to a clean (empty) side; the
4768// non-interactive job path leaves it unset so a missing path is an input error.
4769static int loadFootprintLibrarySide( const wxString& aPath,
4770 std::vector<std::unique_ptr<FOOTPRINT>>& aOwners,
4771 KICAD_DIFF::FP_LIB_DIFFER::FOOTPRINT_MAP& aMap, bool aAllowEmpty,
4772 REPORTER& aReporter )
4773{
4774 if( aAllowEmpty && aPath.IsEmpty() )
4776
4777 try
4778 {
4779 auto loaded = KICAD_DIFF::FP_LIB_DIFFER::LoadLibrary( aPath );
4780 aOwners = std::move( loaded.first );
4781 aMap = std::move( loaded.second );
4783 }
4784 catch( const IO_ERROR& ioe )
4785 {
4786 aReporter.Report( wxString::Format( _( "Failed to load %s: %s\n" ), aPath, ioe.What() ),
4788 }
4789 catch( const std::exception& e )
4790 {
4791 aReporter.Report(
4792 wxString::Format( _( "Failed to load %s: %s\n" ), aPath, wxString::FromUTF8( e.what() ) ),
4794 }
4795
4797}
4798
4799
4801{
4802 JOB_FP_DIFF* diffJob = dynamic_cast<JOB_FP_DIFF*>( aJob );
4803
4804 if( !diffJob )
4806
4807 wxFileName dirA( diffJob->m_inputA );
4808 dirA.MakeAbsolute();
4809 wxFileName dirB( diffJob->m_inputB );
4810 dirB.MakeAbsolute();
4811
4812 std::vector<std::unique_ptr<FOOTPRINT>> ownersA;
4813 std::vector<std::unique_ptr<FOOTPRINT>> ownersB;
4816
4817 if( int rc = loadFootprintLibrarySide( dirA.GetFullPath(), ownersA, mapA, false, *m_reporter );
4819 {
4820 return rc;
4821 }
4822
4823 if( int rc = loadFootprintLibrarySide( dirB.GetFullPath(), ownersB, mapB, false, *m_reporter );
4825 {
4826 return rc;
4827 }
4828
4829 KICAD_DIFF::FP_LIB_DIFFER differ( mapA, mapB, diffJob->m_inputB );
4831
4832 int diffExitCode = KICAD_DIFF::DiffExitCode( result );
4833
4834 if( diffJob->m_exitCodeOnly )
4835 return diffExitCode;
4836
4838 KICAD_DIFF::MakeEmitOptions( *diffJob, diffJob->m_inputA, diffJob->m_inputB );
4840 emitOpts.referenceGeometry = [&]( const KIGFX::COLOR4D& aColor )
4841 { return KICAD_DIFF::ExtractFootprintGeometry( mapA, aColor ); };
4842 emitOpts.comparisonGeometry = [&]( const KIGFX::COLOR4D& aColor )
4843 { return KICAD_DIFF::ExtractFootprintGeometry( mapB, aColor ); };
4844
4845 return KICAD_DIFF::EmitDiffResult( result, emitOpts, diffExitCode, *m_reporter );
4846}
4847
4848
4849// ============================================================================
4850// JobOpenDiffDialog: load two on-disk files and open DIALOG_KICAD_DIFF.
4851// Dispatched from the project manager / PR-review dialog via KIWAY.
4852// ============================================================================
4857#include <jobs/scratch_doc.h>
4858
4859
4860// Both boards of a diff, kept while the caller draws them.
4871
4872
4873static int loadPcbDiffSides( SETTINGS_MANAGER& aMgr, REPORTER& aReporter, const wxString& aFileA,
4874 const wxString& aFileB, PCB_DIFF_SIDES& aSides )
4875{
4876 aSides.a = loadScratchBoard( aMgr, aFileA, /* aInitializeAfterLoad */ false );
4877 aSides.b = loadScratchBoard( aMgr, aFileB, /* aInitializeAfterLoad */ false );
4878
4879 if( !aSides.a.doc && !aFileA.IsEmpty() )
4880 {
4881 aReporter.Report( wxString::Format( _( "Failed to load %s\n" ), aFileA ), RPT_SEVERITY_ERROR );
4883 }
4884
4885 if( !aSides.b.doc && !aFileB.IsEmpty() )
4886 {
4887 aReporter.Report( wxString::Format( _( "Failed to load %s\n" ), aFileB ), RPT_SEVERITY_ERROR );
4889 }
4890
4891 // An ADDED or REMOVED side is an empty board, so the differ still produces a per-item
4892 // list rather than failing on an empty input file.
4893 aSides.boardA = aSides.a.doc ? aSides.a.doc.get() : &aSides.emptyA;
4894 aSides.boardB = aSides.b.doc ? aSides.b.doc.get() : &aSides.emptyB;
4895
4896 KICAD_DIFF::PCB_DIFFER differ( aSides.boardA, aSides.boardB, aFileB );
4897 aSides.diff = differ.Diff();
4898
4900}
4901
4902
4903// The two boards a window outside the kiface shows, taken off their canvases before they go.
4905{
4906public:
4908 m_before( aBefore ),
4909 m_after( aAfter )
4910 {
4911 }
4912
4914 {
4915 m_before->SetContextItems( {} );
4916 m_after->SetContextItems( {} );
4917 }
4918
4920
4921private:
4924};
4925
4926
4928PCBNEW_JOBS_HANDLER::AttachDiffCanvases( KICAD_DIFF::DOC_KIND aKind, const wxString& aFileA, const wxString& aFileB,
4929 WIDGET_DIFF_CANVAS* aBefore, WIDGET_DIFF_CANVAS* aAfter,
4930 KICAD_DIFF::DOCUMENT_DIFF& aDiff, REPORTER* aReporter )
4931{
4932 SCOPED_SET_RESET<REPORTER*> reporterGuard( m_reporter, aReporter ? aReporter : m_reporter );
4933
4934 if( aKind != KICAD_DIFF::DOC_KIND::PCB )
4935 return nullptr;
4936
4937 auto context = std::make_unique<PCB_DIFF_CANVAS_CONTEXT>( aBefore, aAfter );
4938
4939 if( loadPcbDiffSides( Pgm().GetSettingsManager(), *m_reporter, aFileA, aFileB, context->m_sides )
4941 {
4942 return nullptr;
4943 }
4944
4945 const KICAD_DIFF::DIFF_COLOR_THEME theme;
4946
4947 KICAD_DIFF::ConfigurePcbDiffCanvasContext( *aBefore, context->m_sides.boardA, nullptr, theme.reference, {}, {},
4948 {} );
4949 KICAD_DIFF::ConfigurePcbDiffCanvasContext( *aAfter, nullptr, context->m_sides.boardB, theme.reference, {}, {}, {} );
4950
4951 aDiff = context->m_sides.diff;
4952 return context.release();
4953}
4954
4955
4957 const wxString& aFileB, const wxString& aLabelA,
4958 const wxString& aLabelB, wxWindow* aParent,
4959 REPORTER* aReporter )
4960{
4961 // Restore m_reporter on scope exit so a caller's transient (often
4962 // stack-local) reporter doesn't outlive this call as a dangling member.
4964 aReporter ? aReporter : m_reporter );
4965
4966 wxWindow* parent = aParent ? aParent : ( wxTheApp ? wxTheApp->GetTopWindow() : nullptr );
4967
4969
4970 const wxString labelA = aLabelA.IsEmpty() ? aFileA : aLabelA;
4971 const wxString labelB = aLabelB.IsEmpty() ? aFileB : aLabelB;
4972
4973 std::vector<std::unique_ptr<FOOTPRINT>> ownersA;
4974 std::vector<std::unique_ptr<FOOTPRINT>> ownersB;
4977
4978 switch( aKind )
4979 {
4981 {
4982 PCB_DIFF_SIDES sides;
4983
4984 if( int rc = loadPcbDiffSides( mgr, *m_reporter, aFileA, aFileB, sides ); rc != CLI::EXIT_CODES::SUCCESS )
4985 return rc;
4986
4987 BOARD* boardA = sides.boardA;
4988 BOARD* boardB = sides.boardB;
4989
4990 // Background geometry, so the dialog's canvas shows the board outline and footprints
4991 // beneath the change rectangles.
4992 const KICAD_DIFF::DIFF_COLOR_THEME theme;
4993
4995 parent, labelA, labelB, sides.diff, KICAD_DIFF::ExtractBoardGeometry( *boardA, theme.reference ),
4997 [boardA, boardB, color = theme.reference]( WIDGET_DIFF_CANVAS& aCanvas, const KIID_PATH& )
4998 {
4999 KICAD_DIFF::ConfigurePcbDiffCanvasContext( aCanvas, boardA, boardB, color );
5000 } );
5001 dlg.ShowModal();
5002
5004 }
5006 {
5007 if( int rc = loadFootprintLibrarySide( aFileA, ownersA, mapA, true, *m_reporter );
5009 {
5010 return rc;
5011 }
5012
5013 if( int rc = loadFootprintLibrarySide( aFileB, ownersB, mapB, true, *m_reporter );
5015 {
5016 return rc;
5017 }
5018
5019 break;
5020 }
5022 {
5023 const wxString nameA = wxFileName( aFileA ).GetName();
5024 const wxString nameB = wxFileName( aFileB ).GetName();
5025 const wxString itemName = !nameB.IsEmpty() ? nameB : nameA;
5026
5027 auto loadSide = [&]( const wxString& aPath, std::vector<std::unique_ptr<FOOTPRINT>>& aOwners,
5029 {
5030 if( aPath.IsEmpty() )
5031 return true;
5032
5033 wxFileName fn( aPath );
5034 fn.MakeAbsolute();
5035
5036 try
5037 {
5038 // The footprint name inside a .kicad_mod need not match its filename
5040 wxString name;
5041
5042 if( std::unique_ptr<FOOTPRINT> footprint = io.ImportFootprint( fn.GetFullPath(), name ) )
5043 {
5044 aMap[itemName] = footprint.get();
5045 aOwners.push_back( std::move( footprint ) );
5046 }
5047
5048 return true;
5049 }
5050 catch( const IO_ERROR& ioe )
5051 {
5052 m_reporter->Report( wxString::Format( _( "Failed to load %s: %s\n" ), aPath, ioe.What() ),
5054 return false;
5055 }
5056 };
5057
5058 if( !loadSide( aFileA, ownersA, mapA ) || !loadSide( aFileB, ownersB, mapB ) )
5060
5061 break;
5062 }
5063 default:
5064 m_reporter->Report( _( "Unsupported document kind for this dispatcher.\n" ), RPT_SEVERITY_ERROR );
5066 }
5067
5068 KICAD_DIFF::FP_LIB_DIFFER differ( mapA, mapB, aFileB );
5070
5071 const KICAD_DIFF::DIFF_COLOR_THEME theme;
5072
5073 DIALOG_KICAD_DIFF dlg( parent, labelA, labelB, result,
5076
5078 [&]( WIDGET_DIFF_CANVAS& aCanvas, const wxString& aName )
5079 {
5080 KICAD_DIFF::ShowFootprintPair( aCanvas, mapA, mapB, aName );
5081 } );
5082
5083 dlg.ShowModal();
5084
5086}
5087
5088
5089// ============================================================================
5090// JobFpLibMerge: 3-way merge of .pretty footprint libraries.
5091// ============================================================================
5094
5095
5096int PCBNEW_JOBS_HANDLER::runFpLibMerge( const wxString& aAncestor, const wxString& aOurs,
5097 const wxString& aTheirs, const wxString& aOutput,
5098 bool aInteractive, bool aSingleFile )
5099{
5100 if( aOutput.IsEmpty() )
5101 {
5102 m_reporter->Report( _( "--output is required\n" ), RPT_SEVERITY_ERROR );
5104 }
5105
5106 struct LIB_SIDE
5107 {
5108 std::vector<std::unique_ptr<FOOTPRINT>> owners;
5110 };
5111
5112 LIB_SIDE ancestor, ours, theirs;
5113
5114 // Accept either a `.pretty` directory (library mode) or a single `.kicad_
5115 // mod` file (git's per-file driver mode). Extension autodetection works
5116 // for native invocations, but git's external driver passes temp paths
5117 // (`.merge_file_XXX`) with no extension, so the `--single-file` flag
5118 // overrides on demand.
5119 auto isSingleFile = [&]( const wxString& aPath )
5120 {
5121 if( aSingleFile )
5122 return true;
5123
5124 return wxFileName( aPath ).GetExt() == FILEEXT::KiCadFootprintFileExtension;
5125 };
5126
5127 auto loadSide = [&]( const wxString& aPath, LIB_SIDE& aSide ) -> int
5128 {
5129 try
5130 {
5131 if( isSingleFile( aPath ) )
5132 {
5134 wxString name;
5135 std::unique_ptr<FOOTPRINT> fp = io.ImportFootprint( aPath, name );
5136
5137 if( !fp )
5139
5140 // Use the footprint's own item-name (LIB_ID) if set,
5141 // falling back to the file basename. Both sides must
5142 // agree for the differ/applier to align them.
5143 const UTF8& itemName = fp->GetFPID().GetLibItemName();
5144 const wxString key = itemName.empty() ? name : itemName.wx_str();
5145
5146 aSide.map[key] = fp.get();
5147 aSide.owners.push_back( std::move( fp ) );
5149 }
5150
5151 auto loaded = KICAD_DIFF::FP_LIB_DIFFER::LoadLibrary( aPath );
5152 aSide.owners = std::move( loaded.first );
5153 aSide.map = std::move( loaded.second );
5155 }
5156 catch( const IO_ERROR& ioe )
5157 {
5158 m_reporter->Report( wxString::Format( _( "Failed to load %s: %s\n" ), aPath, ioe.What() ),
5160 }
5161 catch( const std::exception& e )
5162 {
5163 m_reporter->Report(
5164 wxString::Format( _( "Failed to load %s: %s\n" ), aPath, wxString::FromUTF8( e.what() ) ),
5166 }
5167
5169 };
5170
5171 if( int rc = loadSide( aAncestor, ancestor ); rc != CLI::EXIT_CODES::SUCCESS )
5172 return rc;
5173
5174 if( int rc = loadSide( aOurs, ours ); rc != CLI::EXIT_CODES::SUCCESS )
5175 return rc;
5176
5177 if( int rc = loadSide( aTheirs, theirs ); rc != CLI::EXIT_CODES::SUCCESS )
5178 return rc;
5179
5180 KICAD_DIFF::FP_LIB_DIFFER ourDiff( ancestor.map, ours.map, aOurs );
5181 KICAD_DIFF::FP_LIB_DIFFER theirDiff( ancestor.map, theirs.map, aTheirs );
5182
5183 KICAD_DIFF::DOCUMENT_DIFF ourDocDiff = ourDiff.Diff();
5184 KICAD_DIFF::DOCUMENT_DIFF theirDocDiff = theirDiff.Diff();
5185
5187 KICAD_DIFF::MERGE_PLAN plan = engine.Plan( ourDocDiff, theirDocDiff );
5188
5189 // Footprint edits are never combined, so one edited on both sides stays a conflict
5191 plan,
5192 []( const KIID_PATH& )
5193 {
5194 return false;
5195 },
5196 KICAD_DIFF::EditedNamesIn( ourDocDiff, theirDocDiff ) );
5197
5198 if( aInteractive && !KICAD_DIFF::BuildConflictList( plan ).empty() )
5199 {
5202
5203 std::set<wxString> names;
5204
5205 for( const KICAD_DIFF::FP_LIB_DIFFER::FOOTPRINT_MAP* side : { &ancestor.map, &ours.map, &theirs.map } )
5206 {
5207 for( const auto& [name, footprint] : *side )
5208 names.insert( name );
5209 }
5210
5211 // Each side is drawn over the common version so its own edits stand out
5213 names,
5214 [&]( WIDGET_DIFF_CANVAS& aCanvas, DIALOG_KICAD_MERGE_3WAY::SIDE aSide, const wxString& aName )
5215 {
5216 const KICAD_DIFF::FP_LIB_DIFFER::FOOTPRINT_MAP* side = &ours.map;
5217
5219 side = &theirs.map;
5220 else if( aSide == DIALOG_KICAD_MERGE_3WAY::SIDE::ANCESTOR )
5221 side = &ancestor.map;
5222
5223 KICAD_DIFF::ShowFootprintPair( aCanvas, ancestor.map, *side, aName );
5224 } );
5225
5226 DIALOG_KICAD_MERGE_3WAY dlg( wxTheApp->GetTopWindow(), plan, std::move( ctx ) );
5227
5228 // Cancelling leaves the conflicts unresolved and the files untouched
5229 if( dlg.ShowModal() != wxID_APPLY )
5231
5232 plan = dlg.GetResolvedPlan();
5233 }
5234
5235 const KICAD_DIFF::MERGE_PLAN planSnapshot = plan;
5236
5237 KICAD_DIFF::FP_LIB_MERGE_APPLIER applier( ancestor.map, ours.map, theirs.map, std::move( plan ) );
5238 std::vector<std::unique_ptr<FOOTPRINT>> merged = applier.Apply();
5239
5240 // Per-property footprint merge isn't implemented; MERGE_PROPS resolutions
5241 // are downgraded to TAKE_OURS. Surface that as unresolved so the user sees
5242 // a marker instead of silent partial-merge.
5243 const bool hadSilentFallback = applier.GetReport().mergePropsFallback > 0;
5244
5245 const bool singleFileOutput = isSingleFile( aOutput );
5246
5247 // .pretty is a directory; .kicad_mod is a single file. wxFileName parses
5248 // a path ending in `.pretty` as a file with that extension, so library
5249 // mode uses DirName(); single-file mode keeps the file path as-is and
5250 // hands it directly to FootprintSave, which auto-detects .kicad_mod via
5251 // its own extension check.
5252 wxFileName outFn;
5253
5254 if( singleFileOutput )
5255 outFn = wxFileName( aOutput );
5256 else
5257 outFn = wxFileName::DirName( aOutput );
5258
5259 outFn.MakeAbsolute();
5260
5261 // In library mode wxFileName::DirName treats `foo.pretty` as a directory,
5262 // so GetPath() returns the .pretty itself. In single-file mode GetPath()
5263 // returns the file's parent dir. Either way it's the directory we Mkdir
5264 // into.
5265 const wxString outDir = outFn.GetPath();
5266
5267 if( !wxFileName::DirExists( outDir ) && !wxFileName::Mkdir( outDir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
5268 {
5269 m_reporter->Report( wxString::Format( _( "Cannot create output directory %s\n" ), outDir ),
5272 }
5273
5274 try
5275 {
5277
5278 if( singleFileOutput )
5279 {
5280 // Git per-file driver mode: one merged footprint -> one .kicad_mod.
5281 // Multiple survivors would lose data; flag that as an error since
5282 // single-file input by definition has at most one footprint per
5283 // side.
5284 if( merged.size() > 1 )
5285 {
5286 m_reporter->Report( _( "Single-file fp merge produced multiple footprints; refusing to "
5287 "collapse into one .kicad_mod\n" ),
5290 }
5291
5292 if( merged.empty() )
5293 {
5294 // All sides deleted the footprint. Remove the output file if
5295 // it existed, leaving nothing where the merged content would
5296 // have gone.
5297 if( wxFileName::FileExists( outFn.GetFullPath() ) )
5298 wxRemoveFile( outFn.GetFullPath() );
5299 }
5300 else if( wxFileName( outFn.GetFullPath() ).GetExt() == FILEEXT::KiCadFootprintFileExtension )
5301 {
5302 // FootprintSave's .kicad_mod extension autodetection handles
5303 // the write to the path as-given.
5304 io.FootprintSave( outFn.GetFullPath(), merged.front().get(), nullptr );
5305 }
5306 else
5307 {
5308 // Git driver mode: output is an extension-less temp path
5309 // (typically `.merge_file_XXX`). FootprintSave's
5310 // autodetection would treat it as a library directory.
5311 // Format directly via PRETTIFIED_FILE_OUTPUTFORMATTER, the
5312 // same writer the sexpr lib cache uses.
5313 PRETTIFIED_FILE_OUTPUTFORMATTER formatter( outFn.GetFullPath() );
5314 io.SetOutputFormatter( &formatter );
5315 io.Format( merged.front().get() );
5316 formatter.Finish();
5317 }
5318 }
5319 else
5320 {
5321 // Library mode. Footprints in `merged` are the survivors. Any
5322 // footprint already in the output `.pretty` but absent from
5323 // `merged` is a stale leftover from a previous invocation (or a
5324 // resolved DELETE / TAKE_ANCESTOR-with-no-ancestor case). Delete
5325 // those before saving the survivors, otherwise the resolved
5326 // DELETE never propagates to disk.
5327 std::set<wxString> mergedNames;
5328
5329 for( const auto& fp : merged )
5330 {
5331 if( fp )
5332 mergedNames.insert( fp->GetFPID().GetLibItemName() );
5333 }
5334
5335 wxArrayString existing;
5336 io.FootprintEnumerate( existing, outDir, false, nullptr );
5337
5338 for( const wxString& name : existing )
5339 {
5340 if( !mergedNames.count( name ) )
5341 io.FootprintDelete( outDir, name, nullptr );
5342 }
5343
5344 for( const auto& fp : merged )
5345 {
5346 if( !fp )
5347 continue;
5348
5349 const wxString name = fp->GetFPID().GetLibItemName();
5350
5351 if( io.FootprintExists( outDir, name, nullptr ) )
5352 io.FootprintDelete( outDir, name, nullptr );
5353
5354 io.FootprintSave( outDir, fp.get(), nullptr );
5355 }
5356 }
5357 }
5358 catch( const IO_ERROR& ioe )
5359 {
5360 m_reporter->Report( wxString::Format( _( "Failed to save merged footprint library: %s\n" ), ioe.What() ),
5363 }
5364
5365 // The merged library was saved above, so the output is always valid.
5366 if( !planSnapshot.Resolved() || hadSilentFallback )
5367 {
5368 // Conflict count = engine-unresolved ∪ applier-downgraded (deduped, so
5369 // an item that was both unresolved and silently downgraded counts once).
5370 std::set<KIID_PATH> conflicts( planSnapshot.unresolved.begin(), planSnapshot.unresolved.end() );
5371
5372 for( const KIID_PATH& id : applier.GetReport().mergePropsFallbackIds )
5373 conflicts.insert( id );
5374
5375 m_reporter->Report( wxString::Format( _( "Footprint library merge completed with %zu unresolved "
5376 "conflict(s) in %s\n" ),
5377 conflicts.size(), aOutput ),
5380 }
5381
5383}
@ VIEW3D_BOTTOM
Definition 3d_enums.h:84
PROJECTION_TYPE
Camera projection types.
Definition 3d_enums.h:50
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
#define RANGE_SCALE_3D
This defines the range that all coord will have to be rendered.
COMPATIBILITY_REPORT ClassifyBoardForDowngrade(const BOARD *aBoard, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Report what a board would lose if exported to an older KiCad.
void FlattenBoardVariant(BOARD *aBoard, const wxString &aVariantName)
Bake a variant's overrides into the base footprint attributes.
bool ExportBoardToOlderVersion(const wxString &aSrcFile, const wxString &aDestFile, const DOWNGRADE_TARGET &aTarget, COMPATIBILITY_REPORT &aReport, wxString *aUnsupportedToken, const wxString &aVariant, bool aDropInsteadOfApproximate)
Load a board, downgrade the copy, and write it stamped for the target.
DOWNGRADE_FILE_RESULT DowngradeFootprintFileToTemp(const wxString &aSrcFile, const wxString &aTmpFile, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate)
Load one .kicad_mod, classify it against the rule table, and write the downgraded copy to aTmpFile.
constexpr int FIRST_PCB_VARIANTS
First board format that stores variants.
wxString BuildStackupCsv(BOARD_STACKUP &aStackup, EDA_UNITS aUnits, const STACKUP_CSV_OPTIONS &aOptions)
wxString FormatBoardStatisticsJson(const BOARD_STATISTICS_DATA &aData, BOARD *aBoard, const UNITS_PROVIDER &aUnitsProvider, const wxString &aProjectName, const wxString &aBoardName)
void ComputeBoardStatistics(BOARD *aBoard, const BOARD_STATISTICS_OPTIONS &aOptions, BOARD_STATISTICS_DATA &aData)
wxString FormatBoardStatisticsReport(const BOARD_STATISTICS_DATA &aData, BOARD *aBoard, const UNITS_PROVIDER &aUnitsProvider, const wxString &aProjectName, const wxString &aBoardName)
void InitializeBoardStatisticsData(BOARD_STATISTICS_DATA &aData)
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
static wxString m_DrawingSheetFileName
the name of the drawing sheet file, or empty to use the default drawing sheet
Definition base_screen.h:81
Helper class to handle information needed to display 3D board.
double BiuTo3dUnits() const noexcept
Board integer units To 3D units.
void SetVisibleLayers(const std::bitset< LAYER_3D_END > &aLayers)
std::bitset< LAYER_3D_END > GetVisibleLayers() const
void SetBoard(BOARD *aBoard) noexcept
Set current board to be rendered.
void SetLayerColors(const std::map< int, COLOR4D > &aColors)
EDA_3D_VIEWER_SETTINGS * m_Cfg
std::map< int, COLOR4D > m_ColorOverrides
allows to override color scheme colors
void Set3dCacheManager(S3D_CACHE *aCacheMgr) noexcept
Update the cache manager pointer.
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
Container for design settings for a BOARD object.
std::shared_ptr< NET_SETTINGS > m_NetSettings
std::map< int, SEVERITY > m_DRCSeverities
std::shared_ptr< DRC_ENGINE > m_DRCEngine
const VECTOR2I & GetAuxOrigin() const
BOARD_STACKUP & GetStackupDescriptor()
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
static bool SaveBoard(wxString &aFileName, BOARD &aBoard, PCB_IO_MGR::PCB_FILE_T aFormat)
static std::unique_ptr< BOARD > Load(const wxString &aFileName, PCB_IO_MGR::PCB_FILE_T aFormat, PROJECT *aProject, const OPTIONS &aOptions)
Manage one layer needed to make a physical board.
Manage layers needed to make a physical board.
const std::vector< BOARD_STACKUP_ITEM * > & GetList() const
bool SynchronizeWithBoard(const BOARD_DESIGN_SETTINGS *aSettings)
Synchronize the BOARD_STACKUP_ITEM* list with the board.
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
void SetCurrentVariant(const wxString &aVariant)
Definition board.cpp:3016
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Removes an item from the container.
Definition board.cpp:1548
const PAGE_INFO & GetPageSettings() const
Definition board.h:1029
void RecordDRCExclusions()
Scan existing markers and record data from any that are Excluded.
Definition board.cpp:569
TITLE_BLOCK & GetTitleBlock()
Definition board.h:1035
const std::map< wxString, wxString > & GetProperties() const
Definition board.h:526
const FOOTPRINTS & Footprints() const
Definition board.h:465
const wxString & GetFileName() const
Definition board.h:454
std::vector< PCB_MARKER * > ResolveDRCExclusions(bool aCreateMarkers)
Rebuild DRC markers from the serialized data in BOARD_DESIGN_SETTINGS.
Definition board.cpp:595
wxString GetVariantDescription(const wxString &aVariantName) const
Definition board.cpp:3172
int GetFileFormatVersionAtLoad() const
Definition board.h:585
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition board.h:1032
const wxString GetLayerName(PCB_LAYER_ID aLayer) const
Return the name of a aLayer.
Definition board.cpp:960
wxString GetCurrentVariant() const
Definition board.h:530
PROJECT * GetProject() const
Definition board.h:774
wxString GetDesignRulesPath() const
Return the absolute path to the design rules file for this board.
Definition board.cpp:437
const LSET & GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition board.cpp:1202
void SynchronizeProperties()
Copy the current project's text variables into the boards property cache.
Definition board.cpp:2996
BOX2I ComputeBoundingBox(bool aBoardEdgesOnly=false, bool aPhysicalLayersOnly=false) const
Calculate the bounding box containing all board items (or board edge segments).
Definition board.cpp:2572
void DeleteMARKERs()
Delete all MARKERS from the board.
Definition board.cpp:2100
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
constexpr const Vec GetCenter() const
Definition box2.h:233
void SetProjection(PROJECTION_TYPE aProjection)
Definition camera.h:197
void RotateY_T1(float aAngleInRadians)
Definition camera.cpp:682
bool Zoom_T1(float aFactor)
Definition camera.cpp:625
bool SetCurWindowSize(const wxSize &aSize)
Update the windows size of the camera.
Definition camera.cpp:567
bool ViewCommand_T1(VIEW3D_TYPE aRequestedView)
Definition camera.cpp:106
void RotateX_T1(float aAngleInRadians)
Definition camera.cpp:676
void SetLookAtPos_T1(const SFVEC3F &aLookAtPos)
Definition camera.h:153
const SFVEC3F & GetLookAtPos_T1() const
Definition camera.h:158
void RotateZ_T1(float aAngleInRadians)
Definition camera.cpp:688
bool ParametersChanged()
Definition camera.cpp:726
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
What an export to a given target will keep, approximate, drop, or block.
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.
The dialog to create footprint position files and choose options (one or 2 files, units and force all...
File-compare dialog (Phase 7).
void DrawChosenLibraryItem(LIBRARY_ITEM_DRAWER aDraw)
Draw only the library item named by the chosen change, since the outlines of a whole library pile up ...
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.
A dialog to set the plot options and create plot files in various formats.
Definition dialog_plot.h:38
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)
bool WriteJsonReport(const wxString &aFullFileName)
bool WriteTextReport(const wxString &aFullFileName)
Helper to handle drill precision format in excellon files.
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 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 SetSheetName(const std::string &aSheetName)
Set the sheet name displayed in the title block.
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.
LAYER_PRESET_3D * FindPreset(const wxString &aName)
std::vector< LAYER_PRESET_3D > m_LayerPresets
Create Excellon drill, drill map, and drill report files.
void SetFormat(bool aMetric, ZEROS_FMT aZerosFmt=DECIMAL_FORMAT, int aLeftDigits=0, int aRightDigits=0)
Initialize internal parameters to match the given format.
bool CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board.
void SetOptions(bool aMirror, bool aMinimalHeader, const VECTOR2I &aOffset, bool aMerge_PTH_NPTH)
Initialize internal parameters to match drill options.
void SetRouteModeForOvalHoles(bool aUseRouteModeForOvalHoles)
wxString m_outputFile
Wrapper to expose an API for writing VRML files, without exposing all the many structures used in the...
Definition export_vrml.h:33
bool ExportVRML_File(PROJECT *aProject, wxString *aMessages, const wxString &aFullFileName, double aMMtoWRMLunit, bool aIncludeUnspecified, bool aIncludeDNP, bool aExport3DFiles, bool aUseRelativePaths, const wxString &a3D_Subdir, double aXRef, double aYRef)
Exports the board and its footprint shapes 3D (vrml files only) as a vrml file.
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.
Provide an extensible class to resolve 3D model paths.
wxString ResolvePath(const wxString &aFileName, const wxString &aWorkingPath, std::vector< const EMBEDDED_FILES * > aEmbeddedFilesStack)
Determine the full path of the given file name.
void SetProgramBase(PGM_BASE *aBase)
Set a pointer to the application's PGM_BASE instance used to extract the local env vars.
bool SetProject(const PROJECT *aProject, bool *flgChanged=nullptr)
Set the current KiCad project directory as the first entry in the model path list.
const FOOTPRINT_REFERENCE_LIST & GetReferenceList() const
void UpdateReferences(const FOOTPRINT_REFERENCE_LIST &aRefs)
An interface to the global shared library manager that is schematic-specific and linked to one projec...
This is the minimal equivalent to the SCH_REFERENCE so we can provide similar non-null guarantees thr...
const LIB_ID & GetFPID() const
Definition footprint.h:417
void GetFields(std::vector< PCB_FIELD * > &aVector, bool aVisibleOnly) const
Populate a std::vector with PCB_TEXTs.
void SetPath(const wxString &aPath)
void Save(FOOTPRINT *aFootprintFilter=nullptr)
Save the footprint cache or a single footprint from it to disk.
boost::ptr_map< wxString, FP_CACHE_ENTRY > & GetFootprints()
Export board to GenCAD file format.
void UseIndividualShapes(bool aUnique)
Make pad shapes unique.
void UsePinNamesUnique(bool aUnique)
Make pin names unique.
void StoreOriginCoordsInFile(bool aStore)
Store origin coordinate in GenCAD file.
void FlipBottomPads(bool aFlip)
Flip pad shapes on the bottom side.
void SetPlotOffet(VECTOR2I aOffset)
Set the coordinates offset when exporting items.
bool WriteFile(const wxString &aFullFileName)
Export a GenCAD file.
void SetMapFileFormat(PLOT_FORMAT aMapFmt)
Initialize the format for the drill map file.
bool GenDrillReportFile(const wxString &aFullFileName, REPORTER *aReporter=nullptr)
Create a plain text report file giving a list of drill values and drill count for through holes,...
GERBER_JOBFILE_WRITER is a class used to create Gerber job file a Gerber job file stores info to make...
bool CreateJobFile(const wxString &aFullFilename)
Creates a Gerber job file.
void AddGbrFile(PCB_LAYER_ID aLayer, wxString &aFilename)
add a gerber file name and type in job file list
virtual bool EndPlot() override
Used to create Gerber drill files.
bool CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, bool aGenTenting, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board filenames are computed from the board name,...
void SetOptions(const VECTOR2I &aOffset)
Initialize internal parameters to match drill options.
void SetFormat(int aRightDigits=6)
Initialize internal parameters to match the given format.
bool Export(const wxString &aFullFileName) const
Generate IDFv3 compliant board (*.emn) and library (*.emp) files for aPcb.
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...
An exception saying that the user cancelled an interactive part of a load, import,...
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()
Wrapper to expose an API for writing IPC-D356 files.
Definition export_d356.h:60
bool Write(const wxString &aFilename)
Generates and writes the netlist to a given path.
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
JOB_EXPORT_PCB_3D::FORMAT m_format
EXPORTER_STEP_PARAMS m_3dparams
Despite the name; also used for other formats.
std::vector< wxString > m_variantNames
wxString GetSettingsDialogTitle() const override
ODB_COMPRESSION m_compressionMode
@ ALL_LAYERS_ONE_FILE
DEPRECATED MODE.
GEN_MODE m_pdfGenMode
uused by the cli, will be removed when the other behavior is deprecated
LSEQ ResolvePlotLayers(const LSET &aEnabledLayers) const
Return the layers to plot on a board with aEnabledLayers.
LSEQ m_plotOnAllLayersSequence
Layers to include on all individual layer prints.
std::optional< wxString > m_argLayers
std::optional< wxString > m_argCommonLayers
bool m_plotAllCopperLayers
Plot every copper layer of the board in addition to m_plotLayerSequence.
wxString m_variant
Variant name for variant-aware filtering.
void SetDefaultOutputPath(const wxString &aReferenceName)
void SetDefaultOutputPath(const wxString &aReferenceName)
wxString m_outputLibraryPath
Where to write the converted copy.
bool m_dropInsteadOfApproximate
Omit features that would otherwise be approximated.
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.
COMPATIBILITY_REPORT m_report
Filled by the handler so the caller can show it.
bool m_dryRun
Only classify and fill m_report, do not write anything.
wxString m_libraryPath
The .pretty footprint library to convert.
wxString m_libraryPath
wxString m_outputLibraryPath
Job: diff two PCB files end-to-end via PCB_DIFFER.
wxString m_outputFile
Where to write the downgraded copy.
bool m_dropInsteadOfApproximate
Omit features that would otherwise be approximated.
wxString m_filename
Input board file (may be empty to downgrade only libraries)
wxString m_libraryDir
If set, downgrade every .kicad_mod footprint under this folder too.
COMPATIBILITY_REPORT m_report
Filled by the handler so the caller can show it.
wxString m_variant
Flatten this variant into the export. Empty means the base design.
bool m_inPlace
Internal project export operating only on its prepared copy.
wxString m_target
Target release name, e.g. "KiCad 10.0". Empty means the newest.
bool m_dryRun
Only classify and fill m_report, do not write anything.
bool m_force
Export even when features must be dropped or approximated.
bool m_saveBoard
Definition job_pcb_drc.h:36
bool m_reportAllTrackErrors
Definition job_pcb_drc.h:32
bool m_refillZones
Definition job_pcb_drc.h:35
Job to import a non-KiCad PCB file to KiCad format.
wxString m_importPcbId
EasyEDA Pro PCB document identifier selected by project-level import.
std::map< wxString, wxString > m_layerMap
Explicit overrides from source layer name to KiCad layer name (canonical board-file name,...
std::map< wxString, wxString > m_netNameMap
bool m_isPartOfMultiBoardProject
Avoid promoting an individual board's source settings into shared project settings.
std::vector< std::pair< wxString, wxString > > m_projectBoards
PCB document identifier and source name pairs found during a probe.
wxString m_reportFile
IMPORT_REPORT_FORMAT m_reportFormat
wxString m_inputFile
VECTOR3D m_lightBottomIntensity
VECTOR3D m_lightTopIntensity
VECTOR3D m_lightCameraIntensity
VECTOR3D m_rotation
wxString m_filename
bool m_useBoardStackupColors
VECTOR3D m_lightSideIntensity
std::string m_appearancePreset
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
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
wxString ResolveOutputPath(const wxString &aPath, bool aPathIsDirectory, PROJECT *aProject) const
Definition job.cpp:100
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
wxString GetWorkingOutputPath() const
Returns the working output path for the job, if one has been set.
Definition job.h:246
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
JSON_SETTINGS_INTERNALS * Internals()
Keeps the documents drawn on a pair of diff canvases alive.
Diff two .pretty footprint library directories.
static std::pair< std::vector< std::unique_ptr< FOOTPRINT > >, FOOTPRINT_MAP > LoadLibrary(const wxString &aPrettyPath)
Load a .pretty directory into a FOOTPRINT_MAP.
DOCUMENT_DIFF Diff() override
Produce a DOCUMENT_DIFF of the inputs the concrete differ was constructed with.
std::map< wxString, const FOOTPRINT * > FOOTPRINT_MAP
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 BOARDs and produce a DOCUMENT_DIFF.
Definition pcb_differ.h:62
DOCUMENT_DIFF Diff() override
Produce a DOCUMENT_DIFF of the inputs the concrete differ was constructed with.
Materialize a MERGE_PLAN into a real merged BOARD.
std::unique_ptr< BOARD > Apply()
Produce the merged board.
const REPORT & GetReport() const
Read the new s-expression based KiCad netlist format.
virtual void LoadNetlist() override
Load the contents of the netlist file into aNetlist.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
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_SCH
eeschema DSO
Definition kiway.h:355
Plugin class for import plugins that support remappable layers.
void AsyncLoad()
Loads all available libraries for this adapter type in the background.
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
LSEQ is a sequence (and therefore also a set) of PCB_LAYER_IDs.
Definition lseq.h:47
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
static const LSET & AllCuMask()
return AllCuMask( MAX_CU_LAYERS );
Definition lset.cpp:604
LSEQ UIOrder() const
Return the copper, technical and user layers in the order shown in layer widget.
Definition lset.cpp:739
LSEQ SeqStackupForPlotting() const
Return the sequence that is typical for a bottom-to-top stack-up.
Definition lset.cpp:400
static LSET AllNonCuMask()
Return a mask holding all layer minus CU layers.
Definition lset.cpp:623
static LSET AllCuMask(int aCuLayerCount)
Return a mask holding the requested number of Cu PCB_LAYER_IDs.
Definition lset.cpp:595
static const LSET & AllLayersMask()
Definition lset.cpp:637
static const LSET & InternalCuMask()
Return a complete set of internal copper layers which is all Cu layers except F_Cu and B_Cu.
Definition lset.cpp:573
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
@ MARKER_DRAWING_SHEET
Definition marker_base.h:51
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
Calls Store() and then saves the JSON document contents into the parent JSON_SETTINGS.
void CopyFrom(NET_SETTINGS &aOther)
Deep-copy the persisted contents of aOther into this instance.
Describe the page size and margins of a paper page on which to eventually print or plot.
Definition page_info.h:75
const VECTOR2D GetSizeIU(double aIUScale) const
Gets the page size in internal units.
Definition page_info.h:172
static bool EnsurePathExists(const wxString &aPath, bool aPathToFile=false)
Attempts to create a given path if it does not exist.
Definition paths.cpp:470
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...
int runFpLibMerge(const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive, bool aSingleFile)
int JobExportSpecctraDsn(JOB *aJob)
void refillFabZones(const JOB_EXPORT_PCB_FAB &aJob, BOARD *aBoard)
bool preparePlotLayers(JOB_EXPORT_PCB_PLOT *aJob, BOARD *aBoard, TOOL_MANAGER *aToolManager, LSEQ &aLayersToPlot)
DS_PROXY_VIEW_ITEM * getDrawingSheetProxyView(BOARD *aBrd)
wxString resolveJobOutputPath(JOB *aJob, BOARD *aBoard, const wxString *aDrawingSheet=nullptr)
int runPcbMerge(const wxString &aAncestor, const wxString &aOurs, const wxString &aTheirs, const wxString &aOutput, bool aInteractive)
void loadOverrideDrawingSheet(BOARD *brd, const wxString &aSheetPath)
PCBNEW_JOBS_HANDLER(KIWAY *aKiway)
TOOL_MANAGER * getToolManager(BOARD *aBrd)
std::unique_ptr< BOARD > m_cliBoard
BOARD * getBoard(const wxString &aPath=wxEmptyString)
wxString resolvePlotOutputPath(JOB_EXPORT_PCB_PLOT *aJob, BOARD *aBoard, PLOT_FORMAT aFormat, bool aSingleOutput)
std::unique_ptr< TOOL_MANAGER > m_toolManager
int OpenDiffDialog(KICAD_DIFF::DOC_KIND aKind, const wxString &aFileA, const wxString &aFileB, const wxString &aLabelA, const wxString &aLabelB, wxWindow *aParent, REPORTER *aReporter)
LSEQ convertLayerArg(wxString &aLayerString, BOARD *aBoard) const
void ClearCachedBoard()
Clear the cached CLI board so the next job reloads from the current project.
int doFpExportSvg(JOB_FP_EXPORT_SVG *aSvgJob, const FOOTPRINT *aFootprint)
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 boards for a window outside the kiface, drawing the first on aBefore and the second on aAfte...
BOARD * GetBoard() const
PCB_DIFF_CANVAS_CONTEXT(WIDGET_DIFF_CANVAS *aBefore, WIDGET_DIFF_CANVAS *aAfter)
The main frame for Pcbnew.
A PCB_IO derivation for saving and loading Pcbnew s-expression formatted files.
void FootprintDelete(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Delete aFootprintName from the library at aLibraryPath.
void FootprintEnumerate(wxArrayString &aFootprintNames, const wxString &aLibraryPath, bool aBestEfforts, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Return a list of footprint names contained within the library at aLibraryPath.
std::unique_ptr< FOOTPRINT > ImportFootprint(const wxString &aFootprintPath, wxString &aFootprintNameOut, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Load a single footprint from aFootprintPath and put its name in aFootprintNameOut.
bool FootprintExists(const wxString &aLibraryPath, const wxString &aFootprintName, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Check for the existence of a footprint.
void FootprintSave(const wxString &aLibraryPath, const FOOTPRINT *aFootprint, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aFootprint to an existing library located at aLibraryPath.
void SaveBoard(const wxString &aFileName, BOARD &aBoard, const std::map< std::string, UTF8 > *aProperties=nullptr) override
Write aBoard to a storage file in a format that this PCB_IO implementation knows about or it can be u...
void Format(const BOARD_ITEM *aItem) const
Output aItem to aFormatter in s-expression format.
void SetOutputFormatter(OUTPUTFORMATTER *aFormatter)
static bool ConvertLibrary(const std::map< std::string, UTF8 > &aOldFileProps, const wxString &aOldFilePath, const wxString &aNewFilePath, REPORTER *aReporter)
Convert a schematic symbol library to the latest KiCad format.
PCB_FILE_T
The set of file types that the PCB_IO_MGR knows about, and for which there has been a plugin written,...
Definition pcb_io_mgr.h:52
@ KICAD_SEXP
S-expression Pcbnew file format.
Definition pcb_io_mgr.h:54
@ EASYPC
Easy-PC / DesignSpark PCB.
Definition pcb_io_mgr.h:76
@ TARGET3001
TARGET 3001! project.
Definition pcb_io_mgr.h:77
@ ALTIUM_DESIGNER
Definition pcb_io_mgr.h:59
@ CADSTAR_PCB_ARCHIVE
Definition pcb_io_mgr.h:60
@ PCB_FILE_UNKNOWN
0 is not a legal menu id on Mac
Definition pcb_io_mgr.h:53
static PCB_IO * FindPlugin(PCB_FILE_T aFileType)
Return a PCB_IO which the caller can use to import, export, save, or load design documents.
static PCB_FILE_T FindPluginTypeFromBoardPath(const wxString &aFileName, int aCtl=0)
Return a plugin type given a path for a board file.
static PCB_FILE_T GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a footprint library's libPath.
static bool ImportGeneratesProjectLibrary(PCB_FILE_T aFileType)
Return true when importing aFileType should materialize a project footprint library.
static const wxString ShowType(PCB_FILE_T aFileType)
Return a brief name for a plugin given aFileType enum.
std::unique_ptr< BOARD > LoadBoard(const wxString &aFileName, const std::map< std::string, UTF8 > *aProperties=nullptr, PROJECT *aProject=nullptr)
Load information from some input file format that this PCB_IO implementation knows about into new BOA...
Definition pcb_io.cpp:72
bool Plot(const wxString &aOutputPath, const LSEQ &aLayersToPlot, const LSEQ &aCommonLayers, bool aUseGerberFileExtensions, bool aPlotAllLayersToSingleFile, bool aForceAllLayersToSinglePage, std::optional< wxString > aLayerName=std::nullopt, std::optional< wxString > aSheetName=std::nullopt, std::optional< wxString > aSheetPath=std::nullopt, std::vector< wxString > *aOutputFiles=nullptr)
static void PlotJobToPlotOpts(PCB_PLOT_PARAMS &aOpts, JOB_EXPORT_PCB_PLOT *aJob, REPORTER &aReporter)
Translate a JOB to PCB_PLOT_PARAMS.
static void BuildPlotFileName(wxFileName *aFilename, const wxString &aOutputDir, const wxString &aSuffix, const wxString &aExtension)
Complete a plot filename.
Parameters and options when plotting/printing a board.
LSEQ GetPlotOnAllLayersSequence() const
void SetLayerSelection(const LSET &aSelection)
void SetPlotOnAllLayersSequence(LSEQ aSeq)
LSET GetLayerSelection() const
bool GetUseGerberProtelExtensions() const
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
Used to create Gerber drill files.
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
void SetVariant(const wxString &aVariant)
Set the variant name for variant-aware filtering.
int CreatePlaceFile(const wxString &aFullFilename, PCB_LAYER_ID aLayer, bool aIncludeBrdEdges, bool aExcludeDNP, bool aExcludeBOM)
Create an pnp gerber file.
The ASCII format of the kicad place file is:
static wxString DecorateFilename(const wxString &aBaseName, bool aFront, bool aBack)
std::string GenPositionData()
build a string filled with the position data
void SetVariant(const wxString &aVariant)
Set the variant name for variant-aware export.
Base plotter engine class.
Definition plotter.h:138
virtual bool EndPlot()=0
bool Finish() override
Runs prettification over the buffered bytes, writes them to the sibling temp file,...
Definition richio.cpp:710
The backing store for a PROJECT, in JSON format.
wxString m_BoardDrawingSheetFile
PcbNew params.
bool Store() override
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
static S3D_CACHE * Get3DCacheManager(PROJECT *aProject, bool updateProjDir=false)
Return a pointer to an instance of the 3D cache manager.
static FILENAME_RESOLVER * Get3DFilenameResolver(PROJECT *aProject)
Accessor for 3D path resolver.
static FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(PROJECT *aProject)
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:271
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:289
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
void SetReporters(std::shared_ptr< REPORTER > aActivityReporter, std::shared_ptr< REPORTER > aWarningReporter)
Set the reporters for activity and warning messages.
bool Redraw(bool aIsMoving) override
Redraw the view.
void SetCurWindowSize(const wxSize &aSize) override
Before each render, the canvas will tell the render what is the size of its windows,...
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
RAII class that sets an value at construction and resets it to the original value at destruction.
bool SaveProjectCopy(const wxString &aFullPath, PROJECT *aProject=nullptr)
Save a copy of the current project under the given path.
PROJECT * GetProject(const wxString &aFullPath) const
Retrieve a loaded project by name.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
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.
Is a LINE_READER that reads from a multiline 8 bit wide std::string.
Definition richio.h:225
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
Master controller class:
T * GetTool()
Return the tool of given type or nullptr if there is no such tool registered.
TOOL_BASE * FindTool(int aId) const
Search for a tool with given ID.
void RegisterTool(TOOL_BASE *aTool)
Add a tool to the manager set and sets it up.
void SetEnvironment(EDA_ITEM *aModel, KIGFX::VIEW *aView, KIGFX::VIEW_CONTROLS *aViewControls, APP_SETTINGS_BASE *aSettings, TOOLS_HOLDER *aFrame)
Set the work environment (model, view, view controls and the parent window).
void Pan_T1(const SFVEC3F &aDeltaOffsetInc) override
void SetT0_and_T1_current_T() override
This will set T0 and T1 with the current values.
void Interpolate(float t) override
It will update the matrix to interpolate between T0 and T1 values.
An 8 bit string that is assuredly encoded in UTF8, and supplies special conversion support to and fro...
Definition utf8.h:67
bool empty() const
Definition utf8.h:105
wxString wx_str() const
Definition utf8.cpp:41
GAL-backed canvas for visualizing a KICAD_DIFF::DIFF_SCENE.
Handle actions specific to filling copper zones.
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.
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
static DRILL_PRECISION precisionListForInches(2, 4)
static DRILL_PRECISION precisionListForMetric(3, 3)
static bool empty(const wxTextEntryBase *aCtrl)
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)
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.
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)
#define FOLLOW_PLOT_SETTINGS
#define FOLLOW_PCB
EDA_UNITS
Definition eda_units.h:45
std::vector< FOOTPRINT_REF > FOOTPRINT_REFERENCE_LIST
FOOTPRINT_IMPORT_RECONCILE_RESULT ReconcileImportedFootprints(std::vector< std::unique_ptr< FOOTPRINT > > aDefinitions, BOARD &aBoard, PROJECT &aProject, const wxString &aBoardPath, const std::map< std::string, UTF8 > *aProperties, REPORTER &aReporter)
Reconcile aBoard against the definitions an importer retained while loading it.
@ FRAME_PCB_EDITOR
Definition frame_type.h:38
@ FRAME_SCH
Definition frame_type.h:30
Classes used in drill files, map files and report files generation.
Classes used in drill files, map files and report files generation.
int RefreshGeneratedTables(BOARD &aBoard)
Bring every generated table on the board up to date and return how many were rebuilt.
Classes used to generate a Gerber job file in JSON.
Classes used in place file generation.
nlohmann::json json
Definition gerbview.cpp:50
static const std::string LegacySchematicFileExtension
static const std::string BrepFileExtension
static const std::string SymbolLibraryTableFileName
static const std::string JpegFileExtension
static const std::string GerberJobFileExtension
static const std::string GerberFileExtension
static const std::string XaoFileExtension
static const std::string ReportFileExtension
static const std::string GltfBinaryFileExtension
static const std::string ProjectFileExtension
static const std::string PngFileExtension
static const std::string FootprintPlaceFileExtension
static const std::string JsonFileExtension
static const std::string IdfV3BoardFileExtension
static const std::string KiCadSchematicFileExtension
static const std::string CsvFileExtension
static const std::string U3DFileExtension
static const std::string PdfFileExtension
static const std::string Ipc2581FileExtension
static const std::string FootprintLibraryTableFileName
static const std::string GencadFileExtension
static const std::string StlFileExtension
static const std::string IpcD356FileExtension
static const std::string PlyFileExtension
static const std::string SpecctraDsnFileExtension
static const std::string StepFileExtension
static const std::string SVGFileExtension
static const std::string DesignRulesFileExtension
static const std::string VrmlFileExtension
static const std::string KiCadFootprintFileExtension
static const std::string ArchiveFileExtension
static const std::string KiCadPcbFileExtension
std::string source
bool ApplyImportedNetNameMap(BOARD &aBoard, const std::map< wxString, wxString > &aNames, REPORTER &aReporter)
Apply caller-selected imported net names without changing net identity or connectivity.
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
bool GenerateIpc2581File(JOB_EXPORT_PCB_IPC2581 &aJob, BOARD *aBoard, PROGRESS_REPORTER *aProgressReporter, REPORTER *aReporter)
Write the IPC-2581 file or archive of aJob and record it as a job output.
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...
Service::Type GetKifaceService(KIFACE *aKiface)
Look up a service exported by a KIFACE.
#define KICTL_KICAD_ONLY
chosen file is from KiCad according to user
wxString LayerName(int aLayer)
Returns the default display name for a given layer.
Definition layer_id.cpp:31
@ LAYER_3D_BACKGROUND_TOP
Definition layer_ids.h:584
@ LAYER_3D_BACKGROUND_BOTTOM
Definition layer_ids.h:583
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_CrtYd
Definition layer_ids.h:112
@ B_Adhes
Definition layer_ids.h:99
@ F_Paste
Definition layer_ids.h:100
@ F_Adhes
Definition layer_ids.h:98
@ B_Mask
Definition layer_ids.h:94
@ B_Cu
Definition layer_ids.h:61
@ F_Mask
Definition layer_ids.h:93
@ B_Paste
Definition layer_ids.h:101
@ F_Fab
Definition layer_ids.h:115
@ F_SilkS
Definition layer_ids.h:96
@ B_CrtYd
Definition layer_ids.h:111
@ UNDEFINED_LAYER
Definition layer_ids.h:57
@ B_SilkS
Definition layer_ids.h:97
@ F_Cu
Definition layer_ids.h:60
@ B_Fab
Definition layer_ids.h:114
This file contains miscellaneous commonly used macros and functions.
@ MAIL_SCH_GET_NETLIST
Definition mail_type.h:45
#define MAIL_SCH_GET_NETLIST_CANCELLED
Reply payload for MAIL_SCH_GET_NETLIST when the user deliberately aborts netlist generation (for exam...
Definition mail_type.h:79
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
void ExportBoardToSpecctraFile(BOARD *aBoard, const wxString &aFullFilename, REPORTER *aReporter=nullptr)
Helper method to export board to DSN file.
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,...
const wxString DOC_PROP_NET_CLASSES
LIB_MERGE_APPLIER< FOOTPRINT > FP_LIB_MERGE_APPLIER
Footprint-library 3-way merge applier. See LIB_MERGE_APPLIER for behavior.
wxString OlderFormatNotice(int aAncestorVersion, int aOursVersion, int aTheirsVersion, int aCurrentVersion)
Empty when every side is already in the current file format.
DOCUMENT_GEOMETRY ExtractFootprintGeometry(const FOOTPRINT &aFootprint, const KIGFX::COLOR4D &aColor)
Extract drawable context geometry from a single FOOTPRINT.
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...
void ConfigurePcbDiffCanvasContext(WIDGET_DIFF_CANVAS &aCanvas, BOARD *aReference, BOARD *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)
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.
const wxString DOC_PROP_DRC_SEVERITIES
DOCUMENT_GEOMETRY ExtractBoardGeometry(const BOARD &aBoard, const KIGFX::COLOR4D &aColor)
Extract a coarse outline of a BOARD into a DOCUMENT_GEOMETRY for use as background context in DIFF_SC...
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.
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.
void ShowFootprintPair(WIDGET_DIFF_CANVAS &aCanvas, const FP_LIB_DIFFER::FOOTPRINT_MAP &aBefore, const FP_LIB_DIFFER::FOOTPRINT_MAP &aAfter, const wxString &aName)
Draw the footprint aName as it is in aBefore and aAfter.
void PackBoardStackup(const BOARD &aBoard, BoardStackup &aOut)
ODB_EXPORT_RESULT GenerateODBPPFiles(const JOB_EXPORT_PCB_ODB &aJob, BOARD *aBoard, PCB_EDIT_FRAME *aParentFrame, PROGRESS_REPORTER *aProgressReporter, REPORTER *aReporter)
Generate the ODB++ tree or archive and return the write status and the paths written.
#define SEXPR_FOOTPRINT_LIB_FILE_VERSION
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
#define CTL_FOR_LIBRARY
Format output for a footprint library instead of clipboard or BOARD.
bool PlotFootprintToSVG(const FOOTPRINT &aFootprint, PROJECT &aProject, const std::map< wxString, wxString > *aVarOverrides, PCB_PLOT_PARAMS &aPlotOpts, const LSEQ &aLayersToPlot, const LSEQ &aLayersOnAll, const wxString &aFileName, REPORTER *aReporter)
Plot a footprint to an SVG file, with the footprint origin at the SVG origin and the page/viewBox siz...
static PCB_LAYER_ID resolveKiCadLayerName(const wxString &aName)
static int loadFootprintLibrarySide(const wxString &aPath, std::vector< std::unique_ptr< FOOTPRINT > > &aOwners, KICAD_DIFF::FP_LIB_DIFFER::FOOTPRINT_MAP &aMap, bool aAllowEmpty, REPORTER &aReporter)
static wxString footprintRefusedMessage(const wxString &aFile, const DOWNGRADE_TARGET &aTarget)
static DRILL_PRECISION precisionListForInches(2, 4)
static DRILL_PRECISION precisionListForMetric(3, 3)
static SCRATCH_DOC< BOARD > loadScratchBoard(SETTINGS_MANAGER &aMgr, const wxString &aPath, bool aInitializeAfterLoad=true)
static int loadPcbDiffSides(SETTINGS_MANAGER &aMgr, REPORTER &aReporter, const wxString &aFileA, const wxString &aFileB, PCB_DIFF_SIDES &aSides)
static wxString downgradeFootprintLibraries(const wxString &aDir, const DOWNGRADE_TARGET &aTarget, bool aDropInsteadOfApproximate, DOWNGRADE_FILE_TRANSACTION *aTransaction=nullptr, wxString *aRecoveryError=nullptr)
static void classifyFootprintLibraries(const wxString &aDir, const DOWNGRADE_TARGET &aTarget, COMPATIBILITY_REPORT &aReport, bool aDropInsteadOfApproximate)
static int plotJob(JOB_EXPORT_PCB_PLOT *aJob, PCB_PLOTTER &aPlotter, const LSEQ &aLayersToPlot, const wxString &aOutPath, bool aSingleOutput, bool aUseVarOverrides, bool aForceAllLayersToOnePage=false)
const wxString GetGerberProtelExtension(int aLayer)
Definition pcbplot.cpp:39
PLOTTER * StartPlotBoard(BOARD *aBoard, const PCB_PLOT_PARAMS *aPlotOpts, int aLayer, const wxString &aLayerName, const wxString &aFullFileName, const wxString &aSheetName, const wxString &aSheetPath, const wxString &aPageName=wxT("1"), const wxString &aPageNumber=wxEmptyString, const int aPageCount=1)
Open a new plotfile using the options (and especially the format) specified in the options and prepar...
void PlotBoardLayers(BOARD *aBoard, PLOTTER *aPlotter, const LSEQ &aLayerSequence, const PCB_PLOT_PARAMS &aPlotOptions)
Plot a sequence of board layer IDs.
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_SET_DIRTY
Definition sch_commit.h:40
#define SKIP_UNDO
Definition sch_commit.h:38
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 ...
T * GetAppSettings(const char *aFilename)
const int scale
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
#define OPEN_OSTREAM(var, name)
#define CLOSE_STREAM(var)
wxString ExpandVariantOutputPath(const wxString &aPath, const wxString &aVariantToken)
#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_boardVersion
SEXPR_BOARD_FILE_VERSION for the target.
wxString m_name
User-facing name, e.g. "KiCad 10.0".
std::vector< KIGFX::COLOR4D > raytrace_lightColor
std::vector< BOM_PRESET > m_BomPresets
std::vector< BOM_FMT_PRESET > m_BomFmtPresets
Describes an imported layer and how it could be mapped to KiCad Layers.
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.
Result of planning a 3-way merge.
std::size_t ConflictCount() const
std::vector< KIID_PATH > unresolved
Report on the application after Apply() runs.
wxString fpLibTable
fp-lib-table content the applier resolved.
VALIDATION_REPORT validation
Post-apply validator pipeline result (refdes uniqueness, connectivity-rebuild-ack,...
bool projectFileTouched
True iff the applier resolved state that lives in the .kicad_pro or a project sibling file.
wxString customDrcRules
Custom DRC rules (.kicad_dru) content the applier resolved.
wxString symLibTable
sym-lib-table content the applier resolved.
wxString drawingSheetFile
Drawing sheet path the applier resolved (from a doc-level resolution).
Outcome of a single validator run.
std::vector< VALIDATION_FAILURE > failures
A filename or source description, a problem input line, a line number, a byte offset,...
KICAD_DIFF::DOCUMENT_DIFF diff
SCRATCH_DOC< BOARD > a
SCRATCH_DOC< BOARD > b
Move-only RAII wrapper for "load a KiCad document into a non-active scratch PROJECT and clean up afte...
std::unique_ptr< DOC > doc
Options controlling which stackup fields are included in CSV exports.
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
static void checkParity(CREEPAGE_PARITY_FIXTURE &aFixture, const std::string &aBoard)
nanodbc::result res
std::string netlist
std::string path
IbisParser parser & reporter
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
Declaration for a track ball camera.
double DEG2RAD(double deg)
Definition trigo.h:178
@ PCB_VIA_T
class PCB_VIA, a via (like a track segment on a copper layer)
Definition typeinfo.h:89
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
Definition of file extensions used in Kicad.
glm::vec3 SFVEC3F
Definition xv3d_types.h:40
#define ZONE_FILLER_TOOL_NAME