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( "VCSHASH" ) ) )
101 {
103 return true;
104 }
105 else if( aToken->IsSameAs( wxT( "VCSSHORTHASH" ) ) )
106 {
108 return true;
109 }
110 else if( GetTextVars().count( *aToken ) > 0 )
111 {
112 *aToken = GetTextVars().at( *aToken );
113 return true;
114 }
115
116 return false;
117}
118
119
120std::map<wxString, wxString>& PROJECT::GetTextVars() const
121{
122 return GetProjectFile().m_TextVars;
123}
124
125
126void PROJECT::ApplyTextVars( const std::map<wxString, wxString>& aVarsMap )
127{
128 if( aVarsMap.size() == 0 )
129 return;
130
131 std::map<wxString, wxString>& existingVarsMap = GetTextVars();
132
133 for( const auto& var : aVarsMap )
134 {
135 // create or update the existing vars
136 existingVarsMap[var.first] = var.second;
137 }
138}
139
140
141void PROJECT::setProjectFullName( const wxString& aFullPathAndName )
142{
143 // Compare paths, rather than inodes, to be less surprising to the user.
144 // Create a temporary wxFileName to normalize the path
145 wxFileName candidate_path( aFullPathAndName );
146
147 // Edge transitions only. This is what clears the project
148 // data using the Clear() function.
149 if( m_project_name.GetFullPath() != candidate_path.GetFullPath() )
150 {
151 Clear(); // clear the data when the project changes.
152
153 wxLogTrace( tracePathsAndFiles, "%s: old:'%s' new:'%s'", __func__,
154 TO_UTF8( GetProjectFullName() ), TO_UTF8( aFullPathAndName ) );
155
156 m_project_name = aFullPathAndName;
157
158 wxASSERT( m_project_name.IsAbsolute() );
159 wxString ext = m_project_name.GetExt();
160
161 if( !ext.IsEmpty() && ext != FILEEXT::ProjectFileExtension )
162 {
163 wxLogDebug( wxT( "Project file has unexpected extension '%s', expected '%s'" ), ext,
166 }
167 }
168}
169
170
171const wxString PROJECT::GetProjectFullName() const
172{
173 return m_project_name.GetFullPath();
174}
175
176
177const wxString PROJECT::GetProjectPath() const
178{
179 return m_project_name.GetPathWithSep();
180}
181
182
183const wxString PROJECT::GetProjectDirectory() const
184{
185 return m_project_name.GetPath();
186}
187
188
189const wxString PROJECT::GetProjectName() const
190{
191 return m_project_name.GetName();
192}
193
194
196{
197 return m_project_name.GetName().IsEmpty();
198}
199
200
205
206
211
212
217
218
219void PROJECT::PinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
220{
222 std::vector<wxString>* pinnedLibsCfg = nullptr;
223 std::vector<wxString>* pinnedLibsFile = nullptr;
224
225 switch( aLibType )
226 {
228 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
229 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
230 break;
232 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
233 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
234 break;
236 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
237 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
238 break;
239 default:
240 wxFAIL_MSG( "Cannot pin library: invalid library type" );
241 return;
242 }
243
244 if( !alg::contains( *pinnedLibsFile, aLibrary ) )
245 pinnedLibsFile->push_back( aLibrary );
246
248
249 if( !alg::contains( *pinnedLibsCfg, aLibrary ) )
250 pinnedLibsCfg->push_back( aLibrary );
251
252 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
253}
254
255
256void PROJECT::UnpinLibrary( const wxString& aLibrary, enum LIB_TYPE_T aLibType )
257{
259 std::vector<wxString>* pinnedLibsCfg = nullptr;
260 std::vector<wxString>* pinnedLibsFile = nullptr;
261
262 switch( aLibType )
263 {
265 pinnedLibsFile = &m_projectFile->m_PinnedSymbolLibs;
266 pinnedLibsCfg = &cfg->m_Session.pinned_symbol_libs;
267 break;
269 pinnedLibsFile = &m_projectFile->m_PinnedFootprintLibs;
270 pinnedLibsCfg = &cfg->m_Session.pinned_fp_libs;
271 break;
273 pinnedLibsFile = &m_projectFile->m_PinnedDesignBlockLibs;
274 pinnedLibsCfg = &cfg->m_Session.pinned_design_block_libs;
275 break;
276 default:
277 wxFAIL_MSG( "Cannot unpin library: invalid library type" );
278 return;
279 }
280
281 std::erase( *pinnedLibsFile, aLibrary );
283
284 std::erase( *pinnedLibsCfg, aLibrary );
285 cfg->SaveToFile( Pgm().GetSettingsManager().GetPathForSettingsFile( cfg ) );
286}
287
288
289const wxString PROJECT::libTableName( const wxString& aLibTableName ) const
290{
291 wxFileName fn = GetProjectFullName();
292 wxString path = fn.GetPath();
293
294 // if there's no path to the project name, or the name as a whole is bogus or its not
295 // write-able then use a template file.
296 if( !fn.GetDirCount() || !fn.IsOk() || !wxFileName::IsDirWritable( path ) )
297 {
298 // return a template filename now.
299
300 // this next line is likely a problem now, since it relies on an
301 // application title which is no longer constant or known. This next line needs
302 // to be re-thought out.
303
304#ifdef __WXMAC__
305 fn.AssignDir( KIPLATFORM::ENV::GetUserConfigPath() );
306#else
307 // don't pollute home folder, temp folder seems to be more appropriate
308 fn.AssignDir( wxStandardPaths::Get().GetTempDir() );
309#endif
310
311#if defined( __WINDOWS__ )
312 fn.AppendDir( wxT( "kicad" ) );
313#endif
314
315 /*
316 * The library table name used when no project file is passed to the appropriate
317 * code. This is used temporarily to store the project specific library table
318 * until the project file being edited is saved. It is then moved to the correct
319 * file in the folder where the project file is saved.
320 */
321 fn.SetName( wxS( "prj-" ) + aLibTableName );
322 }
323 else // normal path.
324 {
325 fn.SetName( aLibTableName );
326 }
327
328 fn.ClearExt();
329
330 return fn.GetFullPath();
331}
332
333
334const wxString PROJECT::GetSheetName( const KIID& aSheetID )
335{
336 if( m_sheetNames.empty() )
337 {
338 for( const std::pair<KIID, wxString>& pair : GetProjectFile().GetSheets() )
339 m_sheetNames[pair.first] = pair.second;
340 }
341
342 if( m_sheetNames.count( aSheetID ) )
343 return m_sheetNames.at( aSheetID );
344 else
345 return aSheetID.AsString();
346}
347
348
349void PROJECT::SetRString( RSTRING_T aIndex, const wxString& aString )
350{
351 unsigned ndx = unsigned( aIndex );
352
353 if( ndx < m_rstrings.size() )
354 m_rstrings[ndx] = aString;
355 else
356 wxASSERT( 0 ); // bad index
357}
358
359
360const wxString& PROJECT::GetRString( RSTRING_T aIndex )
361{
362 unsigned ndx = unsigned( aIndex );
363
364 if( ndx < m_rstrings.size() )
365 {
366 return m_rstrings[ndx];
367 }
368 else
369 {
370 static wxString no_cookie_for_you;
371
372 wxASSERT( 0 ); // bad index
373
374 return no_cookie_for_you;
375 }
376}
377
378
380{
381 // This is virtual, so implement it out of line
382
383 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
384 return m_elems[static_cast<unsigned>( aIndex )];
385
386 return nullptr;
387}
388
389
391{
392 // This is virtual, so implement it out of line
393 if( static_cast<unsigned>( aIndex ) < m_elems.size() )
394 {
395 delete m_elems[static_cast<unsigned>(aIndex)];
396 m_elems[static_cast<unsigned>( aIndex )] = aElem;
397 }
398}
399
400
401const wxString PROJECT::AbsolutePath( const wxString& aFileName ) const
402{
403 wxFileName fn = aFileName;
404
405 // Paths which start with an unresolved variable reference are more likely to be
406 // absolute than relative.
407 if( aFileName.StartsWith( wxT( "${" ) ) )
408 return aFileName;
409
410 if( !fn.IsAbsolute() )
411 {
412 wxString pro_dir = wxPathOnly( GetProjectFullName() );
413 fn.Normalize( FN_NORMALIZE_FLAGS | wxPATH_NORM_ENV_VARS, pro_dir );
414 }
415
416 return fn.GetFullPath();
417}
418
419
425
426
428{
429 std::scoped_lock lock( m_designBlockLibsMutex );
430
432 std::optional<LIBRARY_MANAGER_ADAPTER*> adapter = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
433
434 if( !adapter )
435 {
437 std::make_unique<DESIGN_BLOCK_LIBRARY_ADAPTER>( mgr ) );
438
439 std::optional<LIBRARY_MANAGER_ADAPTER*> created = mgr.Adapter( LIBRARY_TABLE_TYPE::DESIGN_BLOCK );
440 wxCHECK( created && ( *created )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
441 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *created );
442 }
443
444 wxCHECK( ( *adapter )->Type() == LIBRARY_TABLE_TYPE::DESIGN_BLOCK, nullptr );
445 return static_cast<DESIGN_BLOCK_LIBRARY_ADAPTER*>( *adapter );
446}
447
448
450{
451 return m_project_lock.get();
452}
453
454
456{
457 m_project_lock.reset( aLockFile );
458}
459
460
461void PROJECT::SaveToHistory( const wxString& aProjectPath, std::vector<wxString>& aFiles )
462{
463 wxString projectFile = GetProjectFullName();
464
465 if( projectFile.IsEmpty() )
466 return;
467
468 wxFileName projectFn( projectFile );
469 wxFileName requestedFn( aProjectPath );
470 // wxPATH_NORM_ALL is now deprecated.
471 // So define a similar option
472 int norm_opt = wxPATH_NORM_ENV_VARS|wxPATH_NORM_DOTS|wxPATH_NORM_TILDE|wxPATH_NORM_ABSOLUTE
473 |wxPATH_NORM_LONG|wxPATH_NORM_SHORTCUT;
474
475 if( !projectFn.Normalize( norm_opt ) || !requestedFn.Normalize( norm_opt ) )
476 return;
477
478 if( projectFn.GetFullPath() != requestedFn.GetFullPath() )
479 return;
480
481 wxFileName historyDir( projectFn.GetPath(), wxS( ".history" ) );
482
483 if( !historyDir.DirExists() )
484 {
485 if( !historyDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
486 return;
487 }
488
489 // Save project file (.kicad_pro)
490 wxFileName historyProFile( historyDir.GetFullPath(), projectFn.GetName(),
491 projectFn.GetExt() );
492 wxCopyFile( projectFile, historyProFile.GetFullPath(), true );
493 aFiles.push_back( historyProFile.GetFullPath() );
494
495 // Save project local settings (.kicad_prl) if it exists
496 wxFileName prlFile( projectFn.GetPath(), projectFn.GetName(), FILEEXT::ProjectLocalSettingsFileExtension );
497
498 if( prlFile.FileExists() )
499 {
500 wxFileName historyPrlFile( historyDir.GetFullPath(), prlFile.GetName(),
501 prlFile.GetExt() );
502 wxCopyFile( prlFile.GetFullPath(), historyPrlFile.GetFullPath(), true );
503 aFiles.push_back( historyPrlFile.GetFullPath() );
504 }
505}
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:49
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:295
virtual KIFACE * KiFACE(FACE_T aFaceId, bool doLoad=true)
Return the KIFACE* given a FACE_T.
Definition kiway.cpp:213
@ FACE_PCB
pcbnew DSO
Definition kiway.h:303
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:131
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:133
A PROJECT can hold stuff it knows nothing about, in the form of _ELEM derivatives.
Definition project.h:92
std::map< wxString, wxString > m_TextVars
PROJECT_FILE * m_projectFile
Backing store for project data – owned by SETTINGS_MANAGER.
Definition project.h:371
void SetProjectLock(LOCKFILE *aLockFile)
Definition project.cpp:455
bool m_lockOverrideGranted
User granted override at project level.
Definition project.h:366
LOCKFILE * GetProjectLock() const
Definition project.cpp:449
@ SYMBOL_LIB
Definition project.h:193
@ DESIGN_BLOCK_LIB
Definition project.h:195
@ FOOTPRINT_LIB
Definition project.h:194
virtual const wxString GetProjectFullName() const
Return the full path and name of the project.
Definition project.cpp:171
virtual void SetElem(PROJECT::ELEM aIndex, _ELEM *aElem)
Definition project.cpp:390
virtual const wxString DesignBlockLibTblName() const
Return the path and file name of this projects design block library table.
Definition project.cpp:213
void PinLibrary(const wxString &aLibrary, enum LIB_TYPE_T aLibType)
Definition project.cpp:219
RSTRING_T
Retain a number of project specific wxStrings, enumerated here:
Definition project.h:217
std::map< KIID, wxString > m_sheetNames
Definition project.h:376
std::unique_ptr< LOCKFILE > m_project_lock
Lock.
Definition project.h:385
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:177
virtual const wxString GetProjectName() const
Return the short name of the project.
Definition project.cpp:189
int m_netclassesTicker
Update counter on netclasses.
Definition project.h:368
virtual const wxString SymbolLibTableName() const
Return the path and file name of this projects symbol library table.
Definition project.cpp:201
virtual _ELEM * GetElem(PROJECT::ELEM aIndex)
Get and set the elements for this project.
Definition project.cpp:379
virtual ~PROJECT()
Definition project.cpp:79
void SaveToHistory(const wxString &aProjectPath, std::vector< wxString > &aFiles)
Save project files (.kicad_pro and .kicad_prl) to the .history directory.
Definition project.cpp:461
virtual void ApplyTextVars(const std::map< wxString, wxString > &aVarsMap)
Applies the given var map, it will create or update existing vars.
Definition project.cpp:126
virtual DESIGN_BLOCK_LIBRARY_ADAPTER * DesignBlockLibs()
Return the table of design block libraries.
Definition project.cpp:427
virtual bool TextVarResolver(wxString *aToken) const
Definition project.cpp:85
virtual PROJECT_FILE & GetProjectFile() const
Definition project.h:203
virtual const wxString GetSheetName(const KIID &aSheetID)
Return the name of the sheet identified by the given UUID.
Definition project.cpp:334
std::mutex m_designBlockLibsMutex
Synchronise access to DesignBlockLibs()
Definition project.h:388
std::array< _ELEM *, static_cast< unsigned int >(PROJECT::ELEM::COUNT)> m_elems
Definition project.h:382
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:207
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:349
wxFileName m_project_name
<fullpath>/<basename>.pro
Definition project.h:363
void Clear()
Clear the _ELEMs and RSTRINGs.
Definition project.h:274
virtual FOOTPRINT_LIBRARY_ADAPTER * FootprintLibAdapter(KIWAY &aKiway)
Fetches the footprint library adapter from the PCB editor instance.
Definition project.cpp:420
PROJECT_LOCAL_SETTINGS * m_localSettings
Backing store for project local settings – owned by SETTINGS_MANAGER.
Definition project.h:374
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:401
int m_textVarsTicker
Update counter on text vars.
Definition project.h:367
void UnpinLibrary(const wxString &aLibrary, enum LIB_TYPE_T aLibType)
Definition project.cpp:256
std::array< wxString, RSTRING_COUNT > m_rstrings
Definition project.h:379
const wxString libTableName(const wxString &aLibTableName) const
Return the full path and file name of the project specific library table aLibTableName.
Definition project.cpp:289
virtual void setProjectFullName(const wxString &aFullPathAndName)
Set the full directory, basename, and extension of the project.
Definition project.cpp:141
bool m_readOnly
No project files will be written to disk.
Definition project.h:365
virtual const wxString GetProjectDirectory() const
Return the full path of the project DIRECTORY.
Definition project.cpp:183
virtual std::map< wxString, wxString > & GetTextVars() const
Definition project.cpp:120
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:360
virtual bool IsNullProject() const
Check if this project is a null project (i.e.
Definition project.cpp:195
ELEM
The set of #_ELEMs that a PROJECT can hold.
Definition project.h:71
bool SaveProject(const wxString &aFullPath=wxEmptyString, PROJECT *aProject=nullptr)
Save a loaded project.
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
SETTINGS_MANAGER * GetSettingsManager()
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
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