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 <string_utils.h>
34#include <kiface_ids.h>
35#include <kiway.h>
38#include <lockfile.h>
39#include <macros.h>
41#include <git2.h>
42#include <project.h>
43
45
47#include <trace_helpers.h>
51#include <title_block.h>
52#include <local_history.h>
53
54
55
57 m_readOnly( false ),
58 m_lockOverrideGranted( false ),
61 m_projectFile( nullptr ),
62 m_localSettings( nullptr )
63{
64 m_elems.fill( nullptr );
65}
66
67
69{
70 // careful here, this should work, but the virtual destructor may not
71 // be in the same link image as PROJECT.
72 for( unsigned i = 0; i < m_elems.size(); ++i )
73 {
74 SetElem( static_cast<PROJECT::ELEM>( i ), nullptr );
75 }
76}
77
78
83
84
85bool PROJECT::TextVarResolver( wxString* aToken ) const
86{
87 if( !m_projectFile )
88 return false;
89
90 if( aToken->IsSameAs( wxT( "PROJECTNAME" ) ) )
91 {
92 *aToken = GetProjectName();
93 return true;
94 }
95 else if( aToken->IsSameAs( wxT( "CURRENT_DATE" ) ) )
96 {
98 return true;
99 }
100 else if( aToken->IsSameAs( wxT( "CURRENT_TIME_HH_MM_SS" ) ) )
101 {
103 return true;
104 }
105 else if( aToken->IsSameAs( wxT( "CURRENT_TIME_LOCALE" ) ) )
106 {
108 return true;
109 }
110 else if( aToken->IsSameAs( wxT( "VCSHASH" ) ) )
111 {
113 return true;
114 }
115 else if( aToken->IsSameAs( wxT( "VCSSHORTHASH" ) ) )
116 {
118 return true;
119 }
120 else if( GetTextVars().count( *aToken ) > 0 )
121 {
122 *aToken = GetTextVars().at( *aToken );
123 return true;
124 }
125
126 return false;
127}
128
129
130std::map<wxString, wxString>& PROJECT::GetTextVars() const
131{
132 return GetProjectFile().m_TextVars;
133}
134
135
136void PROJECT::ApplyTextVars( const std::map<wxString, wxString>& aVarsMap )
137{
138 if( aVarsMap.size() == 0 )
139 return;
140
141 std::map<wxString, wxString>& existingVarsMap = GetTextVars();
142
143 for( const auto& var : aVarsMap )
144 {
145 // create or update the existing vars
146 existingVarsMap[var.first] = var.second;
147 }
148}
149
150
151void PROJECT::setProjectFullName( const wxString& aFullPathAndName )
152{
153 // Compare paths, rather than inodes, to be less surprising to the user.
154 // Create a temporary wxFileName to normalize the path
155 wxFileName candidate_path( aFullPathAndName );
156
157 // Edge transitions only. This is what clears the project
158 // data using the Clear() function.
159 if( m_project_name.GetFullPath() != candidate_path.GetFullPath() )
160 {
161 Clear(); // clear the data when the project changes.
162
163 wxLogTrace( tracePathsAndFiles, "%s: old:'%s' new:'%s'", __func__,
164 TO_UTF8( GetProjectFullName() ), TO_UTF8( aFullPathAndName ) );
165
166 m_project_name = aFullPathAndName;
167
168 wxASSERT( m_project_name.IsAbsolute() );
169 wxString ext = m_project_name.GetExt();
170
171 if( !ext.IsEmpty() && ext != FILEEXT::ProjectFileExtension )
172 {
173 wxLogDebug( wxT( "Project file has unexpected extension '%s', expected '%s'" ), ext,
176 }
177 }
178}
179
180
181const wxString PROJECT::GetProjectFullName() const
182{
183 return m_project_name.GetFullPath();
184}
185
186
187const wxString PROJECT::GetProjectPath() const
188{
189 return m_project_name.GetPathWithSep();
190}
191
192
193const wxString PROJECT::GetProjectDirectory() const
194{
195 return m_project_name.GetPath();
196}
197
198
199const wxString PROJECT::GetProjectName() const
200{
201 return m_project_name.GetName();
202}
203
204
206{
207 return m_project_name.GetName().IsEmpty();
208}
209
210
215
216
221
222
227
228
229void PROJECT::PinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
230{
232 std::vector<wxString>* pinnedLibsCfg = nullptr;
233 std::vector<wxString>* pinnedLibsFile = nullptr;
234
235 switch( aLibType )
236 {
238 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
239 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
240 break;
242 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
243 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
244 break;
246 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
247 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
248 break;
249 default:
250 wxFAIL_MSG( "Cannot pin library: invalid library type" );
251 return;
252 }
253
254 if( !alg::contains( *pinnedLibsFile, aLibrary ) )
255 pinnedLibsFile->push_back( aLibrary );
256
258
259 if( !alg::contains( *pinnedLibsCfg, aLibrary ) )
260 pinnedLibsCfg->push_back( aLibrary );
261
262 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
263}
264
265
266void PROJECT::UnpinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
267{
269 std::vector<wxString>* pinnedLibsCfg = nullptr;
270 std::vector<wxString>* pinnedLibsFile = nullptr;
271
272 switch( aLibType )
273 {
275 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
276 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
277 break;
279 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
280 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
281 break;
283 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
284 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
285 break;
286 default:
287 wxFAIL_MSG( "Cannot unpin library: invalid library type" );
288 return;
289 }
290
291 std::erase( *pinnedLibsFile, aLibrary );
293
294 std::erase( *pinnedLibsCfg, aLibrary );
295 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
296}
297
298
299const wxString PROJECT::libTableName( const wxString& aLibTableName ) const
300{
301 wxFileName fn = GetProjectFullName();
302 wxString path = fn.GetPath();
303
304 // if there's no path to the project name, or the name as a whole is bogus or its not
305 // write-able then use a template file.
306 if( !fn.GetDirCount() || !fn.IsOk() || !wxFileName::IsDirWritable( path ) )
307 {
308 // return a template filename now.
309
310 // this next line is likely a problem now, since it relies on an
311 // application title which is no longer constant or known. This next line needs
312 // to be re-thought out.
313
314#ifdef __WXMAC__
315 fn.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
316#else
317 // don't pollute home folder, temp folder seems to be more appropriate
318 fn.AssignDir( wxStandardPaths::Get().GetTempDir() );
319#endif
320
321#if defined( __WINDOWS__ )
322 fn.AppendDir( wxT( "kicad" ) );
323#endif
324
325 /*
326 * The library table name used when no project file is passed to the appropriate
327 * code. This is used temporarily to store the project specific library table
328 * until the project file being edited is saved. It is then moved to the correct
329 * file in the folder where the project file is saved.
330 */
331 fn.SetName( wxS( "prj-" ) + aLibTableName );
332 }
333 else // normal path.
334 {
335 fn.SetName( aLibTableName );
336 }
337
338 fn.ClearExt();
339
340 return fn.GetFullPath();
341}
342
343
344const wxString PROJECT::GetSheetName( const KIID& aSheetID )
345{
346 if( m_sheetNames.empty() )
347 {
348 for( const std::pair<KIID, wxString>& pair : GetProjectFile().GetSheets() )
349 m_sheetNames[pair.first] = pair.second;
350 }
351
352 if( m_sheetNames.count( aSheetID ) )
353 return m_sheetNames.at( aSheetID );
354 else
355 return aSheetID.AsString();
356}
357
358
359void PROJECT::SetRString( RSTRING_T aIndex, const wxString& aString )
360{
361 unsigned ndx = unsigned( aIndex );
362
363 if( ndx < m_rstrings.size() )
364 m_rstrings[ndx] = aString;
365 else
366 wxASSERT( 0 ); // bad index
367}
368
369
370const wxString& PROJECT::GetRString( RSTRING_T aIndex )
371{
372 unsigned ndx = unsigned( aIndex );
373
374 if( ndx < m_rstrings.size() )
375 {
376 return m_rstrings[ndx];
377 }
378 else
379 {
380 static wxString no_cookie_for_you;
381
382 wxASSERT( 0 ); // bad index
383
384 return no_cookie_for_you;
385 }
386}
387
388
390{
391 // This is virtual, so implement it out of line
392
393 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
394 return m_elems[static_cast<unsigned>( aIndex )];
395
396 return nullptr;
397}
398
399
401{
402 // This is virtual, so implement it out of line
403 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
404 {
405 delete m_elems[static_cast<unsigned>(aIndex)];
406 m_elems[static_cast<unsigned>( aIndex )] = aElem;
407 }
408}
409
410
411const wxString PROJECT::AbsolutePath( const wxString& aFileName ) const
412{
413 wxFileName fn = aFileName;
414
415 // Paths which start with an unresolved variable reference are more likely to be
416 // absolute than relative.
417 if( aFileName.StartsWith( wxT( "${" ) ) )
418 return aFileName;
419
420 if( !fn.IsAbsolute() )
421 {
422 wxString pro_dir = wxPathOnly( GetProjectFullName() );
423 fn.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS, pro_dir );
424 }
425
426 return fn.GetFullPath();
427}
428
429
435
436
438{
439 std::scoped_lock lock( m_designBlockLibsMutex );
440
442 std::optional<LIBRARY_MANAGER_ADAPTER*> adapter = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
443
444 if( !adapter )
445 {
447 std::make_unique<DESIGN_BLOCK_LIBRARY_ADAPTER>( mgr ) );
448
449 std::optional<LIBRARY_MANAGER_ADAPTER*> created = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
450 wxCHECK( created && ( *created )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
451 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *created );
452 }
453
454 wxCHECK( ( *adapter )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
455 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *adapter );
456}
457
458
460{
461 return m_project_lock.get();
462}
463
464
466{
467 m_project_lock.reset( aLockFile );
468}
469
470
471void PROJECT::SaveToHistory( const wxString& aProjectPath, std::vector<HISTORY_FILE_DATA>& aFileData )
472{
473 wxString projectFile = GetProjectFullName();
474
475 if( projectFile.IsEmpty() )
476 return;
477
478 wxFileName projectFn( projectFile );
479 wxFileName requestedFn( aProjectPath );
480 // wxPATH_NORM_ALL is now deprecated.
481 // So define a similar option
482 int norm_opt = wxPATH_NORM_ENV_VARS|wxPATH_NORM_DOTS|wxPATH_NORM_TILDE|wxPATH_NORM_ABSOLUTE
483 |wxPATH_NORM_LONG|wxPATH_NORM_SHORTCUT;
484
485 if( !projectFn.Normalize( norm_opt ) || !requestedFn.Normalize( norm_opt ) )
486 return;
487
488 if( projectFn.GetFullPath() != requestedFn.GetFullPath() )
489 return;
490
491 wxFileName historyDir( projectFn.GetPath(), wxS( ".history" ) );
492
493 if( !historyDir.DirExists() )
494 {
495 if( !historyDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
496 return;
497 }
498
499 // Save project file (.kicad_pro) via file-copy
500 wxFileName historyProFile( historyDir.GetFullPath(), projectFn.GetName(),
501 projectFn.GetExt() );
502
503 HISTORY_FILE_DATA proEntry;
504 proEntry.path = historyProFile.GetFullPath();
505 proEntry.sourcePath = projectFile;
506 aFileData.push_back( std::move( proEntry ) );
507
508 // Save project local settings (.kicad_prl) if it exists
509 wxFileName prlFile( projectFn.GetPath(), projectFn.GetName(), FILEEXT::ProjectLocalSettingsFileExtension );
510
511 if( prlFile.FileExists() )
512 {
513 wxFileName historyPrlFile( historyDir.GetFullPath(), prlFile.GetName(),
514 prlFile.GetExt() );
515
516 HISTORY_FILE_DATA prlEntry;
517 prlEntry.path = historyPrlFile.GetFullPath();
518 prlEntry.sourcePath = prlFile.GetFullPath();
519 aFileData.push_back( std::move( prlEntry ) );
520 }
521}
An interface to the global shared library manager that is schematic-specific and linked to one projec...
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:48
wxString AsString() const
Definition kiid.cpp:244
A minimalistic software bus for communications between various DLLs/DSOs (DSOs) within the same KiCad...
Definition kiway.h:315
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:211
@ FACE_PCB
pcbnew DSO
Definition kiway.h:323
std::optional< LIBRARY_MANAGER_ADAPTER * > Adapter(LIBRARY_TABLE_TYPE aType) const
void RegisterAdapter(LIBRARY_TABLE_TYPE aType, std::unique_ptr< LIBRARY_MANAGER_ADAPTER > &&aAdapter)
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:541
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:130
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:132
A PROJECT can hold stuff it knows nothing about, in the form of _ELEM derivatives.
Definition project.h:93
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:465
bool m_lockOverrideGranted
User granted override at project level.
Definition project.h:368
LOCKFILE * GetProjectLock() const
Definition project.cpp:459
@ SYMBOL_LIB
Definition project.h:194
@ DESIGN_BLOCK_LIB
Definition project.h:196
@ FOOTPRINT_LIB
Definition project.h:195
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:181
virtual void SetElem(PROJECT::ELEM aIndex, _ELEM *aElem)
Definition project.cpp:400
virtual const wxString DesignBlockLibTblName() const
Return the path and file name of this projects design block library table.
Definition project.cpp:223
void PinLibrary(const wxString &aLibrary, enum LIB_TYPE_T aLibType)
Definition project.cpp:229
RSTRING_T
Retain a number of project specific wxStrings, enumerated here:
Definition project.h:218
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:187
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:199
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:211
virtual _ELEM * GetElem(PROJECT::ELEM aIndex)
Get and set the elements for this project.
Definition project.cpp:389
virtual ~PROJECT()
Definition project.cpp:79
virtual void ApplyTextVars(const std::map< wxString, wxString > &aVarsMap)
Applies the given var map, it will create or update existing vars.
Definition project.cpp:136
virtual DESIGN_BLOCK_LIBRARY_ADAPTER * DesignBlockLibs()
Return the table of design block libraries.
Definition project.cpp:437
virtual bool TextVarResolver(wxString *aToken) const
Definition project.cpp:85
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:204
virtual const wxString GetSheetName(const KIID &aSheetID)
Return the name of the sheet identified by the given UUID.
Definition project.cpp:344
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:68
virtual const wxString FootprintLibTblName() const
Returns the path and filename of this project's footprint library table.
Definition project.cpp:217
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:359
wxFileName m_project_name
<fullpath>/<basename>.pro
Definition project.h:365
void Clear()
Clear the _ELEMs and RSTRINGs.
Definition project.h:275
virtual FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(KIWAY &aKiway)
Fetches the footprint library adapter from the PCB editor instance.
Definition project.cpp:430
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:411
void SaveToHistory(const wxString &aProjectPath, std::vector< HISTORY_FILE_DATA > &aFileData)
Produce HISTORY_FILE_DATA entries for project files (.kicad_pro and .kicad_prl).
Definition project.cpp:471
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:266
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:299
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition project.cpp:151
bool m_readOnly
No project files will be written to disk.
Definition project.h:367
virtual const wxString GetProjectDirectory() const
Return the full path of the project DIRECTORY.
Definition project.cpp:193
virtual std::map< wxString, wxString > & GetTextVars() const
Definition project.cpp:130
PROJECT()
Definition project.cpp:56
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:370
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition project.cpp:205
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 GetCurrentTimeLocale()
static wxString GetCurrentTimeHHMMSS()
static wxString GetCurrentDate()
This file is part of the common library.
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_FOOTPRINT_LIBRARY_ADAPTER
Definition kiface_ids.h:34
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
PGM_BASE & Pgm()
The global program "get" accessor.
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
Data produced by a registered saver on the UI thread, consumed by the background commit thread.
wxString sourcePath
For file-copy savers (small files like .kicad_pro)
wxString path
Destination inside .history/.
Implement a participant in the KIWAY alchemy.
Definition kiway.h:156
IFACE KIFACE_BASE kiface("pcb_test_frame", KIWAY::FACE_PCB)
std::string path
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