KiCad PCB EDA Suite
Loading...
Searching...
No Matches
footprint_libraries_utils.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20#include <algorithm>
21#include <memory>
22#include <wx/ffile.h>
23#include <pgm_base.h>
24#include <kiface_base.h>
25#include <confirm.h>
26#include <kidialog.h>
27#include <macros.h>
28#include <string_utils.h>
29#include <pcb_edit_frame.h>
30#include <eda_list_dialog.h>
31#include <filter_reader.h>
33#include <validators.h>
35#include <tool/tool_manager.h>
36#include <tools/pcb_actions.h>
38#include <footprint.h>
39#include <zone.h>
40#include <pcb_group.h>
47#include <env_paths.h>
48#include <paths.h>
50#include <kiplatform/ui.h>
51#include <project_pcb.h>
56#include <reporter.h>
57#include <view/view_controls.h>
58#include <wx/filedlg.h>
59#include <wx/fswatcher.h>
60
61
62static constexpr int ID_MAKE_NEW_LIBRARY = 4173;
63
64
65// unique, "file local" translations:
66
67
68static const wxString INFO_LEGACY_LIB_WARN_EDIT(
69 _( "Writing/modifying legacy libraries (.mod files) is not allowed\n"\
70 "Please save the current library to the new .pretty format\n"\
71 "and update your footprint lib table\n"\
72 "to save your footprint (a .kicad_mod file) in the .pretty library folder" ) );
73
74static const wxString INFO_LEGACY_LIB_WARN_DELETE(
75 _( "Modifying legacy libraries (.mod files) is not allowed\n"\
76 "Please save the current library under the new .pretty format\n"\
77 "and update your footprint lib table\n"\
78 "before deleting a footprint" ) );
79
80
82{
83 wxFileName fn;
84
85 if( !aName.empty() )
86 {
87 fn = aName;
88 }
89 else
90 {
91 // Prompt the user for a footprint file to open.
92 static int lastFilterIndex = 0; // To store the last choice during a session.
93 wxString fileFiltersStr;
94 std::vector<std::string> allExtensions;
95 std::set<wxString> allWildcardsSet;
96
97 for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
98 {
99 IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
100
101 if( !pi )
102 continue;
103
104 const IO_BASE::IO_FILE_DESC& desc = pi->GetLibraryFileDesc();
105
106 if( !desc )
107 continue;
108
109 if( !fileFiltersStr.IsEmpty() )
110 fileFiltersStr += wxChar( '|' );
111
112 fileFiltersStr += desc.FileFilter();
113
114 for( const std::string& ext : desc.m_FileExtensions )
115 {
116 allExtensions.emplace_back( ext );
117 allWildcardsSet.insert( wxT( "*." ) + formatWildcardExt( ext ) + wxT( ";" ) );
118 }
119 }
120
121 wxString allWildcardsStr;
122
123 for( const wxString& wildcard : allWildcardsSet )
124 allWildcardsStr << wildcard;
125
126 fileFiltersStr = _( "All supported formats" ) + wxT( "|" ) + allWildcardsStr + wxT( "|" )
127 + fileFiltersStr;
128
129 wxFileDialog dlg( this, _( "Import Footprint" ), m_mruPath, wxEmptyString, fileFiltersStr,
130 wxFD_OPEN | wxFD_FILE_MUST_EXIST );
131
132 wxArrayString dummy1, dummy2;
133 const int nWildcards = wxParseCommonDialogsFilter( fileFiltersStr, dummy1, dummy2 );
134
135 if( lastFilterIndex >= 0 && lastFilterIndex < nWildcards )
136 dlg.SetFilterIndex( lastFilterIndex );
137
139
140 if( dlg.ShowModal() == wxID_CANCEL )
141 return nullptr;
142
143 lastFilterIndex = dlg.GetFilterIndex();
144
145 fn = dlg.GetPath();
146 }
147
148 if( !fn.IsOk() )
149 return nullptr;
150
151 if( !wxFileExists( fn.GetFullPath() ) )
152 {
153 wxString msg = wxString::Format( _( "File '%s' not found." ), fn.GetFullPath() );
154 DisplayError( this, msg );
155 return nullptr;
156 }
157
158 m_mruPath = fn.GetPath();
159
161
162 for( const auto& plugin : PCB_IO_MGR::PLUGIN_REGISTRY::Instance()->AllPlugins() )
163 {
164 IO_RELEASER<PCB_IO> pi( plugin.m_createFunc() );
165
166 if( !pi )
167 continue;
168
169 if( pi->GetLibraryFileDesc().m_FileExtensions.empty() )
170 continue;
171
172 if( pi->CanReadFootprint( fn.GetFullPath() ) )
173 {
174 fileType = plugin.m_type;
175 break;
176 }
177 }
178
180 {
181 DisplayError( this, _( "Not a footprint file." ) );
182 return nullptr;
183 }
184
185 std::unique_ptr<FOOTPRINT> footprint;
186 wxString footprintName;
187
188 try
189 {
191
192 // This is a direct user action, so surface any import warnings rather than
193 // relying on a reporter that only the board loader would have attached.
194 pi->SetReporter( &WXLOG_REPORTER::GetInstance() );
195
196 footprint = pi->ImportFootprint( fn.GetFullPath(), footprintName );
197
198 if( !footprint )
199 {
200 wxString msg = wxString::Format( _( "Unable to load footprint '%s' from '%s'" ),
201 footprintName, fn.GetFullPath() );
202 DisplayError( this, msg );
203 return nullptr;
204 }
205 }
206 catch( const IO_ERROR& ioe )
207 {
208 DisplayError( this, ioe.What() );
209
210 // if the footprint is not loaded, exit.
211 // However, even if an error happens, it can be loaded, because in KICAD and GPCB format,
212 // a fp library is a set of separate files, and the error(s) are not necessary when
213 // reading the selected file
214
215 if( !footprint )
216 return nullptr;
217 }
218
219 footprint->SetFPID( LIB_ID( wxEmptyString, footprintName ) );
220
221 // An import has no library home to key a tab on and must not replace the document being edited, so
222 // it gets its own unnamed tab that a later save-as promotes
223 // The plugin's own board does not survive the tab switch; ReloadFootprint reparents the
224 // footprint to the incoming board
225 footprint->SetParent( nullptr );
227
228 // AddFootprintToBoard takes ownership of the footprint from here on
229 FOOTPRINT* fp = footprint.get();
230
231 // Insert footprint in list
232 AddFootprintToBoard( footprint.release() );
233
234 // Display info :
235 SetMsgPanel( fp );
236 PlaceFootprint( fp );
237
238 fp->SetPosition( VECTOR2I( 0, 0 ) );
239
241 UpdateView();
242
243 // The import lives only in its tab until saved to a library, so flag it dirty or closing the tab
244 // would silently discard it
245 OnModify();
246
247 return fp;
248}
249
250
252{
253 wxFileName fn;
255
256 if( !aFootprint )
257 return;
258
259 fn.SetName( aFootprint->GetFPID().GetLibItemName() );
260
261 wxString wildcard = FILEEXT::KiCadFootprintLibFileWildcard();
262
264
265 if( !cfg->m_LastExportPath.empty() )
266 fn.SetPath( cfg->m_LastExportPath );
267 else
268 fn.SetPath( m_mruPath );
269
270 wxFileDialog dlg( this, _( "Export Footprint" ), fn.GetPath(), fn.GetFullName(),
271 wildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
272
274
275 if( dlg.ShowModal() == wxID_CANCEL )
276 return;
277
279 cfg->m_LastExportPath = fn.GetPath();
280
281 try
282 {
283 // Export as *.kicad_pcb format, using a strategy which is specifically chosen
284 // as an example on how it could also be used to send it to the system clipboard.
285
287
288 /* This footprint should *already* be "normalized" in a way such that
289 orientation is zero, etc., since it came from the Footprint Editor.
290
291 aFootprint->SetParent( 0 );
292 aFootprint->SetOrientation( 0 );
293 */
294
295 std::unique_ptr<FOOTPRINT> copy( static_cast<FOOTPRINT*>( aFootprint->Clone() ) );
296
297 pcb_io.FormatFootprintLibFile( copy.get() );
298
299 FILE* fp = wxFopen( fn.GetFullPath(), wxT( "wt" ) );
300
301 if( fp == nullptr )
302 {
303 DisplayErrorMessage( this, wxString::Format( _( "Insufficient permissions to write file '%s'." ),
304 fn.GetFullPath() ) );
305 return;
306 }
307
308 std::string prettyData = pcb_io.GetStringOutput( false );
309 KICAD_FORMAT::Prettify( prettyData, KICAD_FORMAT::FORMAT_MODE::NORMAL );
310
311 if( fprintf( fp, "%s", prettyData.c_str() ) < 0 || fclose( fp ) != 0 )
312 {
313 DisplayErrorMessage( this, wxString::Format( _( "Error writing file '%s'." ), fn.GetFullPath() ) );
314 return;
315 }
316 }
317 catch( const IO_ERROR& ioe )
318 {
319 DisplayError( this, ioe.What() );
320 return;
321 }
322
323 wxString msg = wxString::Format( _( "Footprint exported to file '%s'." ), fn.GetFullPath() );
324 DisplayInfoMessage( this, msg );
325}
326
327
328wxString PCB_BASE_EDIT_FRAME::CreateNewProjectLibrary( const wxString& aDialogTitle, const wxString& aLibName )
329{
330 return createNewLibrary( aDialogTitle, aLibName, wxEmptyString, LIBRARY_TABLE_SCOPE::PROJECT );
331}
332
333
334wxString PCB_BASE_EDIT_FRAME::CreateNewLibrary( const wxString& aDialogTitle, const wxString& aInitialPath )
335{
336 return createNewLibrary( aDialogTitle, wxEmptyString, aInitialPath );
337}
338
339
340wxString PCB_BASE_EDIT_FRAME::createNewLibrary( const wxString& aDialogTitle, const wxString& aLibName,
341 const wxString& aInitialPath, std::optional<LIBRARY_TABLE_SCOPE> aScope )
342{
343 // Kicad cannot write legacy format libraries, only .pretty new format because the legacy
344 // format cannot handle current features.
345 // The footprint library is actually a directory.
346
347 wxFileName fn;
348 bool doAdd = false;
349 bool isGlobal = false;
350 FILEDLG_HOOK_NEW_LIBRARY tableChooser( isGlobal );
351 FILEDLG_HOOK_NEW_LIBRARY* fileDlgHook = &tableChooser;
352
353 if( aScope )
354 fileDlgHook = nullptr;
355
356 if( aLibName.IsEmpty() )
357 {
358 fn = aInitialPath.IsEmpty() ? Prj().GetProjectPath() : aInitialPath;
359
360 if( !LibraryFileBrowser( aDialogTitle, false, fn, FILEEXT::KiCadFootprintLibPathWildcard(),
361 FILEEXT::KiCadFootprintLibPathExtension, false, fileDlgHook ) )
362 {
363 return wxEmptyString;
364 }
365
366 if( fileDlgHook )
367 {
368 isGlobal = fileDlgHook->GetUseGlobalTable();
370 }
371
372 doAdd = true;
373 }
374 else
375 {
377
378 if( !fn.IsAbsolute() )
379 {
380 fn.SetName( aLibName );
381 fn.MakeAbsolute( Prj().GetProjectPath() );
382 }
383 }
384
385 // We can save fp libs only using PCB_IO_MGR::KICAD_SEXP format (.pretty libraries)
387 wxString libPath = fn.GetFullPath();
388
389 try
390 {
392
393 bool writable = false;
394 bool exists = false;
395
396 try
397 {
398 writable = pi->IsLibraryWritable( libPath );
399 exists = true; // no exception was thrown, lib must exist.
400 }
401 catch( const IO_ERROR& )
402 {
403 // best efforts....
404 }
405
406 if( exists )
407 {
408 if( !writable )
409 {
410 wxString msg = wxString::Format( _( "Library %s is read only." ), libPath );
411 ShowInfoBarError( msg );
412 return wxEmptyString;
413 }
414 else
415 {
416 wxString msg = wxString::Format( _( "Library %s already exists." ), libPath );
417 KIDIALOG dlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
418 dlg.SetOKLabel( _( "Overwrite" ) );
419 dlg.DoNotShowCheckbox( __FILE__, __LINE__ );
420
421 if( dlg.ShowModal() == wxID_CANCEL )
422 return wxEmptyString;
423
424 pi->DeleteLibrary( libPath );
425 }
426 }
427
428 pi->CreateLibrary( libPath );
429 }
430 catch( const IO_ERROR& ioe )
431 {
432 DisplayError( this, ioe.What() );
433 return wxEmptyString;
434 }
435
436 if( doAdd && !AddLibrary( aDialogTitle, libPath, aScope ) )
437 return wxEmptyString;
438
439 return libPath;
440}
441
442
443wxString PCB_BASE_EDIT_FRAME::SelectLibrary( const wxString& aDialogTitle, const wxString& aListLabel,
444 const std::vector<std::pair<wxString, bool*>>& aExtraCheckboxes )
445{
446 // Keep asking the user for a new name until they give a valid one or cancel the operation
447 while( true )
448 {
449 wxArrayString headers;
450 std::vector<wxArrayString> itemsToDisplay;
451
452 GetLibraryItemsForListDialog( headers, itemsToDisplay );
453
454 wxString libraryName = Prj().GetRString( PROJECT::PCB_LIB_NICKNAME );
455
456 EDA_LIST_DIALOG dlg( this, aDialogTitle, headers, itemsToDisplay, libraryName, false );
457 dlg.SetListLabel( aListLabel );
458
459 for( const auto& [label, val] : aExtraCheckboxes )
460 dlg.AddExtraCheckbox( label, val );
461
462 wxButton* newLibraryButton = new wxButton( &dlg, ID_MAKE_NEW_LIBRARY, _( "New Library..." ) );
463 dlg.m_ButtonsSizer->Prepend( 80, 20 );
464 dlg.m_ButtonsSizer->Prepend( newLibraryButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 10 );
465
466 newLibraryButton->Bind( wxEVT_BUTTON,
467 [&dlg]( wxCommandEvent& )
468 {
469 dlg.EndModal( ID_MAKE_NEW_LIBRARY );
471
472 dlg.Layout();
473 dlg.GetSizer()->Fit( &dlg );
474
475 int ret = dlg.ShowModal();
476
477 switch( ret )
478 {
479 case wxID_CANCEL:
480 return wxEmptyString;
481
482 case wxID_OK:
483 libraryName = dlg.GetTextSelection();
484 Prj().SetRString( PROJECT::PCB_LIB_NICKNAME, libraryName );
486 return libraryName;
487
489 {
490 wxFileName fn = CreateNewLibrary( _( "New Footprint Library" ),
491 Prj().GetRString( PROJECT::PCB_LIB_PATH ) );
492
493 if( !fn.GetFullPath().IsEmpty() )
494 {
495 Prj().SetRString( PROJECT::PCB_LIB_PATH, fn.GetPath() );
496 Prj().SetRString( PROJECT::PCB_LIB_NICKNAME, fn.GetName() );
497 }
498 break;
499 }
500
501 default:
502 break;
503 }
504 }
505}
506
507
508bool PCB_BASE_EDIT_FRAME::AddLibrary( const wxString& aDialogTitle, const wxString& aFilename,
509 std::optional<LIBRARY_TABLE_SCOPE> aScope )
510{
513 bool isGlobal = false;
514 FILEDLG_HOOK_NEW_LIBRARY tableChooser( isGlobal );
515 FILEDLG_HOOK_NEW_LIBRARY* fileDlgHook = &tableChooser;
516
517 if( aScope )
518 {
519 isGlobal = ( *aScope == LIBRARY_TABLE_SCOPE::GLOBAL );
520 fileDlgHook = nullptr;
521 }
522
523 wxFileName fn( aFilename );
524
525 if( aFilename.IsEmpty() )
526 {
527 if( !LibraryFileBrowser( aDialogTitle, true, fn, FILEEXT::KiCadFootprintLibPathWildcard(),
528 FILEEXT::KiCadFootprintLibPathExtension, true, fileDlgHook ) )
529 {
530 return false;
531 }
532
533 if( fileDlgHook )
534 isGlobal = fileDlgHook->GetUseGlobalTable();
535 }
536
538
539 wxString libPath = fn.GetFullPath();
540 wxString libName = fn.GetName();
541
542 if( libName.IsEmpty() )
543 return false;
544
546
547 if( lib_type == PCB_IO_MGR::FILE_TYPE_NONE )
548 lib_type = PCB_IO_MGR::KICAD_SEXP;
549
550 wxString type = PCB_IO_MGR::ShowType( lib_type );
551
552 // KiCad lib is our default guess. So it might not have the .pretty extension
553 // In this case, the extension is part of the library name
554 if( lib_type == PCB_IO_MGR::KICAD_SEXP && fn.GetExt() != FILEEXT::KiCadFootprintLibPathExtension )
555 libName = fn.GetFullName();
556
557 // try to use path normalized to an environmental variable or project path
558 wxString normalizedPath = NormalizePath( libPath, &Pgm().GetLocalEnvVariables(), &Prj() );
559 bool success = true;
560
561 try
562 {
563 std::optional<LIBRARY_TABLE*> optTable = manager.Table( LIBRARY_TABLE_TYPE::FOOTPRINT, aScope.value() );
564
565 if( !optTable )
566 return false;
567
568 LIBRARY_TABLE* table = optTable.value();
569
570 LIBRARY_TABLE_ROW& row = table->InsertRow();
571
572 row.SetNickname( libName );
573 row.SetURI( normalizedPath );
574 row.SetType( type );
575
576 table->Save().map_error(
577 [&]( const LIBRARY_ERROR& aError )
578 {
579 wxMessageBox( _( "Error saving library table:\n\n" ) + aError.message,
580 _( "File Save Error" ), wxOK | wxICON_ERROR );
581 success = false;
582 } );
583 }
584 catch( const IO_ERROR& ioe )
585 {
586 DisplayError( this, ioe.What() );
587 return false;
588 }
589
590 if( success )
591 {
592 manager.ReloadTables( aScope.value(), { LIBRARY_TABLE_TYPE::FOOTPRINT } );
593 adapter->LoadOne( libName );
594
595 // Don't use dynamic_cast; it will fail across compile units on MacOS
597 {
598 LIB_ID libID( libName, wxEmptyString );
599 editor->SyncLibraryTree( true );
600 editor->FocusOnLibID( libID );
601 }
602
603 auto viewer = (FOOTPRINT_VIEWER_FRAME*) Kiway().Player( FRAME_FOOTPRINT_VIEWER, false );
604
605 if( viewer )
606 viewer->ReCreateLibraryList();
607 }
608
609 return success;
610}
611
612
614{
615 if( !aFPID.IsValid() )
616 return false;
617
620
621 wxString nickname = aFPID.GetLibNickname();
622 wxString fpname = aFPID.GetLibItemName();
623 wxString libfullname;
624
625 // Legacy libraries are readable, but modifying legacy format is not allowed
626 // So prompt the user if he try to delete a footprint from a legacy lib
627 if( std::optional<wxString> optUri = manager.GetFullURI( LIBRARY_TABLE_TYPE::FOOTPRINT, nickname ) )
628 libfullname = *optUri;
629 else
630 return false;
631
633 {
635 return false;
636 }
637
638 if( !adapter->IsFootprintLibWritable( nickname ) )
639 {
640 wxString msg = wxString::Format( _( "Library '%s' is read only." ), nickname );
641 ShowInfoBarError( msg );
642 return false;
643 }
644
645 // Confirmation
646 wxString msg = wxString::Format( _( "Delete footprint '%s' from library '%s'?" ),
647 fpname.GetData(),
648 nickname.GetData() );
649
650 if( aConfirm && !IsOK( this, msg ) )
651 return false;
652
653 try
654 {
655 adapter->DeleteFootprint( nickname, fpname );
656 }
657 catch( const IO_ERROR& ioe )
658 {
659 DisplayError( this, ioe.What() );
660 return false;
661 }
662
663 msg.Printf( _( "Footprint '%s' deleted from library '%s'" ),
664 fpname.GetData(),
665 nickname.GetData() );
666
667 SetStatusText( msg );
668
669 return true;
670}
671
672
674{
675 if( GetBoard()->GetFirstFootprint() == nullptr )
676 {
677 DisplayInfoMessage( this, _( "No footprints to export!" ) );
678 return;
679 }
680
681 bool map = false;
682 PROJECT& prj = Prj();
683 wxString nickname;
684
685 if( aStoreInNewLib )
686 {
687 wxFileName fn = CreateNewLibrary( _( "New Footprint Library" ), Prj().GetRString( PROJECT::PCB_LIB_PATH ) );
688
689 if( fn.GetFullPath().IsEmpty() )
690 return;
691
692 Prj().SetRString( PROJECT::PCB_LIB_PATH, fn.GetPath() );
693 nickname = fn.GetName();
694 map = IsOK( this, _( "Update footprints on board to refer to new library?" ) );
695 }
696 else
697 {
698 nickname = SelectLibrary( _( "Export Footprints" ), _( "Export footprints to library:" ),
699 { { _( "Update board footprints to link to exported footprints" ), &map } } );
700
701 if( !nickname ) // Aborted
702 return;
703 }
704
705 prj.SetRString( PROJECT::PCB_LIB_NICKNAME, nickname );
706
707 for( FOOTPRINT* footprint : GetBoard()->Footprints() )
708 {
709 bool saved = false;
710
711 try
712 {
714
715 if( !footprint->GetFPID().GetLibItemName().empty() ) // Handle old boards.
716 {
717 std::unique_ptr<FOOTPRINT> fpCopy(
718 static_cast<FOOTPRINT*>( footprint->Duplicate( IGNORE_PARENT_GROUP ) ) );
719
720 // Reset reference designator, group membership, and zone offset before saving
721
722 fpCopy->SetReference( "REF**" );
723 fpCopy->SetParentGroup( nullptr );
724
725 for( ZONE* zone : fpCopy->Zones() )
726 zone->Move( -fpCopy->GetPosition() );
727
728 saved = adapter->SaveFootprint( nickname, fpCopy.get(), true ) == FOOTPRINT_LIBRARY_ADAPTER::SAVE_OK;
729 }
730 }
731 catch( const IO_ERROR& ioe )
732 {
733 DisplayError( this, ioe.What() );
734 }
735
736 // Relink only if the footprint was actually written; otherwise the board would point
737 // at an entry the library does not contain.
738 if( map && saved )
739 {
740 LIB_ID id = footprint->GetFPID();
741 id.SetLibNickname( nickname );
742 footprint->SetFPID( id );
743 }
744 }
745}
746
747
749{
750 if( !aFootprint ) // Happen if no footprint loaded
751 return false;
752
754
755 wxString libraryName = aFootprint->GetFPID().GetLibNickname();
756 wxString footprintName = aFootprint->GetFPID().GetLibItemName();
757 bool nameChanged = m_footprintNameWhenLoaded != footprintName;
758
759 if( aFootprint->GetLink() != niluuid )
760 {
761 if( SaveFootprintToBoard( false ) )
762 {
763 m_footprintNameWhenLoaded = footprintName;
764 return true;
765 }
766
767 return false;
768 }
769 else if( libraryName.IsEmpty() || footprintName.IsEmpty() )
770 {
771 if( SaveFootprintAs( aFootprint ) )
772 {
773 // Re-read the name the save-as settled on; keeping the pre-save one would make the next
774 // save look like a rename and delete a library entry that was never ours
776 SyncLibraryTree( true );
777 return true;
778 }
779
780 return false;
781 }
782
784
785 // Legacy libraries are readable, but modifying legacy format is not allowed
786 // So prompt the user if he try to add/replace a footprint in a legacy lib
787 wxString libfullname;
788
789 if( std::optional<wxString> optUri = manager.GetFullURI( LIBRARY_TABLE_TYPE::FOOTPRINT, libraryName ) )
790 libfullname = *optUri;
791 else
792 return false;
793
795 {
797 return false;
798 }
799
800 // Save the renamed footprint before deleting the original, so a failed save does not
801 // destroy the old entry and lose the user's work (issue #23850).
802 if( !SaveFootprintInLibrary( aFootprint, libraryName ) )
803 return false;
804
805 if( nameChanged )
806 {
807 LIB_ID oldFPID( libraryName, m_footprintNameWhenLoaded );
808 DeleteFootprintFromLibrary( oldFPID, false );
809
810 m_footprintNameWhenLoaded = footprintName;
811 SyncLibraryTree( true );
812 }
813
814 return true;
815}
816
817
819{
822
823 LIB_ID fpID = aFootprint->GetFPID();
824 wxString libraryName = fpID.GetLibNickname();
825 wxString footprintName = fpID.GetLibItemName();
826
827 // Legacy libraries are readable, but modifying legacy format is not allowed
828 // So prompt the user if he try to add/replace a footprint in a legacy lib
829 if( std::optional<wxString> optUri = manager.GetFullURI( LIBRARY_TABLE_TYPE::FOOTPRINT, libraryName ) )
830 {
832 {
834 return false;
835 }
836 }
837 else
838 {
839 return false;
840 }
841
842 int i = 1;
843 wxString newName = footprintName;
844
845 // Append a number to the name until the name is unique in the library.
846 while( adapter->FootprintExists( libraryName, newName ) )
847 newName.Printf( "%s_%d", footprintName, i++ );
848
849 aFootprint->SetFPID( LIB_ID( libraryName, newName ) );
850
851 if( aFootprint->GetValue() == footprintName )
852 aFootprint->SetValue( newName );
853
854 return SaveFootprintInLibrary( aFootprint, libraryName );
855}
856
857
859 const wxString& aLibraryName )
860{
861 try
862 {
863 aFootprint->SetFPID( LIB_ID( wxEmptyString, aFootprint->GetFPID().GetLibItemName() ) );
864
865 // Clear selected, brightened, temp flags, edit flags, the whole shebang.
866 aFootprint->RunOnChildren(
867 []( BOARD_ITEM* child )
868 {
869 child->ClearFlags();
870 },
872
874
875 if( adapter->SaveFootprint( aLibraryName, aFootprint ) != FOOTPRINT_LIBRARY_ADAPTER::SAVE_OK )
876 {
877 aFootprint->SetFPID( LIB_ID( aLibraryName, aFootprint->GetFPID().GetLibItemName() ) );
878
879 DisplayError( this, wxString::Format( _( "Footprint '%s' could not be saved to library '%s'." ),
880 aFootprint->GetFPID().GetUniStringLibItemName(),
881 aLibraryName ) );
882 return false;
883 }
884
885 aFootprint->SetFPID( LIB_ID( aLibraryName, aFootprint->GetFPID().GetLibItemName() ) );
886
887 if( aFootprint == GetBoard()->GetFirstFootprint() )
888 setFPWatcher( aFootprint );
889
890 return true;
891 }
892 catch( const IO_ERROR& ioe )
893 {
894 DisplayError( this, ioe.What() );
895
896 aFootprint->SetFPID( LIB_ID( aLibraryName, aFootprint->GetFPID().GetLibItemName() ) );
897 return false;
898 }
899}
900
901
903{
904 // update footprint in the current board,
905 // not just add it to the board with total disregard for the netlist...
906 PCB_EDIT_FRAME* pcbframe = (PCB_EDIT_FRAME*) Kiway().Player( FRAME_PCB_EDITOR, false );
907
908 if( pcbframe == nullptr ) // happens when the board editor is not active (or closed)
909 {
910 ShowInfoBarError( _( "No board currently open." ) );
911 return false;
912 }
913
914 BOARD* mainpcb = pcbframe->GetBoard();
915 FOOTPRINT* sourceFootprint = nullptr;
916 FOOTPRINT* editorFootprint = GetBoard()->GetFirstFootprint();
917
918 if( !editorFootprint )
919 return false;
920
921 // Search the old footprint (source) if exists
922 // Because this source could be deleted when editing the main board...
923 if( editorFootprint->GetLink() != niluuid ) // this is not a new footprint ...
924 {
925 sourceFootprint = nullptr;
926
927 for( FOOTPRINT* candidate : mainpcb->Footprints() )
928 {
929 if( editorFootprint->GetLink() == candidate->m_Uuid )
930 {
931 sourceFootprint = candidate;
932 break;
933 }
934 }
935 }
936
937 if( !aAddNew && sourceFootprint == nullptr ) // source not found
938 {
939 DisplayError( this, _( "Unable to find the footprint on the main board.\nCannot save." ) );
940 return false;
941 }
942
943 TOOL_MANAGER* pcb_ToolManager = pcbframe->GetToolManager();
944
945 if( aAddNew && pcb_ToolManager->GetTool<BOARD_EDITOR_CONTROL>()->PlacingFootprint() )
946 {
947 DisplayError( this, _( "Previous footprint placement still in progress." ) );
948 return false;
949 }
950
952 BOARD_COMMIT commit( pcbframe );
953
954 // Create a copy for the board, first using Clone() to keep existing Uuids, and then either
955 // resetting the uuids to the board values or assigning new Uuids.
956 FOOTPRINT* newFootprint = static_cast<FOOTPRINT*>( editorFootprint->Clone() );
957 newFootprint->SetParent( mainpcb );
958 newFootprint->SetLink( niluuid );
959
960 auto fixUuid =
961 [&]( KIID& aUuid )
962 {
963 if( editorFootprint->GetLink() != niluuid && m_boardFootprintUuids.count( aUuid ) )
964 aUuid = m_boardFootprintUuids[ aUuid ];
965 else
966 aUuid = KIID();
967 };
968
969 {
970 KIID uuid = newFootprint->m_Uuid;
971 fixUuid( uuid );
972 newFootprint->SetUuid( uuid );
973 }
974
975 newFootprint->RunOnChildren(
976 [&]( BOARD_ITEM* aChild )
977 {
978 KIID uuid = aChild->m_Uuid;
979 fixUuid( uuid );
980 aChild->SetUuid( uuid );
981 },
983
984 // Right now, we only show the "Unconnected" net in the footprint editor, but this is still
985 // referenced in the footprint. So we need to update the net pointers in the footprint to
986 // point to the nets in the main board.
987 newFootprint->RunOnChildren(
988 [&]( BOARD_ITEM* aChild )
989 {
990 if( BOARD_CONNECTED_ITEM* conn = dynamic_cast<BOARD_CONNECTED_ITEM*>( aChild ) )
991 {
992 NETINFO_ITEM* net = conn->GetNet();
993 auto& netmap = mainpcb->GetNetInfo().NetsByName();
994
995 if( net )
996 {
997 auto it = netmap.find( net->GetNetname() );
998
999 if( it != netmap.end() )
1000 conn->SetNet( it->second );
1001 }
1002
1003 }
1004 },
1006
1007 BOARD_DESIGN_SETTINGS& bds = m_pcb->GetDesignSettings();
1008
1011
1012 if( sourceFootprint ) // this is an update command
1013 {
1014 // In the main board the new footprint replaces the old one (pos, orient, ref, value, connections
1015 // and properties are kept) and the sourceFootprint (old footprint) is deleted
1016 mainpcb->ExchangeFootprint( sourceFootprint, newFootprint, commit,
1018 true /* match pad positions */ );
1019
1020 commit.Push( _( "Update Footprint" ) );
1021 }
1022 else // This is an insert command
1023 {
1024 KIGFX::VIEW_CONTROLS* viewControls = pcbframe->GetCanvas()->GetViewControls();
1025 VECTOR2D cursorPos = viewControls->GetCursorPosition();
1026
1027 commit.Add( newFootprint );
1028 viewControls->SetCrossHairCursorPosition( VECTOR2D( 0, 0 ), false );
1029 pcbframe->PlaceFootprint( newFootprint );
1030 newFootprint->SetPosition( VECTOR2I( 0, 0 ) );
1031 viewControls->SetCrossHairCursorPosition( cursorPos, false );
1032 newFootprint->ResetUuid();
1033 commit.Push( _( "Insert Footprint" ) );
1034
1035 pcbframe->Raise();
1036 pcb_ToolManager->RunAction( PCB_ACTIONS::placeFootprint, newFootprint );
1037 }
1038
1039 newFootprint->ClearFlags();
1040
1041 return true;
1042}
1043
1044
1046{
1047public:
1048 SAVE_AS_DIALOG( FOOTPRINT_EDIT_FRAME* aParent, const wxString& aFootprintName,
1049 const wxString& aLibraryPreselect,
1050 std::function<bool( wxString libName, wxString fpName )> aValidator ) :
1051 EDA_LIST_DIALOG( aParent, _( "Save Footprint As" ), false ),
1052 m_validator( std::move( aValidator ) )
1053 {
1055 std::vector<wxString> nicknames = adapter->GetLibraryNames();
1056 wxArrayString headers;
1057 std::vector<wxArrayString> itemsToDisplay;
1058
1059 aParent->GetLibraryItemsForListDialog( headers, itemsToDisplay );
1060 initDialog( headers, itemsToDisplay, aLibraryPreselect );
1061
1062 SetListLabel( _( "Save in library:" ) );
1063 SetOKLabel( _( "Save" ) );
1064
1065 wxBoxSizer* bNameSizer = new wxBoxSizer( wxHORIZONTAL );
1066
1067 wxStaticText* label = new wxStaticText( this, wxID_ANY, _( "Name:" ) );
1068 bNameSizer->Add( label, 0, wxALIGN_CENTER_VERTICAL|wxTOP|wxBOTTOM|wxLEFT, 5 );
1069
1070 m_fpNameCtrl = new wxTextCtrl( this, wxID_ANY, aFootprintName );
1071 bNameSizer->Add( m_fpNameCtrl, 1, wxALIGN_CENTER_VERTICAL|wxALL, 5 );
1072
1073 wxTextValidator nameValidator( wxFILTER_EXCLUDE_CHAR_LIST );
1074 nameValidator.SetCharExcludes( FOOTPRINT::StringLibNameInvalidChars( false ) );
1075 m_fpNameCtrl->SetValidator( nameValidator );
1076
1077 wxButton* newLibraryButton = new wxButton( this, ID_MAKE_NEW_LIBRARY, _( "New Library..." ) );
1078 m_ButtonsSizer->Prepend( 80, 20 );
1079 m_ButtonsSizer->Prepend( newLibraryButton, 0, wxALIGN_CENTER_VERTICAL|wxLEFT|wxRIGHT, 10 );
1080
1081 GetSizer()->Prepend( bNameSizer, 0, wxEXPAND|wxTOP|wxLEFT|wxRIGHT, 5 );
1082
1083 // If a footprint name was specified, disable loading of previously-saved state
1084 if( !aFootprintName.IsEmpty() )
1086
1087 Bind( wxEVT_BUTTON,
1088 [this]( wxCommandEvent& )
1089 {
1090 EndModal( ID_MAKE_NEW_LIBRARY );
1092
1093 // Move nameTextCtrl to the head of the tab-order
1094 if( GetChildren().DeleteObject( m_fpNameCtrl ) )
1095 GetChildren().Insert( m_fpNameCtrl );
1096
1098
1100
1101 Layout();
1102 GetSizer()->Fit( this );
1103
1104 Centre();
1105 }
1106
1107 wxString GetFPName()
1108 {
1109 wxString footprintName = m_fpNameCtrl->GetValue();
1110 footprintName.Trim( true );
1111 footprintName.Trim( false );
1112 return footprintName;
1113 }
1114
1115 bool TransferDataToWindow() override
1116 {
1117 // Respond to any filter text loaded from previously-saved state
1118 wxCommandEvent dummy;
1120
1121 return true;
1122 }
1123
1125 {
1126 return m_validator( GetTextSelection(), GetFPName() );
1127 }
1128
1129private:
1130 wxTextCtrl* m_fpNameCtrl;
1131 std::function<bool( wxString libName, wxString fpName )> m_validator;
1132};
1133
1134
1136{
1137 if( aFootprint == nullptr )
1138 return false;
1139
1140 LIBRARY_MANAGER& manager = Pgm().GetLibraryManager();
1142
1143 SetMsgPanel( aFootprint );
1144
1145 LIB_ID old_FPID = aFootprint->GetFPID();
1146 wxString libraryName = old_FPID.GetLibNickname();
1147 wxString footprintName = old_FPID.GetLibItemName();
1148 bool updateValue = aFootprint->GetValue() == footprintName;
1149 bool done = false;
1150 bool footprintExists = false;
1151
1152 while( !done )
1153 {
1154 SAVE_AS_DIALOG dlg( this, footprintName, libraryName,
1155 [&]( const wxString& newLib, const wxString& newName )
1156 {
1157 if( newLib.IsEmpty() )
1158 {
1159 wxMessageBox( _( "A library must be specified." ) );
1160 return false;
1161 }
1162
1163 if( newName.IsEmpty() )
1164 {
1165 wxMessageBox( _( "Footprint must have a name." ) );
1166 return false;
1167 }
1168
1169 // Legacy libraries are readable, but modifying legacy format is not allowed
1170 // So prompt the user if he try to add/replace a footprint in a legacy lib
1171 if( std::optional<wxString> optUri = manager.GetFullURI( LIBRARY_TABLE_TYPE::FOOTPRINT, newLib ) )
1172 {
1174 {
1176 return false;
1177 }
1178 }
1179 else
1180 {
1181 return false;
1182 }
1183
1184 footprintExists = adapter->FootprintExists( newLib, newName );
1185
1186 if( footprintExists )
1187 {
1188 wxString msg = wxString::Format( _( "Footprint %s already exists in %s." ),
1189 newName,
1190 newLib );
1191
1192 KIDIALOG errorDlg( this, msg, _( "Confirmation" ), wxOK | wxCANCEL | wxICON_WARNING );
1193 errorDlg.SetOKLabel( _( "Overwrite" ) );
1194
1195 return errorDlg.ShowModal() == wxID_OK;
1196 }
1197
1198 return true;
1199 } );
1200
1201 int ret = dlg.ShowModal();
1202
1203 if( ret == wxID_CANCEL )
1204 {
1205 return false;
1206 }
1207 else if( ret == wxID_OK )
1208 {
1209 footprintName = dlg.GetFPName();
1210 libraryName = dlg.GetTextSelection();
1211 done = true;
1212 }
1213 else if( ret == ID_MAKE_NEW_LIBRARY )
1214 {
1215 wxFileName fn = CreateNewLibrary( _( "New Footprint Library" ),
1216 Prj().GetRString( PROJECT::PCB_LIB_PATH ) );
1217
1218 if( fn.GetFullPath().IsEmpty() )
1219 continue;
1220
1221 Prj().SetRString( PROJECT::PCB_LIB_PATH, fn.GetPath() );
1222 Prj().SetRString( PROJECT::PCB_LIB_NICKNAME, fn.GetName() );
1223 libraryName = fn.GetName();
1224 }
1225 }
1226
1227 aFootprint->SetFPID( LIB_ID( libraryName, footprintName ) );
1228
1229 if( updateValue )
1230 aFootprint->SetValue( footprintName );
1231
1232 if( !SaveFootprintInLibrary( aFootprint, libraryName ) )
1233 return false;
1234
1236
1237 // Once saved-as a board footprint is no longer a board footprint
1238 aFootprint->SetLink( niluuid );
1239
1240 wxString fmt = footprintExists ? _( "Footprint '%s' replaced in '%s'" )
1241 : _( "Footprint '%s' added to '%s'" );
1242
1243 wxString msg = wxString::Format( fmt, footprintName.GetData(), libraryName.GetData() );
1244 SetStatusText( msg );
1245 RenameFootprintTab( old_FPID, aFootprint->GetFPID() );
1247
1248 return true;
1249}
1250
1251
1252bool FOOTPRINT_EDIT_FRAME::RevertFootprint( bool aSkipConfirmation )
1253{
1255 {
1256 wxString msg;
1257
1258 if( IsCurrentFPFromBoard() )
1259 msg.Printf( _( "Revert '%s' to version from board?" ), m_originalFootprintCopy->GetReference() );
1260 else
1261 msg.Printf( _( "Revert '%s' to last version saved?" ), GetLoadedFPID().GetLibItemName().wx_str() );
1262
1263 if( aSkipConfirmation || ConfirmRevertDialog( this, msg ) )
1264 {
1265 // Clone the baseline up front; a full clear drops the frame's copy of it
1266 std::unique_ptr<FOOTPRINT> restored( static_cast<FOOTPRINT*>( m_originalFootprintCopy->Clone() ) );
1267
1268 // Reverting one tab must leave the others open, so reload in place instead of
1269 // clearing the editor
1270 const wxString oldKey = m_activeTab ? m_activeTab->GetTabKey() : wxString();
1271
1273 installFootprintOnActiveBoard( restored.release() );
1274
1275 // The tab is keyed on the footprint name, which the revert may have rolled back
1276 if( m_activeTab && m_activeTab->GetTabKey() != oldKey )
1277 m_tabsPanel->RenameTab( oldKey, m_activeTab->GetTabKey(), m_activeTab->GetDisplayName() );
1278
1279 Zoom_Automatique( false );
1280
1281 Update3DView( true, true );
1282
1284 ClearModify();
1285
1286 UpdateView();
1287 GetCanvas()->Refresh();
1288
1289 return true;
1290 }
1291 }
1292
1293 return false;
1294}
1295
1296
1297FOOTPRINT* PCB_BASE_FRAME::CreateNewFootprint( wxString aFootprintName, const wxString& aLibName )
1298{
1299 if( aFootprintName.IsEmpty() )
1300 aFootprintName = _( "Untitled" );
1301
1302 int footprintAttrs = FP_SMD;
1303
1304 if( !aLibName.IsEmpty() )
1305 {
1307 std::vector<wxString> fpnames;
1308 wxString baseName = aFootprintName;
1309 int idx = 1;
1310
1311 // Make sure the name is unique
1312 while( adapter->FootprintExists( aLibName, aFootprintName ) )
1313 aFootprintName = baseName + wxString::Format( wxS( "_%d" ), idx++ );
1314
1315 // Try to infer the footprint attributes from an existing footprint in the library
1316 try
1317 {
1318 fpnames = adapter->GetFootprintNames( aLibName, true );
1319
1320 if( !fpnames.empty() )
1321 {
1322 std::unique_ptr<FOOTPRINT> fp( adapter->LoadFootprint( aLibName, fpnames.back(), false ) );
1323
1324 if( fp )
1325 footprintAttrs = fp->GetAttributes();
1326 }
1327 }
1328 catch( ... )
1329 {
1330 // best efforts
1331 }
1332 }
1333
1334 // Create the new footprint and add it to the head of the linked list of footprints
1335 FOOTPRINT* footprint = new FOOTPRINT( GetBoard() );
1336
1337 // Update its name in lib
1338 footprint->SetFPID( LIB_ID( wxEmptyString, aFootprintName ) );
1339
1340 footprint->SetAttributes( footprintAttrs );
1341
1342 PCB_LAYER_ID txt_layer;
1343 VECTOR2I default_pos;
1345
1346 if( settings.m_DefaultFPTextItems.size() > 0 )
1347 {
1348 footprint->Reference().SetText( settings.m_DefaultFPTextItems[0].m_Text );
1349 footprint->Reference().SetVisible( settings.m_DefaultFPTextItems[0].m_Visible );
1350 }
1351
1352 txt_layer = settings.m_DefaultFPTextItems.size() > 0 ? settings.m_DefaultFPTextItems[0].m_Layer : F_SilkS;
1353 footprint->Reference().SetLayer( txt_layer );
1354 default_pos.y -= settings.GetTextSize( txt_layer ).y / 2;
1355 footprint->Reference().SetPosition( default_pos );
1356 default_pos.y += settings.GetTextSize( txt_layer ).y;
1357
1358 if( settings.m_DefaultFPTextItems.size() > 1 )
1359 {
1360 footprint->Value().SetText( settings.m_DefaultFPTextItems[1].m_Text );
1361 footprint->Value().SetVisible( settings.m_DefaultFPTextItems[1].m_Visible );
1362 }
1363
1364 txt_layer = settings.m_DefaultFPTextItems.size() > 1 ? settings.m_DefaultFPTextItems[1].m_Layer : F_Fab;
1365 footprint->Value().SetLayer( txt_layer );
1366 default_pos.y += settings.GetTextSize( txt_layer ).y / 2;
1367 footprint->Value().SetPosition( default_pos );
1368 default_pos.y += settings.GetTextSize( txt_layer ).y;
1369
1370 for( size_t i = 2; i < settings.m_DefaultFPTextItems.size(); ++i )
1371 {
1372 PCB_TEXT* textItem = new PCB_TEXT( footprint );
1373 textItem->SetText( settings.m_DefaultFPTextItems[i].m_Text );
1374 txt_layer = (PCB_LAYER_ID) settings.m_DefaultFPTextItems[i].m_Layer;
1375 textItem->SetLayer( txt_layer );
1376 default_pos.y += settings.GetTextSize( txt_layer ).y / 2;
1377 textItem->SetPosition( default_pos );
1378 default_pos.y += settings.GetTextSize( txt_layer ).y;
1379 footprint->GraphicalItems().push_back( textItem );
1380 }
1381
1382 if( footprint->GetReference().IsEmpty() )
1383 footprint->SetReference( aFootprintName );
1384
1385 if( footprint->GetValue().IsEmpty() )
1386 footprint->SetValue( aFootprintName );
1387
1388 footprint->RunOnChildren(
1389 [&]( BOARD_ITEM* aChild )
1390 {
1391 if( aChild->Type() == PCB_FIELD_T || aChild->Type() == PCB_TEXT_T )
1392 {
1393 PCB_TEXT* textItem = static_cast<PCB_TEXT*>( aChild );
1394 PCB_LAYER_ID layer = textItem->GetLayer();
1395
1396 textItem->SetTextThickness( settings.GetTextThickness( layer ) );
1397 textItem->SetTextSize( settings.GetTextSize( layer ) );
1398 textItem->SetItalic( settings.GetTextItalic( layer ) );
1399 textItem->SetKeepUpright( settings.GetTextUpright( layer ) );
1400 }
1401 },
1403
1404 SetMsgPanel( footprint );
1405 return footprint;
1406}
1407
1408
1410 std::vector<wxArrayString>& aItemsToDisplay )
1411{
1412 aHeaders.Add( _( "Library" ) );
1413 aHeaders.Add( _( "Description" ) );
1414
1418 std::vector<wxString> nicknames = adapter->GetLibraryNames();
1419 std::vector<wxArrayString> unpinned;
1420
1421 for( const wxString& nickname : nicknames )
1422 {
1423 wxArrayString item;
1424 wxString description = adapter->GetLibraryDescription( nickname ).value_or( wxEmptyString );
1425
1426 if( alg::contains( project.m_PinnedFootprintLibs, nickname )
1427 || alg::contains( cfg->m_Session.pinned_fp_libs, nickname ) )
1428 {
1429 item.Add( LIB_TREE_MODEL_ADAPTER::GetPinningSymbol() + nickname );
1430 item.Add( description );
1431 aItemsToDisplay.push_back( item );
1432 }
1433 else
1434 {
1435 item.Add( nickname );
1436 item.Add( description );
1437 unpinned.push_back( item );
1438 }
1439 }
1440
1441 std::sort( aItemsToDisplay.begin(), aItemsToDisplay.end(),
1442 []( const wxArrayString& a, const wxArrayString& b )
1443 {
1444 return StrNumCmp( a[0], b[0], CMP_T::IGNORE_CASE ) < 0;
1445 } );
1446
1447 std::sort( unpinned.begin(), unpinned.end(),
1448 []( const wxArrayString& a, const wxArrayString& b )
1449 {
1450 return StrNumCmp( a[0], b[0], CMP_T::IGNORE_CASE ) < 0;
1451 } );
1452
1453 std::ranges::copy( unpinned, std::back_inserter( aItemsToDisplay ) );
1454}
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
A base class derived from BOARD_ITEM for items that can be connected and have a net,...
Container for design settings for a BOARD object.
std::vector< TEXT_ITEM_INFO > m_DefaultFPTextItems
bool GetTextUpright(PCB_LAYER_ID aLayer) const
int GetTextThickness(PCB_LAYER_ID aLayer) const
Return the default text thickness from the layer class for the given layer.
bool GetTextItalic(PCB_LAYER_ID aLayer) const
VECTOR2I GetTextSize(PCB_LAYER_ID aLayer) const
Return the default text size from the layer class for the given layer.
Handle actions specific to the board editor in PcbNew.
bool PlacingFootprint() const
Re-entrancy checker for above.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
void SetUuid(const KIID &aUuid)
virtual PCB_LAYER_ID GetLayer() const
Return the primary layer this item is on.
virtual void SetLayer(PCB_LAYER_ID aLayer)
Set the layer this item is on.
Definition board_item.h:397
void ResetUuid()
Definition board_item.h:295
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
const NETINFO_LIST & GetNetInfo() const
Definition board.h:1241
void BuildListOfNets()
Definition board.h:1189
FOOTPRINT * GetFirstFootprint() const
Get the first footprint on the board or nullptr.
Definition board.h:713
void ExchangeFootprint(FOOTPRINT *aExisting, FOOTPRINT *aNew, BOARD_COMMIT &aCommit, FLIP_DIRECTION aFlipDirection, bool aMatchPadPositions, bool aDeleteExtraTexts=true, bool aResetTextLayers=true, bool aResetTextEffects=true, bool aResetTextPositions=true, bool aResetTextContent=true, bool aResetFabricationAttrs=true, bool aResetClearanceOverrides=true, bool aReset3DModels=true, bool aResetTransform=false, bool *aUpdated=nullptr, bool *aShifted=nullptr)
Replace aExisting with aNew, preserving connectivity and metadata.
const FOOTPRINTS & Footprints() const
Definition board.h:465
COMMIT & Add(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr)
Add a new item to the model.
Definition commit.h:74
void OptOut(wxWindow *aWindow)
Opt out of control state saving.
void SetInitialFocus(wxWindow *aWindow)
Sets the window (usually a wxTextCtrl) that should be focused when the dialog is shown.
Definition dialog_shim.h:95
void SetupStandardButtons(std::map< int, wxString > aLabels={})
int ShowModal() override
UNDO_REDO_CONTAINER m_undoList
virtual void ClearUndoRedoList()
Clear the undo and redo list using ClearUndoORRedoList()
void ShowInfoBarError(const wxString &aErrorMsg, bool aShowCloseButton=false, INFOBAR_MESSAGE_TYPE aType=INFOBAR_MESSAGE_TYPE::GENERIC)
Show the WX_INFOBAR displayed on the top of the canvas with a message and an error icon on the left o...
UNDO_REDO_CONTAINER m_redoList
void SetMsgPanel(const std::vector< MSG_PANEL_ITEM > &aList)
Clear the message panel and populates it with the contents of aList.
virtual void ReCreateHToolbar()
virtual void Zoom_Automatique(bool aWarpPointer)
Redraw the screen with best zoom level and the best centering that shows all the page or the board.
bool LibraryFileBrowser(const wxString &aTitle, bool doOpen, wxFileName &aFilename, const wxString &wildcard, const wxString &ext, bool isDirectory, FILEDLG_HOOK_NEW_LIBRARY *aFileDlgHook=nullptr)
KIGFX::VIEW_CONTROLS * GetViewControls() const
Return a pointer to the KIGFX::VIEW_CONTROLS instance used in the panel.
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
const KIID m_Uuid
Definition eda_item.h:599
KICAD_T Type() const
Returns the type of object.
Definition eda_item.h:110
void ClearFlags(EDA_ITEM_FLAGS aMask=EDA_ITEM_ALL_FLAGS)
Definition eda_item.h:160
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
A dialog which shows:
void textChangeInFilterBox(wxCommandEvent &event) override
void SetOKLabel(const wxString &aLabel)
void initDialog(const wxArrayString &aItemHeaders, const std::vector< wxArrayString > &aItemList, const wxString &aPreselectText)
wxString GetTextSelection(int aColumn=0)
Return the selected text from aColumn in the wxListCtrl in the dialog.
void SetListLabel(const wxString &aLabel)
void AddExtraCheckbox(const wxString &aLabel, bool *aValuePtr)
Add a checkbox value to the dialog.
void GetExtraCheckboxValues()
Fills in the value pointers from the checkboxes after the dialog has run.
EDA_LIST_DIALOG(wxWindow *aParent, const wxString &aTitle, const wxArrayString &aItemHeaders, const std::vector< wxArrayString > &aItemList, const wxString &aPreselectText=wxEmptyString, bool aSortList=true)
virtual void SetVisible(bool aVisible)
Definition eda_text.cpp:348
void SetKeepUpright(bool aKeepUpright)
Definition eda_text.cpp:387
virtual void SetText(const wxString &aText)
Definition eda_text.cpp:237
void SetItalic(bool aItalic)
Set the text to be italic - this will also update the font if needed.
Definition eda_text.cpp:291
void SyncLibraryTree(bool aProgress)
Synchronize the footprint library tree to the current state of the footprint library table.
bool SaveFootprintInLibrary(FOOTPRINT *aFootprint, const wxString &aLibraryName)
FOOTPRINT_EDITOR_TAB_CONTEXT * CreateUnsavedFootprintTab()
Open a session-only tab over a fresh fp-holder board and make it the active tab.
FOOTPRINT_EDITOR_TAB_CONTEXT * m_activeTab
bool SaveFootprintAs(FOOTPRINT *aFootprint)
bool DuplicateFootprint(FOOTPRINT *aFootprint)
void recombineEditedPad()
Fold a pad being edited back together, so its primitives are not left as loose copper.
void ExportFootprint(FOOTPRINT *aFootprint)
Create a file containing only one footprint.
LIB_ID GetLoadedFPID() const
Return the LIB_ID of the part being edited.
bool SaveFootprintToBoard(bool aAddNew)
EDITOR_TABS_PANEL * m_tabsPanel
bool SaveFootprint(FOOTPRINT *aFootprint)
Save in an existing library a given footprint.
FOOTPRINT * ImportFootprint(const wxString &aName=wxT(""))
Read a file containing only one footprint.
std::map< KIID, KIID > m_boardFootprintUuids
bool IsContentModified() const override
Get if any footprints or libraries have been modified but not saved.
void RenameFootprintTab(const LIB_ID &aOldId, const LIB_ID &aNewId)
Update the open tab for aOldId, if any, to the renamed footprint aNewId so its label and key track th...
void UpdateView()
Reload displayed items and sets view.
void AddFootprintToBoard(FOOTPRINT *aFootprint) override
Override from PCB_BASE_EDIT_FRAME which adds a footprint to the editor's dummy board,...
bool DeleteFootprintFromLibrary(const LIB_ID &aFPID, bool aConfirm)
Delete the given footprint from its library.
void OnModify() override
Must be called after a footprint change in order to set the "modify" flag of the current screen and p...
bool RevertFootprint(bool aSkipConfirmation=false)
std::unique_ptr< FOOTPRINT > m_originalFootprintCopy
FOOTPRINT_EDITOR_SETTINGS * GetSettings()
void freeUndoRedoCommandsWithItems(UNDO_REDO_CONTAINER &aUndo, UNDO_REDO_CONTAINER &aRedo)
Free both the transient board items and the command wrappers in the given lists.
void installFootprintOnActiveBoard(FOOTPRINT *aFootprint)
Replace the active board's footprint with aFootprint and re-point the file watcher at it.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
bool IsFootprintLibWritable(const wxString &aNickname)
Return true if the library given by aNickname is writable.
void DeleteFootprint(const wxString &aNickname, const wxString &aFootprintName)
Deletes the aFootprintName from the library given by aNickname.
SAVE_T SaveFootprint(const wxString &aNickname, const FOOTPRINT *aFootprint, bool aOverwrite=true)
Write aFootprint to an existing library given by aNickname.
std::vector< wxString > GetFootprintNames(const wxString &aNickname, bool aBestEfforts=false)
Retrieves a list of footprint names contained in a given loaded library.
FOOTPRINT * LoadFootprint(const wxString &aNickname, const wxString &aName, bool aKeepUUID)
Load a FOOTPRINT having aName from the library given by aNickname.
std::optional< LIB_STATUS > LoadOne(LIB_DATA *aLib) override
Loads or reloads the given library, if it exists.
bool FootprintExists(const wxString &aNickname, const wxString &aName)
Component library viewer main window.
void SetPosition(const VECTOR2I &aPos) override
void SetFPID(const LIB_ID &aFPID)
Definition footprint.h:418
void SetLink(const KIID &aLink)
Definition footprint.h:1157
void RunOnChildren(const std::function< void(BOARD_ITEM *)> &aFunction, RECURSE_MODE aMode) const override
Invoke a function on all children.
void SetAttributes(int aAttributes)
Definition footprint.h:510
EDA_ITEM * Clone() const override
Create a duplicate of this item with linked list members set to NULL.
PCB_FIELD & Value()
read/write accessors:
Definition footprint.h:831
const LIB_ID & GetFPID() const
Definition footprint.h:417
void SetReference(const wxString &aReference)
Definition footprint.h:799
void ApplyDefaultSettings(const BOARD &board, bool aStyleFields, bool aStyleText, bool aStyleShapes, bool aStyleDimensions, bool aStyleBarcodes)
Apply default board settings to the footprint field text properties.
void SetValue(const wxString &aValue)
Definition footprint.h:822
PCB_FIELD & Reference()
Definition footprint.h:832
void Add(BOARD_ITEM *aItem, ADD_MODE aMode=ADD_MODE::INSERT, bool aSkipConnectivity=false) override
Adds an item to the container.
KIID GetLink() const
Definition footprint.h:1156
static const wxChar * StringLibNameInvalidChars(bool aUserReadable)
Test for validity of the name in a library of the footprint ( no spaces, dir separators ....
const wxString & GetValue() const
Definition footprint.h:817
const wxString & GetReference() const
Definition footprint.h:793
DRAWINGS & GraphicalItems()
Definition footprint.h:358
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()
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
An interface for classes handling user events controlling the view behavior such as zooming,...
virtual void SetCrossHairCursorPosition(const VECTOR2D &aPosition, bool aWarpView=true)=0
Move the graphic crosshair cursor to the requested position expressed in world coordinates.
VECTOR2D GetCursorPosition() const
Return the current cursor position in world coordinates.
Definition kiid.h:46
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
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
virtual PROJECT & Prj() const
Return the PROJECT associated with this KIWAY.
Definition kiway.cpp:210
std::optional< wxString > GetLibraryDescription(const wxString &aNickname) const
std::vector< wxString > GetLibraryNames() const
Returns a list of library nicknames that are available (skips any that failed to load)
void ReloadTables(LIBRARY_TABLE_SCOPE aScope, std::initializer_list< LIBRARY_TABLE_TYPE > aTablesToLoad={})
std::optional< LIBRARY_TABLE * > Table(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope)
Retrieves a given table; creating a new empty project table if a valid project is loaded and the give...
std::optional< wxString > GetFullURI(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, bool aSubstituted=false)
Return the full location specifying URI for the LIB, either in original UI form or in environment var...
void SetNickname(const wxString &aNickname)
void SetType(const wxString &aType)
void SetURI(const wxString &aUri)
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
bool IsValid() const
Check if this LID_ID is valid.
Definition lib_id.h:168
int SetLibNickname(const UTF8 &aLibNickname)
Override the logical library name portion of the LIB_ID to aLibNickname.
Definition lib_id.cpp:113
const wxString GetUniStringLibItemName() const
Get strings for display messages in dialogs.
Definition lib_id.h:108
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
static const wxString GetPinningSymbol()
Handle the data for a net.
Definition netinfo.h:50
const wxString & GetNetname() const
Definition netinfo.h:110
const NETNAMES_MAP & NetsByName() const
Return the name map, at least for python.
Definition netinfo.h:258
FLIP_DIRECTION m_FlipDirection
static TOOL_ACTION placeFootprint
wxString CreateNewLibrary(const wxString &aDialogTitle, const wxString &aInitialPath=wxEmptyString)
If a library name is given, creates a new footprint library in the project folder with the given name...
wxString SelectLibrary(const wxString &aDialogTitle, const wxString &aListLabel, const std::vector< std::pair< wxString, bool * > > &aExtraCheckboxes={})
Put up a dialog and allows the user to pick a library, for unspecified use.
wxString createNewLibrary(const wxString &aDialogTitle, const wxString &aLibName, const wxString &aInitialPath, std::optional< LIBRARY_TABLE_SCOPE > aScope=std::nullopt)
Create a new library in the given table.
wxString CreateNewProjectLibrary(const wxString &aDialogTitle, const wxString &aLibName)
bool AddLibrary(const wxString &aDialogTitle, const wxString &aLibName=wxEmptyString, std::optional< LIBRARY_TABLE_SCOPE > aScope=std::nullopt)
Add an existing library to either the global or project library table.
void setFPWatcher(FOOTPRINT *aFootprint)
Create or removes a watcher on the specified footprint.
FOOTPRINT * CreateNewFootprint(wxString aFootprintName, const wxString &aLibName)
Create a new footprint at position 0,0.
PCBNEW_SETTINGS * GetPcbNewSettings() const
void GetLibraryItemsForListDialog(wxArrayString &aHeaders, std::vector< wxArrayString > &aItemsToDisplay)
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
virtual BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Return the BOARD_DESIGN_SETTINGS for the open project.
void PlaceFootprint(FOOTPRINT *aFootprint, bool aRecreateRatsnest=true, std::optional< VECTOR2I > aPosition=std::nullopt)
Place aFootprint at the current cursor position (or provided one) and updates footprint coordinates w...
virtual void Update3DView(bool aMarkDirty, bool aRefresh, const wxString *aTitle=nullptr)
Update the 3D view, if the viewer is opened by this frame.
The main frame for Pcbnew.
void ExportFootprintsToLibrary(bool aStoreInNewLib)
Save footprints in a library:
A PCB_IO derivation for saving and loading Pcbnew s-expression formatted files.
void FormatFootprintLibFile(FOOTPRINT *aFootprint) const
Output aFootprint as a complete footprint library file.
std::string GetStringOutput(bool doClear)
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
@ LEGACY
Legacy Pcbnew file formats prior to s-expression.
Definition pcb_io_mgr.h:55
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 GuessPluginTypeFromLibPath(const wxString &aLibPath, int aCtl=0)
Return a plugin type given a footprint library's libPath.
static const wxString ShowType(PCB_FILE_T aFileType)
Return a brief name for a plugin given aFileType enum.
void SetTextThickness(int aWidth) override
The TextThickness is that set by the user.
Definition pcb_text.cpp:514
void SetTextSize(VECTOR2I aNewSize, bool aEnforceMinTextSize=true) override
Definition pcb_text.cpp:486
void SetPosition(const VECTOR2I &aPos) override
Definition pcb_text.h:103
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:126
The backing store for a PROJECT, in JSON format.
static FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(PROJECT *aProject)
Container for project specific data.
Definition project.h:63
@ PCB_LIB_PATH
Definition project.h:241
@ PCB_LIB_NICKNAME
Definition project.h:242
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:201
virtual void SetRString(RSTRING_T aStringId, const wxString &aString)
Store a "retained string", which is any session and project specific string identified in enum RSTRIN...
Definition project.cpp:449
virtual const wxString & GetRString(RSTRING_T aStringId)
Return a "retained string", which is any session and project specific string identified in enum RSTRI...
Definition project.cpp:460
bool TransferDataFromWindow() override
SAVE_AS_DIALOG(FOOTPRINT_EDIT_FRAME *aParent, const wxString &aFootprintName, const wxString &aLibraryPreselect, std::function< bool(wxString libName, wxString fpName)> aValidator)
bool TransferDataToWindow() override
std::function< bool(wxString libName, wxString fpName)> m_validator
TOOL_MANAGER * m_toolManager
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.
bool RunAction(const std::string &aActionName, T aParam)
Run the specified action immediately, pausing the current action to run the new one.
static REPORTER & GetInstance()
Definition reporter.cpp:324
Handle a list of polygons defining a copper zone.
Definition zone.h:70
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 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
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
bool ConfirmRevertDialog(wxWindow *parent, const wxString &aMessage)
Display a confirmation dialog for a revert action.
Definition confirm.cpp:133
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.
#define _(s)
@ RECURSE
Definition eda_item.h:51
#define IGNORE_PARENT_GROUP
Definition eda_item.h:55
wxString NormalizePath(const wxFileName &aFilePath, const ENV_VAR_MAP *aEnvVars, const wxString &aProjectPath)
Normalize a file path to an environmental variable, if possible.
Definition env_paths.cpp:73
Helper functions to substitute paths with environmental variables.
@ FP_SMD
Definition footprint.h:87
static const wxString INFO_LEGACY_LIB_WARN_DELETE(_("Modifying legacy libraries (.mod files) is not allowed\n" "Please save the current library under the new .pretty format\n" "and update your footprint lib table\n" "before deleting a footprint"))
static const wxString INFO_LEGACY_LIB_WARN_EDIT(_("Writing/modifying legacy libraries (.mod files) is not allowed\n" "Please save the current library to the new .pretty format\n" "and update your footprint lib table\n" "to save your footprint (a .kicad_mod file) in the .pretty library folder"))
static constexpr int ID_MAKE_NEW_LIBRARY
@ FRAME_PCB_EDITOR
Definition frame_type.h:38
@ FRAME_FOOTPRINT_VIEWER
Definition frame_type.h:41
@ FRAME_FOOTPRINT_EDITOR
Definition frame_type.h:39
static const std::string KiCadFootprintLibPathExtension
static const std::string KiCadFootprintFileExtension
static wxString KiCadFootprintLibFileWildcard()
static wxString KiCadFootprintLibPathWildcard()
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
KIID niluuid(0)
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
@ F_Fab
Definition layer_ids.h:115
@ F_SilkS
Definition layer_ids.h:96
This file contains miscellaneous commonly used macros and functions.
void Prettify(std::string &aSource, FORMAT_MODE aMode)
Pretty-prints s-expression text according to KiCad format rules.
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:741
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
STL namespace.
static std::string normalizedPath(std::string aPath)
Class to handle a set of BOARD_ITEMs.
#define CTL_FOR_LIBRARY
Format output for a footprint library instead of clipboard or BOARD.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
KIWAY Kiway(KFCTL_STANDALONE)
std::vector< FAB_LAYER_COLOR > dummy
MODEL3D_FORMAT_TYPE fileType(const char *aFileName)
std::vector< wxString > pinned_fp_libs
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
wxString FileFilter() const
Definition io_base.cpp:40
wxString message
@ ID_MAKE_NEW_LIBRARY
const std::string table
@ PCB_TEXT_T
class PCB_TEXT, text on a layer
Definition typeinfo.h:84
@ PCB_FIELD_T
class PCB_FIELD, text associated with a footprint property
Definition typeinfo.h:82
Custom text control validator definitions.
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
wxString formatWildcardExt(const wxString &aWildcard)
Format wildcard extension to support case sensitive file dialogs.
Definition of file extensions used in Kicad.