KiCad PCB EDA Suite
Loading...
Searching...
No Matches
pcbnew/files.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) 2004-2015 Jean-Pierre Charras, jp.charras at wanadoo.fr
5 * Copyright (C) 2011 Wayne Stambaugh <[email protected]>
6 * Copyright (C) 2023 CERN (www.cern.ch)
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License
11 * as published by the Free Software Foundation; either version 2
12 * of the License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23#include <string>
24#include <vector>
25
26#include <advanced_config.h>
27#include <confirm.h>
28#include <kidialog.h>
29#include <core/arraydim.h>
30#include <core/profile.h>
31#include <thread_pool.h>
32#include <gestfich.h>
33#include <local_history.h>
34#include <pcb_edit_frame.h>
36#include <board_loader.h>
40#include <import_design_rules.h>
43#include <import_net_names.h>
44#include <kiface_base.h>
45#include <macros.h>
46#include <trace_helpers.h>
48#include <lockfile.h>
50#include <pcbnew_id.h>
52#include <tool/tool_manager.h>
53#include <board.h>
54#include <footprint.h>
55#include <collectors.h>
57#include <kiplatform/app.h>
58#include <kiplatform/ui.h>
60#include <widgets/wx_infobar.h>
63#include <paths.h>
64#include <pgm_base.h>
66#include <project_pcb.h>
70#include <pcb_io/pcb_io_mgr.h>
79#include <tools/pcb_actions.h>
82#include <board_commit.h>
83#include <reporter.h>
84#include <zone_filler.h>
86#include <widgets/kistatusbar.h>
88#include <wx_filename.h> // For ::ResolvePossibleSymlinks()
89#include <kiplatform/io.h>
90
91#include <wx/stdpaths.h>
92#include <wx/ffile.h>
93#include <wx/file.h>
94#include <wx/filedlg.h>
95#include <wx/txtstrm.h>
96#include <wx/wfstream.h>
97#include <wx/zipstrm.h>
98#include <wx/dir.h>
99
101
102//#define USE_INSTRUMENTATION 1
103#define USE_INSTRUMENTATION 0
104
105static const wxChar* const traceAllegroPerf = wxT( "KICAD_ALLEGRO_PERF" );
106
107
116bool AskLoadBoardFileName( PCB_EDIT_FRAME* aParent, wxString* aFileName, int aCtl = 0 )
117{
118 std::vector<IO_BASE::IO_FILE_DESC> descriptions;
119
120 for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
121 {
122 bool isKiCad = plugin.m_type == PCB_IO_MGR::KICAD_SEXP || plugin.m_type == PCB_IO_MGR::LEGACY;
123
124 if( ( aCtl & KICTL_KICAD_ONLY ) && !isKiCad )
125 continue;
126
127 if( ( aCtl & KICTL_NONKICAD_ONLY ) && isKiCad )
128 continue;
129
130 IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
131 wxCHECK( pi, false );
132
133 const IO_BASE::IO_FILE_DESC& desc = pi->GetBoardFileDesc();
134
135 if( desc.m_FileExtensions.empty() || !desc.m_CanRead )
136 continue;
137
138 descriptions.emplace_back( desc );
139 }
140
141 wxString fileFiltersStr;
142 std::vector<std::string> allExtensions;
143 std::set<wxString> allWildcardsSet;
144
145 for( const IO_BASE::IO_FILE_DESC& desc : descriptions )
146 {
147 if( !fileFiltersStr.IsEmpty() )
148 fileFiltersStr += wxChar( '|' );
149
150 fileFiltersStr += desc.FileFilter();
151
152 for( const std::string& ext : desc.m_FileExtensions )
153 {
154 allExtensions.emplace_back( ext );
155 allWildcardsSet.insert( wxT( "*." ) + formatWildcardExt( ext ) + wxT( ";" ) );
156 }
157 }
158
159 wxString allWildcardsStr;
160
161 for( const wxString& wildcard : allWildcardsSet )
162 allWildcardsStr << wildcard;
163
164 if( aCtl & KICTL_KICAD_ONLY )
165 {
166 fileFiltersStr = _( "All KiCad Board Files" ) + AddFileExtListToFilter( allExtensions );
167 }
168 else
169 {
170 fileFiltersStr = _( "All supported formats" ) + wxT( "|" ) + allWildcardsStr + wxT( "|" )
171 + fileFiltersStr;
172 }
173
174 wxFileName fileName( *aFileName );
175 wxString path;
176 wxString name;
177
178 if( fileName.FileExists() )
179 {
180 path = fileName.GetPath();
181 name = fileName.GetFullName();
182 }
183 else
184 {
185 path = aParent->GetMruPath();
186
187 if( path.IsEmpty() )
189 // leave name empty
190 }
191
192 bool kicadFormat = ( aCtl & KICTL_KICAD_ONLY );
193
194 wxFileDialog dlg( aParent, kicadFormat ? _( "Open Board File" ) : _( "Import Non KiCad Board File" ),
195 path, name, fileFiltersStr, wxFD_OPEN | wxFD_FILE_MUST_EXIST );
196
197 FILEDLG_IMPORT_NON_KICAD importOptions( aParent->config()->m_System.show_import_issues );
198
199 if( !kicadFormat )
200 dlg.SetCustomizeHook( importOptions );
201
203
204 if( dlg.ShowModal() == wxID_OK )
205 {
206 *aFileName = dlg.GetPath();
207 aParent->SetMruPath( wxFileName( dlg.GetPath() ).GetPath() );
208
209 if( !kicadFormat )
210 aParent->config()->m_System.show_import_issues = importOptions.GetShowIssues();
211
212 return true;
213 }
214 else
215 {
216 return false;
217 }
218}
219
220
230bool AskSaveBoardFileName( PCB_EDIT_FRAME* aParent, wxString* aFileName, bool* aCreateProject )
231{
232 wxString wildcard = FILEEXT::PcbFileWildcard();
233 wxFileName fn = *aFileName;
234
236
237 wxFileDialog dlg( aParent, _( "Save Board File As" ), fn.GetPath(), fn.GetFullName(), wildcard,
238 wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
239
240// Add a "Create a project" checkbox in standalone mode and one isn't loaded
241 FILEDLG_HOOK_SAVE_PROJECT newProjectHook;
242
243 if( Kiface().IsSingle() && aParent->Prj().IsNullProject() )
244 dlg.SetCustomizeHook( newProjectHook );
245
247
248 if( dlg.ShowModal() != wxID_OK )
249 return false;
250
251 *aFileName = dlg.GetPath();
252 *aFileName = EnsureFileExtension( *aFileName, FILEEXT::KiCadPcbFileExtension );
253
254 if( newProjectHook.IsAttachedToDialog() )
255 *aCreateProject = newProjectHook.GetCreateNewProject();
256 else if( !aParent->Prj().IsNullProject() )
257 *aCreateProject = true;
258
259 return true;
260}
261
262
263void PCB_EDIT_FRAME::OnFileHistory( wxCommandEvent& event )
264{
265 wxString filename = GetFileFromHistory( event.GetId(), _( "Printed circuit board" ) );
266
267 if( !filename.IsEmpty() )
268 {
269 if( !wxFileName::IsFileReadable( filename ) )
270 {
271 if( !AskLoadBoardFileName( this, &filename, KICTL_KICAD_ONLY ) )
272 return;
273 }
274
275 OpenProjectFiles( std::vector<wxString>( 1, filename ), KICTL_KICAD_ONLY );
276 }
277}
278
279
280void PCB_EDIT_FRAME::OnClearFileHistory( wxCommandEvent& aEvent )
281{
283}
284
285
287{
288 // Only standalone mode can directly load a new document
289 if( !Kiface().IsSingle() )
290 return false;
291
292 int open_ctl = KICTL_KICAD_ONLY;
293 wxString fileName = m_frame->Prj().AbsolutePath( m_frame->GetBoard()->GetFileName() );
294
295 if( AskLoadBoardFileName( m_frame, &fileName, open_ctl ) )
296 m_frame->OpenProjectFiles( std::vector<wxString>( 1, fileName ), open_ctl );
297
298 return 0;
299}
300
301
303{
304 // Note: we explicitly allow this even if not in standalone mode for now, even though it is dangerous.
305 int open_ctl = KICTL_NONKICAD_ONLY;
306 wxString fileName; // = Prj().AbsolutePath( GetBoard()->GetFileName() );
307
308 if( AskLoadBoardFileName( m_frame, &fileName, open_ctl ) )
309 m_frame->OpenProjectFiles( std::vector<wxString>( 1, fileName ), open_ctl );
310
311 return 0;
312}
313
314
316{
317 wxFileName fn = m_frame->Prj().AbsolutePath( m_frame->GetBoard()->GetFileName() );
318
319 if( !IsOK( m_frame, wxString::Format( _( "Revert '%s' to last version saved?" ), fn.GetFullPath() ) ) )
320 return false;
321
322 return m_frame->ReloadFromDisk();
323}
324
325
327{
328 // Only standalone mode can directly load a new document
329 if( !Kiface().IsSingle() )
330 return false;
331
332 if( !m_frame->CloseFootprintFieldsTableDialog() )
333 return false;
334
335 if( m_frame->IsContentModified() )
336 {
337 wxFileName fileName = m_frame->GetBoard()->GetFileName();
338 wxString saveMsg = _( "Current board will be closed, save changes to '%s' before "
339 "continuing?" );
340
341 if( !HandleUnsavedChanges( m_frame, wxString::Format( saveMsg, fileName.GetFullName() ),
342 [&]()->bool
343 {
344 return m_frame->SaveBoard();
345 } ) )
346 {
347 return false;
348 }
349 }
350 else if( !m_frame->GetBoard()->IsEmpty() )
351 {
352 if( !IsOK( m_frame, _( "Current Board will be closed. Continue?" ) ) )
353 return false;
354 }
355
356 m_frame->SaveProjectLocalSettings();
357
358 m_frame->GetBoard()->ClearProject();
359 m_frame->GetSettingsManager()->UnloadProject( &m_frame->Prj() );
360
361 if( !m_frame->Clear_Pcb( false ) )
362 return false;
363
364 m_frame->LoadProjectSettings();
365 m_frame->LoadDrawingSheet();
366
367 m_frame->OnBoardLoaded();
368 m_frame->OnModify();
369
370 return 0;
371}
372
373
374bool PCB_EDIT_FRAME::SaveBoard( bool aSaveAs, bool aSaveCopy )
375{
376 if( !aSaveAs )
377 {
378 if( !GetBoard()->GetFileName().IsEmpty() )
379 {
380 if( SavePcbFile( Prj().AbsolutePath( GetBoard()->GetFileName() ) ) )
381 {
382 m_autoSaveRequired = false;
383 return true;
384 }
385
386 return false;
387 }
388 }
389
390 wxString orig_name;
391
392 wxFileName::SplitPath( GetBoard()->GetFileName(), nullptr, nullptr, &orig_name, nullptr );
393
394 if( orig_name.IsEmpty() )
395 orig_name = NAMELESS_PROJECT;
396
397 wxFileName savePath( Prj().GetProjectFullName() );
398
399 if( !savePath.IsOk() || !savePath.IsDirWritable() )
400 {
401 savePath = GetMruPath();
402
403 if( !savePath.IsOk() || !savePath.IsDirWritable() )
405 }
406
407 wxFileName fn( savePath.GetPath(), orig_name, FILEEXT::KiCadPcbFileExtension );
408 wxString filename = fn.GetFullPath();
409 bool createProject = false;
410 bool success = false;
411
412 if( AskSaveBoardFileName( this, &filename, &createProject ) )
413 {
414 if( aSaveCopy )
415 {
416 success = SavePcbCopy( EnsureFileExtension( filename, FILEEXT::KiCadPcbFileExtension ), createProject );
417 }
418 else
419 {
420 success = SavePcbFile( filename, aSaveAs, createProject );
421
422 if( success )
423 m_autoSaveRequired = false;
424 }
425 }
426
427 return success;
428}
429
430
431int PCB_EDIT_FRAME::inferLegacyEdgeClearance( BOARD* aBoard, bool aShowUserMsg )
432{
433 PCB_LAYER_COLLECTOR collector;
434
435 collector.SetLayerId( Edge_Cuts );
436 collector.Collect( aBoard, GENERAL_COLLECTOR::AllBoardItems );
437
438 int edgeWidth = -1;
439 bool mixed = false;
440
441 for( int i = 0; i < collector.GetCount(); i++ )
442 {
443 if( collector[i]->Type() == PCB_SHAPE_T )
444 {
445 int itemWidth = static_cast<PCB_SHAPE*>( collector[i] )->GetWidth();
446
447 if( edgeWidth != -1 && edgeWidth != itemWidth )
448 {
449 mixed = true;
450 edgeWidth = std::max( edgeWidth, itemWidth );
451 }
452 else
453 {
454 edgeWidth = itemWidth;
455 }
456 }
457 }
458
459 if( mixed && aShowUserMsg )
460 {
461 // If they had different widths then we can't ensure that fills will be the same.
462 DisplayInfoMessage( this,
463 _( "If the zones on this board are refilled the Copper Edge "
464 "Clearance setting will be used (see Board Setup > Design "
465 "Rules > Constraints).\n This may result in different fills "
466 "from previous KiCad versions which used the line thicknesses "
467 "of the board boundary on the Edge Cuts layer." ) );
468 }
469
470 return std::max( 0, edgeWidth / 2 );
471}
472
473
475{
476 wxString fileName = GetBoard()->GetFileName();
477
478 if( fileName.IsEmpty() )
479 return false;
480
481 fileName = Prj().AbsolutePath( fileName );
482
483 // The caller already handled confirmation, so skip the save prompt.
484 GetScreen()->SetContentModified( false );
485 ReleaseFile();
486 return OpenProjectFiles( std::vector<wxString>( 1, fileName ), KICTL_REVERT );
487}
488
489
490bool PCB_EDIT_FRAME::OpenProjectFiles( const std::vector<wxString>& aFileSet, int aCtl )
491{
492 // This is for python:
493 if( aFileSet.size() != 1 )
494 {
495 DisplayError( this, wxString::Format( "Pcbnew:%s() takes a single filename", __func__ ) );
496 return false;
497 }
498
499 wxString fullFileName( aFileSet[0] );
500 wxFileName wx_filename( fullFileName );
501 wxString msg;
502
503 if( Kiface().IsSingle() )
505
506 // We insist on caller sending us an absolute path, if it does not, we say it's a bug.
507 wxASSERT_MSG( wx_filename.IsAbsolute(), wxT( "Path is not absolute!" ) );
508
509 std::unique_ptr<LOCKFILE> lock = std::make_unique<LOCKFILE>( fullFileName );
510
511 if( !lock->Valid() )
512 {
513 // If project-level lock override was already granted, silently override this file's lock
514 if( Prj().IsLockOverrideGranted() )
515 {
516 lock->OverrideLock();
517 }
518 else
519 {
520 msg.Printf( _( "PCB '%s' is already open by '%s' at '%s'." ),
521 wx_filename.GetFullName(),
522 lock->GetUsername(),
523 lock->GetHostname() );
524
525 if( !AskOverrideLock( this, msg ) )
526 return false;
527
528 lock->OverrideLock();
529 }
530 }
531
533 return false;
534
535 if( IsContentModified() )
536 {
537 if( !HandleUnsavedChanges( this, _( "The current PCB has been modified. Save changes?" ),
538 [&]() -> bool
539 {
540 return SavePcbFile( GetBoard()->GetFileName() );
541 } ) )
542 {
543 return false;
544 }
545 }
546
547 wxFileName pro = fullFileName;
548 pro.SetExt( FILEEXT::ProjectFileExtension );
549
550 bool is_new = !wxFileName::IsFileReadable( fullFileName );
551
552 wxString previousBoardFileName = GetBoard() ? GetBoard()->GetFileName() : wxString();
553
554 // If its a non-existent PCB and caller thinks it exists
555 if( is_new && !( aCtl & KICTL_CREATE ) )
556 {
557 // notify user that fullFileName does not exist, ask if user wants to create it.
558 msg.Printf( _( "PCB '%s' does not exist. Do you wish to create it?" ), fullFileName );
559
560 if( !IsOK( this, msg ) )
561 return false;
562 }
563
564 // Get rid of any existing warnings about the old board
565 GetInfoBar()->Dismiss();
566 m_loadNoticeInfoBar->Dismiss();
567
568 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
569 statusBar->ClearWarningMessages( "load" );
570
571 WX_PROGRESS_REPORTER progressReporter( this, is_new ? _( "Create PCB" ) : _( "Load PCB" ), 1, PR_CAN_ABORT );
572 WX_STRING_REPORTER loadReporter;
573 LOAD_INFO_REPORTER_SCOPE loadReporterScope( &loadReporter );
574
575 // No save prompt (we already prompted above), and only reset to a new blank board if new
576 Clear_Pcb( false, !is_new );
577
579
580 if( !is_new )
581 pluginType = PCB_IO_MGR::FindPluginTypeFromBoardPath( fullFileName, aCtl );
582
583 if( pluginType == PCB_IO_MGR::FILE_TYPE_NONE )
584 {
585 progressReporter.Hide();
586 DisplayErrorMessage( this, _( "File format is not supported" ), wxEmptyString );
587 return false;
588 }
589
590 bool converted = pluginType != PCB_IO_MGR::LEGACY && pluginType != PCB_IO_MGR::KICAD_SEXP;
591
592 // Loading a project should only be done under carefully considered circumstances.
593
594 // The calling code should know not to ask me here to change projects unless
595 // it knows what consequences that will have on other KIFACEs running and using
596 // this same PROJECT. It can be very harmful if that calling code is stupid.
598 bool setProject;
599
600 if( Kiface().IsSingle() || !( aCtl & KICTL_NONKICAD_ONLY ) )
601 setProject = pro.GetFullPath() != mgr->Prj().GetProjectFullName();
602 else
603 setProject = Prj().GetProjectFullName().IsEmpty();
604
605 if( setProject )
606 {
607 // calls SaveProject
609
611 mgr->UnloadProject( &mgr->Prj() );
612
613 mgr->LoadProject( pro.GetFullPath() );
614
615 if( Kiface().IsSingle() )
616 {
617 // Standalone opens can switch to a different project. Preload libraries after the
618 // project switch so the board load sees project-local library tables.
621 }
622
623 // Do not allow saving a project if one doesn't exist. This normally happens if we are
624 // opening a board that has been moved from its project folder.
625 // For converted projects, we don't want to set the read-only flag because we want a
626 // project to be saved for the new file in case things like netclasses got migrated.
627 Prj().SetReadOnly( !pro.Exists() && !converted );
628 }
629
630 // Crash-recovery: when zip-format autosave is active, look for autosave files newer than
631 // the saved board and offer to recover them before the load happens.
632 if( !is_new )
633 CheckForAutosaveFiles( wx_filename.GetPath(), { FILEEXT::KiCadPcbFileExtension } );
634
635 // custom rules the importer derived, saved with the board once its name is known
636 wxString importedRules;
637
638 if( is_new )
639 {
640 // Link the existing blank board to the new project
641 GetBoard()->SetProject( &Prj() );
642
643 GetBoard()->SetFileName( fullFileName );
644
645 OnModify();
646 }
647 else
648 {
649 BOARD* loadedBoard = nullptr; // it will be set to non-NULL if loaded OK
650 bool failedLoad = false;
651
652 // importer template footprints, captured at load for reconciliation
653 std::vector<std::unique_ptr<FOOTPRINT>> importedLibFootprints;
654
655 try
656 {
657 std::map<std::string, UTF8> props;
658
660 props.insert( m_importProperties->begin(), m_importProperties->end() );
661
662 // PCB_IO_EAGLE uses these to center the BOARD
663 props["page_width"] = std::to_string( GetPageSizeIU().x );
664 props["page_height"] = std::to_string( GetPageSizeIU().y );
665
666#if USE_INSTRUMENTATION
667 // measure the time to load a BOARD.
668 int64_t startTime = GetRunningMicroSecs();
669#endif
670 BOARD_LOADER::OPTIONS loaderOptions;
671 loaderOptions.properties = &props;
672 loaderOptions.progress_reporter = &progressReporter;
673 loaderOptions.reporter = config()->m_System.show_import_issues
674 ? static_cast<REPORTER*>( &loadReporter )
675 : static_cast<REPORTER*>( &NULL_REPORTER::GetInstance() );
676 loaderOptions.initialize_after_load = false;
677
678 loaderOptions.post_load_hook =
679 [&]( PCB_IO& aPlugin )
680 {
681 importedRules = aPlugin.GetImportedDesignRules();
682
683 if( !( aCtl & KICTL_IMPORT_LIB ) )
684 return;
685
686 try
687 {
688 for( FOOTPRINT* fp : aPlugin.GetImportedCachedLibraryFootprints() )
689 importedLibFootprints.emplace_back( fp );
690 }
691 catch( const IO_ERROR& )
692 {
693 // no cached library, reconcile from placed only
694 }
695 };
696
697 loaderOptions.plugin_configurator =
698 [&]( PCB_IO& aPlugin )
699 {
700 if( LAYER_MAPPABLE_PLUGIN* mappable_pi =
701 dynamic_cast<LAYER_MAPPABLE_PLUGIN*>( &aPlugin ) )
702 {
703 if( !ADVANCED_CFG::GetCfg().m_ImportSkipLayerMapping )
704 {
705 const auto layerMapCallback =
706 [this]( const std::vector<INPUT_LAYER_DESC>& aLayers )
707 {
708 return DIALOG_MAP_LAYERS::RunModal( this, aLayers );
709 };
710
711 mappable_pi->RegisterCallback( layerMapCallback );
712 }
713 }
714
715 if( PROJECT_CHOOSER_PLUGIN* chooser_pi =
716 dynamic_cast<PROJECT_CHOOSER_PLUGIN*>( &aPlugin ) )
717 {
718 const auto chooseProjectCallback =
719 [this]( const std::vector<IMPORT_PROJECT_DESC>& aProjects )
720 {
721 return DIALOG_IMPORT_CHOOSE_PROJECT::RunModal( this, aProjects );
722 };
723
724 chooser_pi->RegisterCallback( chooseProjectCallback );
725 }
726
727 aPlugin.SetQueryUserCallback(
728 [&]( wxString aTitle, int aIcon, wxString aMessage, wxString aAction ) -> bool
729 {
730 KIDIALOG dlg( nullptr, aMessage, aTitle, wxOK | wxCANCEL | aIcon );
731
732 if( !aAction.IsEmpty() )
733 dlg.SetOKLabel( aAction );
734
735 dlg.DoNotShowCheckbox( aMessage, 0 );
736
737 return dlg.ShowModal() == wxID_OK;
738 } );
739 };
740
741 std::unique_ptr<BOARD> loaded = BOARD_LOADER::Load( fullFileName, pluginType, &Prj(), loaderOptions );
742
743 if( loaded && props.count( IMPORT_PROJ_PROPS::NET_NAME_MAP ) )
744 {
745 std::optional<std::map<wxString, wxString>> netNames =
747
748 if( !netNames )
749 THROW_IO_ERROR( _( "Invalid imported net-name map." ) );
750
751 if( !ApplyImportedNetNameMap( *loaded, *netNames, loadReporter ) )
752 THROW_IO_ERROR( _( "Cannot apply imported net-name map to the board." ) );
753 }
754
755 loadedBoard = loaded.release();
756
757#if USE_INSTRUMENTATION
758 int64_t stopTime = GetRunningMicroSecs();
759 printf( "PCB_IO::Load(): %u usecs\n", stopTime - startTime );
760#endif
761 }
762 catch( const FUTURE_FORMAT_ERROR& ffe )
763 {
764 msg.Printf( _( "Error loading PCB '%s'." ), fullFileName );
765 progressReporter.Hide();
766 DisplayErrorMessage( this, msg, ffe.Problem() );
767
768 failedLoad = true;
769 }
770 catch( const IO_CANCELLED& )
771 {
772 // A user-cancelled load is not an error; abandon it without a dialog.
773 failedLoad = true;
774 }
775 catch( const IO_ERROR& ioe )
776 {
777 msg.Printf( _( "Error loading PCB '%s'." ), fullFileName );
778 progressReporter.Hide();
779 DisplayErrorMessage( this, msg, ioe.What() );
780
781 failedLoad = true;
782 }
783 catch( const std::bad_alloc& )
784 {
785 msg.Printf( _( "Memory exhausted loading PCB '%s'" ), fullFileName );
786 progressReporter.Hide();
787 DisplayErrorMessage( this, msg, wxEmptyString );
788
789 failedLoad = true;
790 }
791
792 if( failedLoad || !loadedBoard )
793 {
794 // We didn't create a new blank board above, so do that now
795 Clear_Pcb( false );
796
797 // Show any messages collected before the failure
798 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
799 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
800
801 return false;
802 }
803
804 if( converted && GetPcbNewSettings()->m_ImportKeepKiCadLayerNames )
805 {
806 for( PCB_LAYER_ID layer : loadedBoard->GetEnabledLayers().Seq() )
807 loadedBoard->SetLayerName( layer, wxEmptyString );
808 }
809
810 // This fixes a focus issue after the progress reporter is done on GTK. It shouldn't
811 // cause any issues on macOS and Windows. If it does, it will have to be conditionally
812 // compiled.
813 Raise();
814
815 // Skip (possibly expensive) connectivity build here; we build it below after load
816 progressReporter.AddPhases( 1 );
817 progressReporter.AdvancePhase( _( "Finalizing board" ) );
818 progressReporter.KeepRefreshing();
819
820 PROF_TIMER postLoadTimer;
821 SetBoard( loadedBoard, false, &progressReporter );
822 wxLogTrace( traceAllegroPerf, wxT( "Post-load SetBoard: %.3f ms" ),
823 postLoadTimer.msecs( true ) );
824
825 if( loadedBoard->m_LegacyDesignSettingsLoaded )
826 {
827 Prj().SetReadOnly( false );
828
829 // Before we had a copper edge clearance setting, the edge line widths could be used
830 // as a kludge to control them. So if there's no setting then infer it from the
831 // edge widths.
832 if( !loadedBoard->m_LegacyCopperEdgeClearanceLoaded )
833 {
834 // Do not show the inferred edge clearance warning dialog when loading third
835 // party boards. For some reason the dialog completely hangs all of KiCad and
836 // the imported board cannot be saved.
837 int edgeClearance = inferLegacyEdgeClearance( loadedBoard, !converted );
838 loadedBoard->GetDesignSettings().m_CopperEdgeClearance = edgeClearance;
839 }
840
841 // On save; design settings will be removed from the board
842 loadedBoard->SetModified();
843 }
844
845 // Move legacy view settings to local project settings
846 if( !loadedBoard->m_LegacyVisibleLayers.test( Rescue ) )
847 {
849 loadedBoard->SetModified();
850 }
851
853 {
855 loadedBoard->SetModified();
856 }
857
858 if( !loadedBoard->SynchronizeComponentClasses( std::unordered_set<wxString>() ) )
859 {
860 m_infoBar->RemoveAllButtons();
861 m_infoBar->AddCloseButton();
862 m_infoBar->ShowMessage( _( "Could not load component class assignment rules" ),
863 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::GENERIC );
864 }
865
866 // we should not ask PCB_IOs to do these items:
867 loadedBoard->BuildListOfNets();
868 wxLogTrace( traceAllegroPerf, wxT( "Post-load BuildListOfNets: %.3f ms" ),
869 postLoadTimer.msecs( true ) );
870
871 progressReporter.KeepRefreshing();
872
873 m_toolManager->RunAction( PCB_ACTIONS::repairBoard, true);
874 wxLogTrace( traceAllegroPerf, wxT( "Post-load repairBoard: %.3f ms" ),
875 postLoadTimer.msecs( true ) );
876
877 progressReporter.KeepRefreshing();
878
880 wxLogTrace( traceAllegroPerf, wxT( "Post-load rehatchShapes: %.3f ms" ),
881 postLoadTimer.msecs( true ) );
882
883 progressReporter.KeepRefreshing();
884
885 if( loadedBoard->IsModified() )
886 OnModify();
887 else
888 GetScreen()->SetContentModified( false );
889
890 if( ( pluginType == PCB_IO_MGR::LEGACY )
891 || ( pluginType == PCB_IO_MGR::KICAD_SEXP
893 && loadedBoard->GetGenerator().Lower() != wxT( "gerbview" ) ) )
894 {
895 m_infoBar->RemoveAllButtons();
896 m_infoBar->AddCloseButton();
897 m_infoBar->ShowMessage( _( "This file was created by an older version of KiCad. "
898 "It will be converted to the new format when saved." ),
899 wxICON_WARNING, WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE );
900 }
901
902 // extract a project fp library and re-link board FPIDs so update-from-schematic works
903 if( aCtl & KICTL_IMPORT_LIB )
904 reconcileImportedFootprintLibraries( std::move( importedLibFootprints ), fullFileName );
905 }
906
907 {
908 wxString fname;
909
910 if( !previousBoardFileName.IsEmpty() && ( aCtl & KICTL_NONKICAD_ONLY ) && !setProject )
911 {
912 fname = previousBoardFileName;
913 }
914 else
915 {
916 wxFileName fn;
917
918 fn.SetPath( Prj().GetProjectPath() );
919 fn.SetName( Prj().GetProjectName() );
921
922 fname = fn.GetFullPath();
923
924 fname.Replace( WIN_STRING_DIR_SEP, UNIX_STRING_DIR_SEP );
925 }
926
927 GetBoard()->SetFileName( fname );
928 }
929
930 SaveImportedDesignRules( importedRules, wxFileName( GetBoard()->GetDesignRulesPath() ), loadReporter );
931
932 // Lock the file newly opened:
933 m_file_checker.reset( lock.release() );
934
935 if( !converted )
936 UpdateFileHistory( GetBoard()->GetFileName() );
937
938 std::vector<ZONE*> toFill;
939
940 // Rebuild list of nets (full ratsnest rebuild)
941 PROF_TIMER connectivityTimer;
942 GetBoard()->BuildConnectivity( &progressReporter );
943 wxLogTrace( traceAllegroPerf, wxT( "Post-load BuildConnectivity: %.3f ms" ),
944 connectivityTimer.msecs( true ) );
945
946 // Load project settings after setting up board; some of them depend on the nets list
949 wxLogTrace( traceAllegroPerf, wxT( "Post-load LoadProjectSettings+DrawingSheet: %.3f ms" ),
950 connectivityTimer.msecs( true ) );
951
952 // Resolve DRC exclusions after project settings are loaded
953 ResolveDRCExclusions( true );
954
955 // Initialise caches used by component classes
957
958 // Initialise time domain tuning caches
960 wxLogTrace( traceAllegroPerf, wxT( "Post-load DRC+ComponentClass+Tuning caches: %.3f ms" ),
961 connectivityTimer.msecs( true ) );
962
963 // Syncs the UI (appearance panel, etc) with the loaded board and project
965 wxLogTrace( traceAllegroPerf, wxT( "Post-load OnBoardLoaded: %.3f ms" ),
966 connectivityTimer.msecs( true ) );
967 wxLogTrace( traceAllegroPerf, wxT( "=== Post-load pipeline total: %.3f ms ===" ),
968 connectivityTimer.msecs() );
969
970 // Refresh the 3D view, if any
971 if( EDA_3D_VIEWER_FRAME* our3DViewer = GetOur3DViewerFrame() )
972 our3DViewer->NewDisplay();
973
974#if 0 && defined(DEBUG)
975 // Output the board object tree to stdout, but please run from command prompt:
976 GetBoard()->Show( 0, std::cout );
977#endif
978
979 // from EDA_APPL which was first loaded BOARD only:
980 {
981 /* For an obscure reason the focus is lost after loading a board file
982 * when starting up the process.
983 * (seems due to the recreation of the layer manager after loading the file)
984 * Give focus to main window and Drawpanel
985 * must be done for these 2 windows (for an obscure reason ...)
986 * Linux specific
987 * This is more a workaround than a fix.
988 */
989 SetFocus();
990 GetCanvas()->SetFocus();
991 }
992
993 // The project manager and any project switch above both ran this before the loaded board was installed
995
996 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
997 statusBar->AddWarningMessages( "load", loadReporter.GetMessages() );
998
999 // A standalone editor has no project manager to attach the git session for it.
1001
1002 return true;
1003}
1004
1005
1006bool PCB_EDIT_FRAME::SavePcbFile( const wxString& aFileName, bool addToHistory,
1007 bool aChangeProject )
1008{
1009 // please, keep it simple. prompting goes elsewhere.
1010 wxFileName pcbFileName = aFileName;
1011
1012 if( pcbFileName.GetExt() == FILEEXT::LegacyPcbFileExtension )
1013 pcbFileName.SetExt( FILEEXT::KiCadPcbFileExtension );
1014
1015 // Write through symlinks, don't replace them
1017
1018 if( !IsWritable( pcbFileName ) )
1019 {
1020 wxString msg = wxString::Format( _( "Insufficient permissions to write file '%s'." ),
1021 pcbFileName.GetFullPath() );
1022
1023 DisplayError( this, msg );
1024 return false;
1025 }
1026
1027 // TODO: these will break if we ever go multi-board
1028 wxFileName projectFile( pcbFileName );
1029 wxFileName rulesFile( pcbFileName );
1030 wxString msg;
1031
1032 projectFile.SetExt( FILEEXT::ProjectFileExtension );
1033 rulesFile.SetExt( FILEEXT::DesignRulesFileExtension );
1034
1035 if( projectFile.FileExists() )
1036 {
1038 }
1039 else if( aChangeProject )
1040 {
1041 Prj().SetReadOnly( false );
1042 GetSettingsManager()->SaveProjectAs( projectFile.GetFullPath() );
1043 }
1044
1045 wxFileName currentRules( GetBoard()->GetDesignRulesPath() );
1046
1047 if( currentRules.FileExists() && !rulesFile.FileExists() && aChangeProject )
1048 KiCopyFile( currentRules.GetFullPath(), rulesFile.GetFullPath(), msg );
1049
1050 if( !msg.IsEmpty() )
1051 {
1052 DisplayError( this, wxString::Format( _( "Error saving custom rules file '%s'." ),
1053 rulesFile.GetFullPath() ) );
1054 }
1055
1056 if( projectFile.FileExists() )
1057 {
1058 // Save various DRC parameters, such as violation severities (which may have been
1059 // edited via the DRC dialog as well as the Board Setup dialog), DRC exclusions, etc.
1061
1064 }
1065
1067
1068 wxString lowerTxt;
1069
1070 // On Windows, ensure the target file is writeable by clearing problematic attributes like
1071 // hidden or read-only. This can happen when files are synced via cloud services.
1072 if( pcbFileName.FileExists() )
1073 KIPLATFORM::IO::MakeWriteable( pcbFileName.GetFullPath() );
1074
1075 try
1076 {
1078
1079 pi->SaveBoard( pcbFileName.GetFullPath(), *GetBoard(), nullptr );
1080 }
1081 catch( const IO_ERROR& ioe )
1082 {
1083 DisplayError( this, wxString::Format( _( "Error saving board file '%s'.\n%s" ),
1084 pcbFileName.GetFullPath(),
1085 ioe.What() ) );
1086 return false;
1087 }
1088
1089 WX_STRING_REPORTER backupReporter;
1090
1091 if( !Kiface().IsSingle() )
1092 GetSettingsManager()->TriggerBackupIfNeeded( backupReporter );
1093
1094 GetBoard()->SetFileName( pcbFileName.GetFullPath() );
1095
1096 // Update the lock in case it was a Save As
1097 LockFile( pcbFileName.GetFullPath() );
1098
1099 // Put the saved file in File History if requested
1100 if( addToHistory )
1101 UpdateFileHistory( GetBoard()->GetFileName() );
1102
1103 lowerTxt.Printf( _( "File '%s' saved." ), pcbFileName.GetFullPath() );
1104
1105 SetStatusText( lowerTxt, 0 );
1106
1107 // Get rid of the old version conversion warning, or any other dismissable warning :)
1108 if( m_infoBar->GetMessageType() == WX_INFOBAR::MESSAGE_TYPE::OUTDATED_SAVE )
1109 m_infoBar->Dismiss();
1110
1111 if( m_infoBar->IsShownOnScreen() && m_infoBar->HasCloseButton() )
1112 m_infoBar->Dismiss();
1113
1114 if( backupReporter.HasMessage() )
1115 {
1116 wxString backupMsg = backupReporter.GetMessages();
1117 m_infoBar->ShowMessageFor( backupMsg.Trim(), 10000, wxICON_WARNING );
1118 }
1119
1120 GetScreen()->SetContentModified( false );
1121 UpdateTitle();
1123
1124 // Capture entire project state for PCB save events. Skip when running standalone
1125 // without a project loaded - the save path can land anywhere on the filesystem and
1126 // there is no project context for a snapshot to live under.
1127 if( !Prj().IsNullProject() )
1128 {
1129 Kiway().LocalHistory().RunRegisteredSaversAndCommit( Prj().GetProjectPath(), wxS( "PCB Save" ), wxS( "pcb" ) );
1130
1131 // Drop the autosave file for the board we just persisted. Scope to the PCB
1132 // source so a concurrent open eeschema does not lose recovery data for an
1133 // unsaved schematic sheet. RunRegisteredSaversAndCommit above is a no-op when
1134 // format is ZIP; this call is conversely a no-op in INCREMENTAL mode.
1135 Kiway().LocalHistory().RemoveAutosaveFiles( Prj().GetProjectPath(), { pcbFileName.GetFullPath() } );
1136 }
1137
1138 if( m_autoSaveTimer )
1139 m_autoSaveTimer->Stop();
1140
1141 m_autoSavePending = false;
1142 m_autoSaveRequired = false;
1143
1145
1146 return true;
1147}
1148
1149
1150bool PCB_EDIT_FRAME::SavePcbCopy( const wxString& aFileName, bool aCreateProject, bool aHeadless )
1151{
1152 wxFileName pcbFileName( aFileName );
1153
1154 if( !IsWritable( pcbFileName ) )
1155 {
1156 if( !aHeadless )
1157 {
1158 DisplayError( this, wxString::Format( _( "Insufficient permissions to write file '%s'." ),
1159 pcbFileName.GetFullPath() ) );
1160 }
1161 return false;
1162 }
1163
1164 // Save various DRC parameters, such as violation severities (which may have been
1165 // edited via the DRC dialog as well as the Board Setup dialog), DRC exclusions, etc.
1167
1171
1172 // On Windows, ensure the target file is writeable by clearing problematic attributes like
1173 // hidden or read-only. This can happen when files are synced via cloud services.
1174 if( pcbFileName.FileExists() )
1175 KIPLATFORM::IO::MakeWriteable( pcbFileName.GetFullPath() );
1176
1177 try
1178 {
1180
1181 wxASSERT( pcbFileName.IsAbsolute() );
1182
1183 pi->SaveBoard( pcbFileName.GetFullPath(), *GetBoard(), nullptr );
1184 }
1185 catch( const IO_ERROR& ioe )
1186 {
1187 if( !aHeadless )
1188 {
1189 DisplayError( this, wxString::Format( _( "Error saving board file '%s'.\n%s" ),
1190 pcbFileName.GetFullPath(),
1191 ioe.What() ) );
1192 }
1193
1194 return false;
1195 }
1196
1197 wxFileName projectFile( pcbFileName );
1198 wxFileName rulesFile( pcbFileName );
1199 wxString msg;
1200
1201 projectFile.SetExt( FILEEXT::ProjectFileExtension );
1202 rulesFile.SetExt( FILEEXT::DesignRulesFileExtension );
1203
1204 if( aCreateProject && !projectFile.FileExists() )
1205 GetSettingsManager()->SaveProjectCopy( projectFile.GetFullPath() );
1206
1207 wxFileName currentRules( GetBoard()->GetDesignRulesPath() );
1208
1209 if( aCreateProject && currentRules.FileExists() && !rulesFile.FileExists() )
1210 KiCopyFile( currentRules.GetFullPath(), rulesFile.GetFullPath(), msg );
1211
1212 if( !msg.IsEmpty() && !aHeadless )
1213 {
1214 DisplayError( this, wxString::Format( _( "Error saving custom rules file '%s'." ),
1215 rulesFile.GetFullPath() ) );
1216 }
1217
1218 return true;
1219}
1220
1221
1222bool PCB_EDIT_FRAME::importFile( const wxString& aFileName, int aFileType,
1223 const std::map<std::string, UTF8>* aProperties )
1224{
1225 NULLER raiiNuller( (void*&) m_importProperties );
1226
1227 m_importProperties = aProperties;
1228
1230
1231 switch( fileType )
1232 {
1234 case PCB_IO_MGR::EAGLE:
1244 case PCB_IO_MGR::PADS:
1246 {
1247 int ctl = KICTL_NONKICAD_ONLY;
1248
1250 ctl |= KICTL_IMPORT_LIB;
1251
1252 return OpenProjectFiles( std::vector<wxString>( 1, aFileName ), ctl );
1253 }
1254
1255 default:
1256 return false;
1257 }
1258}
1259
1260
1262 std::vector<std::unique_ptr<FOOTPRINT>> aDefinitions, const wxString& aBoardPath )
1263{
1265
1266 ReconcileImportedFootprints( std::move( aDefinitions ), *GetBoard(), Prj(), aBoardPath,
1268
1269 if( reporter.HasMessage() )
1270 {
1271 if( KISTATUSBAR* statusBar = dynamic_cast<KISTATUSBAR*>( GetStatusBar() ) )
1272 statusBar->AddWarningMessages( "load", reporter.GetMessages() );
1273 }
1274}
1275
1276
1278{
1280
1281 dlg.ShowModal();
1282
1283 return 0;
1284}
1285
1286
1288{
1290 dlg.ShowModal();
1291
1292 return 0;
1293}
const char * name
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
void SetContentModified(bool aModified=true)
Definition base_screen.h:55
int GenerateODBPPFiles(const TOOL_EVENT &aEvent)
int New(const TOOL_EVENT &aEvent)
int Revert(const TOOL_EVENT &aEvent)
int GenIPC2581File(const TOOL_EVENT &aEvent)
int Open(const TOOL_EVENT &aEvent)
int OpenNonKicadBoard(const TOOL_EVENT &aEvent)
static std::unique_ptr< BOARD > Load(const wxString &aFileName, PCB_IO_MGR::PCB_FILE_T aFormat, PROJECT *aProject, const OPTIONS &aOptions)
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
bool m_LegacyDesignSettingsLoaded
True if the legacy board design settings were loaded from a file.
Definition board.h:565
GAL_SET m_LegacyVisibleItems
Definition board.h:562
LENGTH_DELAY_CALCULATION * GetLengthCalculation() const
Returns the track length calculator.
Definition board.h:1703
void BuildListOfNets()
Definition board.h:1189
void SetFileName(const wxString &aFileName)
Definition board.h:452
bool BuildConnectivity(PROGRESS_REPORTER *aReporter=nullptr)
Build or rebuild the board connectivity database for the board, especially the list of connected item...
Definition board.cpp:369
void SynchronizeNetsAndNetClasses(bool aResetTrackAndViaSizes)
Copy NETCLASS info to each NET, based on NET membership in a NETCLASS.
Definition board.cpp:3268
bool SetLayerName(PCB_LAYER_ID aLayer, const wxString &aLayerName)
Changes the name of the layer given by aLayer.
Definition board.cpp:978
LSET m_LegacyVisibleLayers
Visibility settings stored in board prior to 6.0, only used for loading legacy files.
Definition board.h:561
void SetProject(PROJECT *aProject, bool aReferenceOnly=false)
Link a board to a given project.
Definition board.cpp:379
const wxString & GetFileName() const
Definition board.h:454
int GetFileFormatVersionAtLoad() const
Definition board.h:585
const wxString & GetGenerator() const
Definition board.h:643
void ClearProject()
Definition board.cpp:420
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
COMPONENT_CLASS_MANAGER & GetComponentClassManager()
Gets the component class manager.
Definition board.h:1708
bool SynchronizeComponentClasses(const std::unordered_set< wxString > &aNewSheetPaths) const
Copy component class / component class generator information from the project settings.
Definition board.cpp:3312
bool m_LegacyCopperEdgeClearanceLoaded
Definition board.h:566
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
int GetCount() const
Return the number of objects in the list.
Definition collector.h:79
void RebuildRequiredCaches(FOOTPRINT *aFootprint=nullptr) const
Rebuilds any caches that may be required by custom assignment rules.
static std::vector< IMPORT_PROJECT_DESC > RunModal(wxWindow *aParent, const std::vector< IMPORT_PROJECT_DESC > &aProjectDesc)
Create and show a dialog (modal) and returns the data from it after completion.
static std::map< wxString, PCB_LAYER_ID > RunModal(wxWindow *aParent, const std::vector< INPUT_LAYER_DESC > &aLayerDesc)
Create and show a dialog (modal) and returns the data from it after completion.
int ShowModal() override
Create and handle a window for the 3d viewer connected to a Kiway and a pcbboard.
virtual APP_SETTINGS_BASE * config() const
Return the settings object used in SaveSettings(), and is overloaded in KICAD_MANAGER_FRAME.
void CheckForAutosaveFiles(const wxString &aProjectPath, const std::vector< wxString > &aExtensions)
Check for autosave files newer than their source files for the given project.
SETTINGS_MANAGER * GetSettingsManager() const
WX_INFOBAR * m_infoBar
wxTimer * m_autoSaveTimer
void UpdateFileHistory(const wxString &FullFileName, FILE_HISTORY *aFileHistory=nullptr)
Update the list of recently opened files.
wxString GetMruPath() const
bool IsWritable(const wxFileName &aFileName, bool aVerbose=true)
Check if aFileName can be written.
virtual void ClearFileHistory()
Remove all files from the file history.
wxString GetFileFromHistory(int cmdId, const wxString &type, FILE_HISTORY *aFileHistory=nullptr)
Fetch the file name from the file history list.
void SetMruPath(const wxString &aPath)
WX_INFOBAR * GetInfoBar()
void ReleaseFile()
Release the current file marked in use.
std::unique_ptr< LOCKFILE > m_file_checker
Prevents opening same file multiple times.
bool LockFile(const wxString &aFileName)
Mark a schematic file as being in use.
void RefreshGitCommitPane()
Attach the git session if needed and refresh the version-control pane, when it is shown.
void SetFocus() override
void SetModified()
Definition eda_item.cpp:270
bool IsModified() const
Definition eda_item.h:130
bool GetCreateNewProject() const
Gets the selected state of the create new project option.
bool IsAttachedToDialog() const
Gets if this hook has attached controls to a dialog box.
static const std::vector< KICAD_T > AllBoardItems
A scan list for all editable board items.
Definition collectors.h:38
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()
virtual const wxString Problem() const
what was the problem?
Helper class to create more flexible dialogs, including 'do not show again' checkbox handling.
Definition kidialog.h:38
void DoNotShowCheckbox(wxString file, int line)
Shows the 'do not show again' checkbox.
Definition kidialog.cpp:51
int ShowModal() override
Definition kidialog.cpp:89
KISTATUSBAR is a wxStatusBar suitable for Kicad manager.
Definition kistatusbar.h:50
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
LOCAL_HISTORY & LocalHistory()
Return the LOCAL_HISTORY associated with this KIWAY.
Definition kiway.h:460
Plugin class for import plugins that support remappable layers.
void SynchronizeTuningProfileProperties() const
Ensure time domain properties provider is synced with board / project settings if required.
bool RunRegisteredSaversAndCommit(const wxString &aProjectPath, const wxString &aTitle, const wxString &aTagFileType=wxEmptyString)
Run all registered savers and, if any staged changes differ from HEAD, create a commit.
void RemoveAutosaveFiles(const wxString &aProjectPath) const
Remove every autosave file under the project at aProjectPath regardless of which source it shadowed.
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
Definition raii.h:34
static REPORTER & GetInstance()
Definition reporter.cpp:207
static wxString GetDefaultUserProjectsPath()
Gets the default path we point users to create projects.
Definition paths.cpp:137
static TOOL_ACTION repairBoard
static TOOL_ACTION rehatchShapes
const VECTOR2I GetPageSizeIU() const override
Works off of GetPageSettings() to return the size of the paper page in the internal units of this par...
PCBNEW_SETTINGS * GetPcbNewSettings() const
PCB_DRAW_PANEL_GAL * GetCanvas() const override
Return a pointer to GAL-based canvas of given EDA draw frame.
PCB_SCREEN * GetScreen() const override
Return a pointer to a BASE_SCREEN or one of its derivatives.
BOARD * GetBoard() const
EDA_3D_VIEWER_FRAME * GetOur3DViewerFrame()
virtual void UpdateStatusBar() override
Update the status bar information.
The main frame for Pcbnew.
void LoadDrawingSheet()
Load the drawing sheet file.
void ResolveDRCExclusions(bool aCreateMarkers)
If aCreateMarkers then create DRC exclusion markers from the serialized data.
void SetBoard(BOARD *aBoard, PROGRESS_REPORTER *aReporter=nullptr) override
Set the m_pcb member in such as way as to ensure deleting any previous BOARD.
void OnModify() override
Must be called after a board change to set the modified flag.
bool CloseFootprintFieldsTableDialog()
bool ReloadFromDisk()
Reload the board from disk.
void OnClearFileHistory(wxCommandEvent &aEvent)
bool SaveBoard(bool aSaveAs=false, bool aSaveCopy=false)
bool OpenProjectFiles(const std::vector< wxString > &aFileSet, int aCtl=0) override
Load a KiCad board (.kicad_pcb) from aFileName.
void ProjectChanged() override
Notification event that the project has changed.
WX_INFOBAR * m_loadNoticeInfoBar
Secondary infobar that stacks above the main one; reserved for load-time notices (currently the WRL -...
void SaveProjectLocalSettings() override
Save changes to the project local settings.
bool SavePcbCopy(const wxString &aFileName, bool aCreateProject=false, bool aHeadless=false)
Write the board data structures to aFileName.
bool IsContentModified() const override
Get if the current board has been modified but not saved.
bool LoadProjectSettings()
Load the current project's file configuration settings which are pertinent to this PCB_EDIT_FRAME ins...
bool Clear_Pcb(bool doAskAboutUnsavedChanges, bool aFinal=false)
Delete all and reinitialize the current board.
Definition initpcb.cpp:38
void OnBoardLoaded()
Update the state of the GUI after a new board is loaded or created.
void UpdateTitle()
Set the main window title bar text.
int inferLegacyEdgeClearance(BOARD *aBoard, bool aShowUserMsg=true)
const std::map< std::string, UTF8 > * m_importProperties
void reconcileImportedFootprintLibraries(std::vector< std::unique_ptr< FOOTPRINT > > aDefinitions, const wxString &aBoardPath)
Reconcile the footprint-library references of a freshly imported non-KiCad board so that every board ...
bool SavePcbFile(const wxString &aFileName, bool addToHistory=true, bool aChangeProject=true)
Write the board data structures to a aFileName.
bool importFile(const wxString &aFileName, int aFileType, const std::map< std::string, UTF8 > *aProperties=nullptr)
Load the given filename but sets the path to the current project path.
void saveProjectSettings() override
Save any design-related project settings associated with this frame.
void OnFileHistory(wxCommandEvent &event)
static PLUGIN_REGISTRY * Instance()
Definition pcb_io_mgr.h:100
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
@ TARGET3001
TARGET 3001! project.
Definition pcb_io_mgr.h:77
@ GEDA_PCB
Geda PCB file formats.
Definition pcb_io_mgr.h:66
@ ALTIUM_DESIGNER
Definition pcb_io_mgr.h:59
@ LEGACY
Legacy Pcbnew file formats prior to s-expression.
Definition pcb_io_mgr.h:55
@ ALTIUM_CIRCUIT_MAKER
Definition pcb_io_mgr.h:57
@ ALTIUM_CIRCUIT_STUDIO
Definition pcb_io_mgr.h:58
@ CADSTAR_PCB_ARCHIVE
Definition pcb_io_mgr.h:60
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 bool ImportGeneratesProjectLibrary(PCB_FILE_T aFileType)
Return true when importing aFileType should materialize a project footprint library.
A base class that BOARD loading and saving plugins should derive from.
Definition pcb_io.h:78
Collect all BOARD_ITEM objects on a given layer.
Definition collectors.h:546
void Collect(BOARD_ITEM *aBoard, const std::vector< KICAD_T > &aTypes)
Test a BOARD_ITEM using this class's Inspector method, which does the collection.
void SetLayerId(PCB_LAYER_ID aLayerId)
Definition collectors.h:552
void PreloadDesignBlockLibraries(KIWAY *aKiway)
Starts a background job to preload the global and project design block libraries.
Definition pgm_base.cpp:946
A small class to help profiling.
Definition profile.h:46
double msecs(bool aSinceLast=false)
Definition profile.h:148
virtual void AdvancePhase() override
Use the next available virtual zone of the dialog progress bar.
void AddPhases(int aNumPhases) override
bool KeepRefreshing(bool aWait=false) override
Update the UI dialog.
Plugin class for import plugins that support choosing a project.
LSET m_VisibleLayers
Board settings.
GAL_SET m_VisibleItems
The GAL layers (aka items) that are turned on for viewing (.
virtual void SetReadOnly(bool aReadOnly=true)
Definition project.h:161
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:271
virtual PROJECT_LOCAL_SETTINGS & GetLocalSettings() const
Definition project.h:207
virtual const wxString AbsolutePath(const wxString &aFileName) const
Fix up aFileName if it is relative to the project's directory to be an absolute path and filename.
Definition project.cpp:501
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition project.cpp:295
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual bool HasMessage() const
Returns true if any messages were reported.
Definition reporter.h:143
void SaveProjectAs(const wxString &aFullPath, PROJECT *aProject=nullptr)
Set the currently loaded project path and saves it (pointers remain valid).
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
bool SaveProjectCopy(const wxString &aFullPath, PROJECT *aProject=nullptr)
Save a copy of the current project under the given path.
bool UnloadProject(PROJECT *aProject, bool aSave=true)
Save, unload and unregister the given PROJECT.
bool TriggerBackupIfNeeded(REPORTER &aReporter) const
Call BackupProject() if a new backup is needed according to the current backup policy.
PROJECT & Prj() const
A helper while we are not MDI-capable – return the one and only 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.
TOOL_MANAGER * m_toolManager
Generic, UI-independent tool event.
Definition tool_event.h:167
static void ResolvePossibleSymlinks(wxFileName &aFilename)
void Dismiss() override
Dismisses the infobar and updates the containing layout and AUI manager (if one is provided).
Multi-thread safe progress reporter dialog, intended for use of tasks that parallel reporting back of...
A wrapper for reporting to a wxString object.
Definition reporter.h:242
const wxString & GetMessages() const
Definition reporter.cpp:188
wxString EnsureFileExtension(const wxString &aFilename, const wxString &aExtension)
It's annoying to throw up nag dialogs when the extension isn't right.
Definition common.cpp:880
bool AskOverrideLock(wxWindow *aParent, const wxString &aMessage)
Display a dialog indicating the file is already open, with an option to reset the lock.
Definition confirm.cpp:38
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
bool HandleUnsavedChanges(wxWindow *aParent, const wxString &aMessage, const std::function< bool()> &aSaveFunction)
Display a dialog with Save, Cancel and Discard Changes buttons.
Definition confirm.cpp:146
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:192
This file is part of the common library.
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
Definition cvpcb.cpp:178
#define _(s)
Declaration of the eda_3d_viewer class.
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.
int RefreshGeneratedTables(BOARD &aBoard)
Bring every generated table on the board up to date and return how many were rebuilt.
void KiCopyFile(const wxString &aSrcPath, const wxString &aDestPath, wxString &aErrors)
Definition gestfich.cpp:416
#define WIN_STRING_DIR_SEP
Definition gestfich.h:42
#define UNIX_STRING_DIR_SEP
Definition gestfich.h:41
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
static const std::string ProjectFileExtension
static const std::string LegacyPcbFileExtension
static const std::string DesignRulesFileExtension
static const std::string KiCadPcbFileExtension
static wxString PcbFileWildcard()
bool SaveImportedDesignRules(const wxString &aRules, const wxFileName &aBoardPath, REPORTER &aReporter)
Save the custom rules an importer derived beside the board it produced.
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
PROJECT & Prj()
Definition kicad.cpp:730
#define KICTL_CREATE
caller thinks requested project files may not exist.
#define KICTL_REVERT
reverting to a previously-saved (KiCad) file.
#define KICTL_IMPORT_LIB
import all footprints into a project library.
#define KICTL_KICAD_ONLY
chosen file is from KiCad according to user
#define KICTL_NONKICAD_ONLY
chosen file is non-KiCad according to user
@ GAL_LAYER_ID_BITMASK_END
This is the end of the layers used for visibility bit masks in legacy board files.
Definition layer_ids.h:283
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ Edge_Cuts
Definition layer_ids.h:108
@ Rescue
Definition layer_ids.h:117
#define GAL_LAYER_INDEX(x)
Use this macro to convert a GAL layer to a 0-indexed offset from LAYER_VIAS.
Definition layer_ids.h:392
This file contains miscellaneous commonly used macros and functions.
std::optional< std::map< wxString, wxString > > SplitNetNameMap(const wxString &aValue)
Decode a net-name map property value, or nothing when the value is not one.
constexpr char NET_NAME_MAP[]
bool RegisterApplicationRestart(const wxString &aCommandLine)
Registers the application for restart with the OS with the given command line string to pass as args.
Definition unix/app.cpp:83
bool MakeWriteable(const wxString &aFilePath)
Ensures that a file has write permissions.
Definition unix/io.cpp:78
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:741
#define SEXPR_BOARD_FILE_VERSION
Current s-expression file format version. 2 was the last legacy format version.
bool AskLoadBoardFileName(PCB_EDIT_FRAME *aParent, wxString *aFileName, int aCtl=0)
Show a wxFileDialog asking for a BOARD filename to open.
bool AskSaveBoardFileName(PCB_EDIT_FRAME *aParent, wxString *aFileName, bool *aCreateProject)
Put up a wxFileDialog asking for a BOARD filename to save.
static const wxChar *const traceAllegroPerf
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
int64_t GetRunningMicroSecs()
An alternate way to calculate an elapsed time (in microsecondes) to class PROF_COUNTER.
#define NAMELESS_PROJECT
default name for nameless projects
Definition project.h:40
KIWAY Kiway(KFCTL_STANDALONE)
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
bool show_import_issues
Stored value for "show import issues" when importing non-KiCad designs to this application.
std::function< void(PCB_IO &)> plugin_configurator
std::function< void(PCB_IO &)> post_load_hook
const std::map< std::string, UTF8 > * properties
PROGRESS_REPORTER * progress_reporter
Variant of PARSE_ERROR indicating that a syntax or related error was likely caused by a file generate...
Container that describes file type info.
Definition io_base.h:43
std::vector< std::string > m_FileExtensions
Filter used for file pickers if m_IsFile is true.
Definition io_base.h:47
bool m_CanRead
Whether the IO can read this file type.
Definition io_base.h:52
virtual void PreloadLibraries(KIWAY *aKiway)
Definition kiway.h:298
std::string path
IbisParser parser & reporter
wxLogTrace helper definitions.
@ PCB_SHAPE_T
class PCB_SHAPE, a segment not on copper layers
Definition typeinfo.h:80
wxString AddFileExtListToFilter(const std::vector< std::string > &aExts)
Build the wildcard extension file dialog wildcard filter to add to the base message dialog.
wxString formatWildcardExt(const wxString &aWildcard)
Format wildcard extension to support case sensitive file dialogs.
Definition of file extensions used in Kicad.
#define PR_CAN_ABORT