KiCad PCB EDA Suite
Loading...
Searching...
No Matches
project.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, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include <wx/log.h>
25#include <wx/stdpaths.h> // required on Mac
27
28#include <algorithm>
29#include <pgm_base.h>
30#include <confirm.h>
31#include <core/kicad_algo.h>
33#include <fp_lib_table.h>
34#include <string_utils.h>
35#include <kiface_ids.h>
36#include <kiway.h>
39#include <lockfile.h>
40#include <macros.h>
42#include <git2.h>
43#include <project.h>
45#include <trace_helpers.h>
49#include <title_block.h>
50#include <local_history.h>
51
52
53
55 m_readOnly( false ),
58 m_projectFile( nullptr ),
59 m_localSettings( nullptr )
60{
61 m_elems.fill( nullptr );
62}
63
64
66{
67 // careful here, this should work, but the virtual destructor may not
68 // be in the same link image as PROJECT.
69 for( unsigned i = 0; i < m_elems.size(); ++i )
70 {
71 SetElem( static_cast<PROJECT::ELEM>( i ), nullptr );
72 }
73}
74
75
80
81
82bool PROJECT::TextVarResolver( wxString* aToken ) const
83{
84 if( aToken->IsSameAs( wxT( "PROJECTNAME" ) ) )
85 {
86 *aToken = GetProjectName();
87 return true;
88 }
89 else if( aToken->IsSameAs( wxT( "CURRENT_DATE" ) ) )
90 {
92 return true;
93 }
94 else if( aToken->IsSameAs( wxT( "VCSHASH" ) ) )
95 {
97 return true;
98 }
99 else if( aToken->IsSameAs( wxT( "VCSSHORTHASH" ) ) )
100 {
102 return true;
103 }
104 else if( GetTextVars().count( *aToken ) > 0 )
105 {
106 *aToken = GetTextVars().at( *aToken );
107 return true;
108 }
109
110 return false;
111}
112
113
114std::map<wxString, wxString>& PROJECT::GetTextVars() const
115{
116 return GetProjectFile().m_TextVars;
117}
118
119
120void PROJECT::ApplyTextVars( const std::map<wxString, wxString>& aVarsMap )
121{
122 if( aVarsMap.size() == 0 )
123 return;
124
125 std::map<wxString, wxString>& existingVarsMap = GetTextVars();
126
127 for( const auto& var : aVarsMap )
128 {
129 // create or update the existing vars
130 existingVarsMap[var.first] = var.second;
131 }
132}
133
134
135void PROJECT::setProjectFullName( const wxString& aFullPathAndName )
136{
137 // Compare paths, rather than inodes, to be less surprising to the user.
138 // Create a temporary wxFileName to normalize the path
139 wxFileName candidate_path( aFullPathAndName );
140
141 // Edge transitions only. This is what clears the project
142 // data using the Clear() function.
143 if( m_project_name.GetFullPath() != candidate_path.GetFullPath() )
144 {
145 Clear(); // clear the data when the project changes.
146
147 wxLogTrace( tracePathsAndFiles, "%s: old:'%s' new:'%s'", __func__,
148 TO_UTF8( GetProjectFullName() ), TO_UTF8( aFullPathAndName ) );
149
150 m_project_name = aFullPathAndName;
151
152 wxASSERT( m_project_name.IsAbsolute() );
153
154 wxASSERT( m_project_name.GetExt() == FILEEXT::ProjectFileExtension );
155 }
156}
157
158
159const wxString PROJECT::GetProjectFullName() const
160{
161 return m_project_name.GetFullPath();
162}
163
164
165const wxString PROJECT::GetProjectPath() const
166{
167 return m_project_name.GetPathWithSep();
168}
169
170
171const wxString PROJECT::GetProjectDirectory() const
172{
173 return m_project_name.GetPath();
174}
175
176
177const wxString PROJECT::GetProjectName() const
178{
179 return m_project_name.GetName();
180}
181
182
184{
185 return m_project_name.GetName().IsEmpty();
186}
187
188
193
194
199
200
205
206
207void PROJECT::PinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
208{
210 std::vector<wxString>* pinnedLibsCfg = nullptr;
211 std::vector<wxString>* pinnedLibsFile = nullptr;
212
213 switch( aLibType )
214 {
216 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
217 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
218 break;
220 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
221 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
222 break;
224 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
225 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
226 break;
227 default:
228 wxFAIL_MSG( "Cannot pin library: invalid library type" );
229 return;
230 }
231
232 if( !alg::contains( *pinnedLibsFile, aLibrary ) )
233 pinnedLibsFile->push_back( aLibrary );
234
236
237 if( !alg::contains( *pinnedLibsCfg, aLibrary ) )
238 pinnedLibsCfg->push_back( aLibrary );
239
240 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
241}
242
243
244void PROJECT::UnpinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
245{
247 std::vector<wxString>* pinnedLibsCfg = nullptr;
248 std::vector<wxString>* pinnedLibsFile = nullptr;
249
250 switch( aLibType )
251 {
253 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
254 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
255 break;
257 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
258 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
259 break;
261 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
262 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
263 break;
264 default:
265 wxFAIL_MSG( "Cannot unpin library: invalid library type" );
266 return;
267 }
268
269 std::erase( *pinnedLibsFile, aLibrary );
271
272 std::erase( *pinnedLibsCfg, aLibrary );
273 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
274}
275
276
277const wxString PROJECT::libTableName( const wxString& aLibTableName ) const
278{
279 wxFileName fn = GetProjectFullName();
280 wxString path = fn.GetPath();
281
282 // if there's no path to the project name, or the name as a whole is bogus or its not
283 // write-able then use a template file.
284 if( !fn.GetDirCount() || !fn.IsOk() || !wxFileName::IsDirWritable( path ) )
285 {
286 // return a template filename now.
287
288 // this next line is likely a problem now, since it relies on an
289 // application title which is no longer constant or known. This next line needs
290 // to be re-thought out.
291
292#ifdef __WXMAC__
293 fn.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
294#else
295 // don't pollute home folder, temp folder seems to be more appropriate
296 fn.AssignDir( wxStandardPaths::Get().GetTempDir() );
297#endif
298
299#if defined( __WINDOWS__ )
300 fn.AppendDir( wxT( "kicad" ) );
301#endif
302
303 /*
304 * The library table name used when no project file is passed to the appropriate
305 * code. This is used temporarily to store the project specific library table
306 * until the project file being edited is saved. It is then moved to the correct
307 * file in the folder where the project file is saved.
308 */
309 fn.SetName( wxS( "prj-" ) + aLibTableName );
310 }
311 else // normal path.
312 {
313 fn.SetName( aLibTableName );
314 }
315
316 fn.ClearExt();
317
318 return fn.GetFullPath();
319}
320
321
322const wxString PROJECT::GetSheetName( const KIID& aSheetID )
323{
324 if( m_sheetNames.empty() )
325 {
326 for( const std::pair<KIID, wxString>& pair : GetProjectFile().GetSheets() )
327 m_sheetNames[pair.first] = pair.second;
328 }
329
330 if( m_sheetNames.count( aSheetID ) )
331 return m_sheetNames.at( aSheetID );
332 else
333 return aSheetID.AsString();
334}
335
336
337void PROJECT::SetRString( RSTRING_T aIndex, const wxString& aString )
338{
339 unsigned ndx = unsigned( aIndex );
340
341 if( ndx < m_rstrings.size() )
342 m_rstrings[ndx] = aString;
343 else
344 wxASSERT( 0 ); // bad index
345}
346
347
348const wxString& PROJECT::GetRString( RSTRING_T aIndex )
349{
350 unsigned ndx = unsigned( aIndex );
351
352 if( ndx < m_rstrings.size() )
353 {
354 return m_rstrings[ndx];
355 }
356 else
357 {
358 static wxString no_cookie_for_you;
359
360 wxASSERT( 0 ); // bad index
361
362 return no_cookie_for_you;
363 }
364}
365
366
368{
369 // This is virtual, so implement it out of line
370
371 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
372 return m_elems[static_cast<unsigned>( aIndex )];
373
374 return nullptr;
375}
376
377
379{
380 // This is virtual, so implement it out of line
381 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
382 {
383 delete m_elems[static_cast<unsigned>(aIndex)];
384 m_elems[static_cast<unsigned>( aIndex )] = aElem;
385 }
386}
387
388
389const wxString PROJECT::AbsolutePath( const wxString& aFileName ) const
390{
391 wxFileName fn = aFileName;
392
393 // Paths which start with an unresolved variable reference are more likely to be
394 // absolute than relative.
395 if( aFileName.StartsWith( wxT( "${" ) ) )
396 return aFileName;
397
398 if( !fn.IsAbsolute() )
399 {
400 wxString pro_dir = wxPathOnly( GetProjectFullName() );
401 fn.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS, pro_dir );
402 }
403
404 return fn.GetFullPath();
405}
406
407
409{
410 // This is a lazy loading function, it loads the project specific table when
411 // that table is asked for, not before.
412
414
415 if( tbl )
416 {
417 wxASSERT( tbl->ProjectElementType() == PROJECT::ELEM::FPTBL );
418 }
419 else
420 {
421 try
422 {
423 // Build a new project specific FP_LIB_TABLE with the global table as a fallback.
424 // ~FP_LIB_TABLE() will not touch the fallback table, so multiple projects may
425 // stack this way, all using the same global fallback table.
426 KIFACE* kiface = aKiway.KiFACE( KIWAY::FACE_PCB );
427
428 tbl = (FP_LIB_TABLE*) kiface->IfaceOrAddress( KIFACE_NEW_FOOTPRINT_TABLE );
429 tbl->Load( FootprintLibTblName() );
430
432 }
433 catch( const IO_ERROR& ioe )
434 {
435 DisplayErrorMessage( nullptr, _( "Error loading project footprint library table." ),
436 ioe.What() );
437 }
438 catch( ... )
439 {
440 DisplayErrorMessage( nullptr, _( "Error loading project footprint library table." ) );
441 }
442 }
443
444 return tbl;
445}
446
447
449{
450 std::scoped_lock lock( m_designBlockLibsMutex );
451
453 std::optional<LIBRARY_MANAGER_ADAPTER*> adapter = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
454
455 if( !adapter )
456 {
458 std::make_unique<DESIGN_BLOCK_LIBRARY_ADAPTER>( mgr ) );
459
460 std::optional<LIBRARY_MANAGER_ADAPTER*> created = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
461 wxCHECK( created && ( *created )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
462 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *created );
463 }
464
465 wxCHECK( ( *adapter )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
466 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *adapter );
467}
468
469
471{
472 return m_project_lock.get();
473}
474
475
477{
478 m_project_lock.reset( aLockFile );
479}
480
481
482void PROJECT::SaveToHistory( const wxString& aProjectPath, std::vector<wxString>& aFiles )
483{
484 wxString projectFile = GetProjectFullName();
485
486 if( projectFile.IsEmpty() )
487 return;
488
489 wxFileName projectFn( projectFile );
490 wxFileName requestedFn( aProjectPath );
491
492 if( !projectFn.Normalize( wxPATH_NORM_ALL ) || !requestedFn.Normalize( wxPATH_NORM_ALL ) )
493 return;
494
495 if( projectFn.GetFullPath() != requestedFn.GetFullPath() )
496 return;
497
498 wxFileName historyDir( projectFn.GetPath(), wxS( ".history" ) );
499
500 if( !historyDir.DirExists() )
501 {
502 if( !historyDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
503 return;
504 }
505
506 // Save project file (.kicad_pro)
507 wxFileName historyProFile( historyDir.GetFullPath(), projectFn.GetName(),
508 projectFn.GetExt() );
509 wxCopyFile( projectFile, historyProFile.GetFullPath(), true );
510 aFiles.push_back( historyProFile.GetFullPath() );
511
512 // Save project local settings (.kicad_prl) if it exists
513 wxFileName prlFile( projectFn.GetPath(), projectFn.GetName(), FILEEXT::ProjectLocalSettingsFileExtension );
514
515 if( prlFile.FileExists() )
516 {
517 wxFileName historyPrlFile( historyDir.GetFullPath(), prlFile.GetName(),
518 prlFile.GetExt() );
519 wxCopyFile( prlFile.GetFullPath(), historyPrlFile.GetFullPath(), true );
520 aFiles.push_back( historyPrlFile.GetFullPath() );
521 }
522}
PROJECT::ELEM ProjectElementType() override
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 bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
Calls Store() and then writes the contents of the JSON document to a file.
static wxString GetCurrentHash(const wxString &aProjectFile, bool aShort)
Return the current HEAD commit hash for the repository containing aProjectFile.
Definition kiid.h:49
wxString AsString() const
Definition kiid.cpp:246
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:292
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:206
@ FACE_PCB
pcbnew DSO
Definition kiway.h:300
std::optional< LIBRARY_MANAGER_ADAPTER * > Adapter(LIBRARY_TABLE_TYPE aType) const
void RegisterAdapter(LIBRARY_TABLE_TYPE aType, std::unique_ptr< LIBRARY_MANAGER_ADAPTER > &&aAdapter)
void Load(const wxString &aFileName)
Load the library table using the path defined by aFileName aFallBackTable.
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:537
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:128
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:130
A PROJECT can hold stuff it knows nothing about, in the form of _ELEM derivatives.
Definition project.h:98
std::map< wxString, wxString > m_TextVars
PROJECT_FILE * m_projectFile
Backing store for project data – owned by SETTINGS_MANAGER.
Definition project.h:373
void SetProjectLock(LOCKFILE *aLockFile)
Definition project.cpp:476
LOCKFILE * GetProjectLock() const
Definition project.cpp:470
@ SYMBOL_LIB
Definition project.h:195
@ DESIGN_BLOCK_LIB
Definition project.h:197
@ FOOTPRINT_LIB
Definition project.h:196
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:159
virtual void SetElem(PROJECT::ELEM aIndex, _ELEM *aElem)
Definition project.cpp:378
virtual const wxString DesignBlockLibTblName() const
Return the path and file name of this projects design block library table.
Definition project.cpp:201
void PinLibrary(const wxString &aLibrary, enum LIB_TYPE_T aLibType)
Definition project.cpp:207
RSTRING_T
Retain a number of project specific wxStrings, enumerated here:
Definition project.h:219
std::map< KIID, wxString > m_sheetNames
Definition project.h:378
std::unique_ptr< LOCKFILE > m_project_lock
Lock.
Definition project.h:387
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:165
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:177
int m_netclassesTicker
Update counter on netclasses.
Definition project.h:370
virtual const wxString SymbolLibTableName() const
Return the path and file name of this projects symbol library table.
Definition project.cpp:189
virtual _ELEM * GetElem(PROJECT::ELEM aIndex)
Get and set the elements for this project.
Definition project.cpp:367
virtual ~PROJECT()
Definition project.cpp:76
void SaveToHistory(const wxString &aProjectPath, std::vector< wxString > &aFiles)
Save project files (.kicad_pro and .kicad_prl) to the .history directory.
Definition project.cpp:482
virtual FP_LIB_TABLE * PcbFootprintLibs(KIWAY &aKiway)
Return the table of footprint libraries.
Definition project.cpp:408
virtual void ApplyTextVars(const std::map< wxString, wxString > &aVarsMap)
Applies the given var map, it will create or update existing vars.
Definition project.cpp:120
virtual DESIGN_BLOCK_LIBRARY_ADAPTER * DesignBlockLibs()
Return the table of design block libraries.
Definition project.cpp:448
virtual bool TextVarResolver(wxString *aToken) const
Definition project.cpp:82
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:205
virtual const wxString GetSheetName(const KIID &aSheetID)
Return the name of the sheet identified by the given UUID.
Definition project.cpp:322
std::mutex m_designBlockLibsMutex
Synchronise access to DesignBlockLibs()
Definition project.h:390
std::array< _ELEM *, static_cast< unsigned int >(PROJECT::ELEM::COUNT)> m_elems
Definition project.h:384
virtual void elemsClear()
Delete all the _ELEMs and set their pointers to NULL.
Definition project.cpp:65
virtual const wxString FootprintLibTblName() const
Returns the path and filename of this project's footprint library table.
Definition project.cpp:195
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:337
wxFileName m_project_name
<fullpath>/<basename>.pro
Definition project.h:366
void Clear()
Clear the _ELEMs and RSTRINGs.
Definition project.h:276
PROJECT_LOCAL_SETTINGS * m_localSettings
Backing store for project local settings – owned by SETTINGS_MANAGER.
Definition project.h:376
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:389
int m_textVarsTicker
Update counter on text vars.
Definition project.h:369
void UnpinLibrary(const wxString &aLibrary, enum LIB_TYPE_T aLibType)
Definition project.cpp:244
std::array< wxString, RSTRING_COUNT > m_rstrings
Definition project.h:381
const wxString libTableName(const wxString &aLibTableName) const
Return the full path and file name of the project specific library table aLibTableName.
Definition project.cpp:277
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition project.cpp:135
bool m_readOnly
No project files will be written to disk.
Definition project.h:368
virtual const wxString GetProjectDirectory() const
Return the full path of the project DIRECTORY.
Definition project.cpp:171
virtual std::map< wxString, wxString > & GetTextVars() const
Definition project.cpp:114
PROJECT()
Definition project.cpp:54
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:348
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition project.cpp:183
ELEM
The set of #_ELEMs that a PROJECT can hold.
Definition project.h:72
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
static wxString GetCurrentDate()
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:202
This file is part of the common library.
#define _(s)
static const std::string SymbolLibraryTableFileName
static const std::string ProjectFileExtension
static const std::string ProjectLocalSettingsFileExtension
static const std::string DesignBlockLibraryTableFileName
static const std::string FootprintLibraryTableFileName
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
@ KIFACE_NEW_FOOTPRINT_TABLE
Return a new FP_LIB_TABLE with the global table installed as a fallback.
Definition kiface_ids.h:46
File locking utilities.
This file contains miscellaneous commonly used macros and functions.
wxString GetUserConfigPath()
Retrieves the operating system specific path for a user's configuration store.
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:100
SETTINGS_MANAGER * GetSettingsManager()
PGM_BASE & Pgm()
The global program "get" accessor.
Definition pgm_base.cpp:946
see class PGM_BASE
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
std::vector< wxString > pinned_design_block_libs
std::vector< wxString > pinned_fp_libs
std::vector< wxString > pinned_symbol_libs
Implement a participant in the KIWAY alchemy.
Definition kiway.h:155
IFACE KIFACE_BASE kiface("pcb_test_frame", KIWAY::FACE_PCB)
wxLogTrace helper definitions.
Definition of file extensions used in Kicad.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:39