KiCad PCB EDA Suite
prjconfig.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2004-2015 Jean-Pierre Charras
5  * Copyright (C) 2004-2017 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
31 #include <wx/dir.h>
32 #include <wx/filename.h>
33 #include <wx/stdpaths.h>
34 #include <wx/msgdlg.h>
35 
36 #include <build_version.h>
37 #include <config_params.h>
38 #include <confirm.h>
39 #include <kiway.h>
40 #include <project.h>
42 
44 
45 #include "kicad.h"
46 #include "pgm_kicad.h"
47 #include "tree_project_frame.h"
48 
49 
50 #define SEP() wxFileName::GetPathSeparator()
51 
52 // Not really useful, provided to save/restore params in project config file,
53 // (Add them in s_KicadManagerParams if any)
54 // Used also to create new .pro files from the kicad.pro template file
55 // for new projects
56 #define GeneralGroupName wxT( "/general" )
57 
59 
60 
61 void KICAD_MANAGER_FRAME::LoadProject( const wxFileName& aProjectFileName )
62 {
63  // The project file should be valid by the time we get here or something has gone wrong.
64  if( !aProjectFileName.Exists() )
65  return;
66 
67  // Any open KIFACE's must be closed if they are not part of the new project.
68  // (We never want a KIWAY_PLAYER open on a KIWAY that isn't in the same project.)
69  // User is prompted here to close those KIWAY_PLAYERs:
70  if( !Kiway.PlayersClose( false ) )
71  return;
72 
73  SetTitle( wxString( "KiCad " ) + GetBuildVersion() );
74 
75  // Save the project file for the currently loaded project.
76  if( m_active_project )
77  Prj().ConfigLoad( PgmTop().SysSearch(), GeneralGroupName, s_KicadManagerParams );
78 
79  m_active_project = true;
80  ClearMsg();
81  SetProjectFileName( aProjectFileName.GetFullPath() );
82  Prj().ConfigLoad( PgmTop().SysSearch(), GeneralGroupName, s_KicadManagerParams );
83 
84  wxString title = GetTitle() + " " + aProjectFileName.GetFullPath();
85 
86  if( !aProjectFileName.IsDirWritable() )
87  title += _( " [Read Only]" );
88  else
89  SetMruPath( Prj().GetProjectPath() ); // Only set MRU path if we have write access. Why?
90 
91  SetTitle( title );
92 
93  UpdateFileHistory( aProjectFileName.GetFullPath(), &PgmTop().GetFileHistory() );
94 
96 
97  // Rebuild the list of watched paths.
98  // however this is possible only when the main loop event handler is running,
99  // so we use it to run the rebuild function.
100  wxCommandEvent cmd( wxEVT_COMMAND_MENU_SELECTED, ID_INIT_WATCHED_PATHS );
101 
102  wxPostEvent( this, cmd );
103 
104  PrintPrjInfo();
105 }
106 
107 
108 void KICAD_MANAGER_FRAME::CreateNewProject( const wxFileName& aProjectFileName )
109 {
110  wxCHECK_RET( aProjectFileName.DirExists() && aProjectFileName.IsDirWritable(),
111  "Project folder must exist and be writable to create a new project." );
112 
113  // Init project filename. This clears all elements from the project object.
114  SetProjectFileName( aProjectFileName.GetFullPath() );
115 
116  // Copy kicad.pro file from template folder.
117  if( !aProjectFileName.FileExists() )
118  {
119  wxString srcFileName = sys_search().FindValidPath( "kicad.pro" );
120 
121  // Create a minimal project (.pro) file if the template project file could not be copied.
122  if( !wxFileName::FileExists( srcFileName )
123  || !wxCopyFile( srcFileName, aProjectFileName.GetFullPath() ) )
124  {
125  Prj().ConfigSave( PgmTop().SysSearch(), GeneralGroupName, s_KicadManagerParams );
126  }
127  }
128 
129  // Ensure a "stub" for a schematic root sheet and a board exist.
130  // It will avoid messages from the schematic editor or the board editor to create a new file
131  // And forces the user to create main files under the right name for the project manager
132  wxFileName fn( aProjectFileName.GetFullPath() );
133  fn.SetExt( SchematicFileExtension );
134 
135  // If a <project>.sch file does not exist, create a "stub" file ( minimal schematic file )
136  if( !fn.FileExists() )
137  {
138  wxFile file( fn.GetFullPath(), wxFile::write );
139 
140  if( file.IsOpened() )
141  file.Write( wxT( "EESchema Schematic File Version 2\n"
142  "EELAYER 25 0\nEELAYER END\n$EndSCHEMATC\n" ) );
143 
144  // wxFile dtor will close the file
145  }
146 
147  // If a <project>.kicad_pcb or <project>.brd file does not exist,
148  // create a .kicad_pcb "stub" file
149  fn.SetExt( KiCadPcbFileExtension );
150  wxFileName leg_fn( fn );
151  leg_fn.SetExt( LegacyPcbFileExtension );
152 
153  if( !fn.FileExists() && !leg_fn.FileExists() )
154  {
155  wxFile file( fn.GetFullPath(), wxFile::write );
156 
157  if( file.IsOpened() )
158  file.Write( wxT( "(kicad_pcb (version 4) (host kicad \"dummy file\") )\n" ) );
159 
160  // wxFile dtor will close the file
161  }
162 }
163 
164 
165 void KICAD_MANAGER_FRAME::OnLoadProject( wxCommandEvent& event )
166 {
167  wxString default_dir = GetMruPath();
168  wxFileDialog dlg( this, _( "Open Existing Project" ), default_dir, wxEmptyString,
169  ProjectFileWildcard, wxFD_OPEN | wxFD_FILE_MUST_EXIST );
170 
171  if( dlg.ShowModal() == wxID_CANCEL )
172  return;
173 
174  wxFileName pro( dlg.GetPath() );
175  pro.SetExt( ProjectFileExtension ); // enforce extension
176 
177  if( !pro.IsAbsolute() )
178  pro.MakeAbsolute();
179 
180  if( !pro.FileExists() )
181  return;
182 
183  LoadProject( pro );
184 }
185 
186 
187 void KICAD_MANAGER_FRAME::OnNewProject( wxCommandEvent& aEvent )
188 {
189  wxString default_dir = GetMruPath();
190  wxFileDialog dlg( this, _( "Create New Project" ), default_dir, wxEmptyString,
191  ProjectFileWildcard, wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
192 
193  if( dlg.ShowModal() == wxID_CANCEL )
194  return;
195 
196  wxFileName pro( dlg.GetPath() );
197  pro.SetExt( ProjectFileExtension ); // enforce extension
198 
199  if( !pro.IsAbsolute() )
200  pro.MakeAbsolute();
201 
202  // Append a new directory with the same name of the project file.
203  pro.AppendDir( pro.GetName() );
204 
205  // Check if the project directory is empty if it already exists.
206  wxDir directory( pro.GetPath() );
207 
208  if( !pro.DirExists() )
209  {
210  if( !pro.Mkdir() )
211  {
212  wxString msg;
213  msg.Printf( _( "Directory '%s' could not be created.\n\n"
214  "Please make sure you have write permissions and try again." ),
215  pro.GetPath() );
216  DisplayErrorMessage( this, msg );
217  return;
218  }
219  }
220  else if( directory.HasFiles() )
221  {
222  wxString msg = _( "The selected directory is not empty. It is recommended that you "
223  "create projects in their own empty directory.\n\nDo you "
224  "want to continue?" );
225 
226  if( !IsOK( this, msg ) )
227  return;
228  }
229 
230  CreateNewProject( pro );
231  LoadProject( pro );
232 }
233 
234 
236 {
237  wxString default_dir = wxFileName( Prj().GetProjectFullName() ).GetPathWithSep();
238  wxString title = _( "New Project Folder" );
239  wxDirDialog dlg( this, title, default_dir );
240 
241  if( dlg.ShowModal() == wxID_CANCEL )
242  return;
243 
244  // Builds the project .pro filename, from the new project folder name
245  wxFileName fn;
246  fn.AssignDir( dlg.GetPath() );
247  fn.SetName( dlg.GetPath().AfterLast( SEP() ) );
248  fn.SetExt( wxT( "pro" ) );
249 
250  wxChar sep[2] = { SEP(), 0 }; // nul terminated separator wxChar string.
251 
252  ClearMsg();
253 
255 
256  wxFileName templatePath;
257  wxString envStr;
258 
259 #ifndef __WXMAC__
260  wxGetEnv( wxT( "KICAD" ), &envStr );
261 
262  // Add a new tab for system templates
263  if( !envStr.empty() )
264  {
265  // user may or may not have including terminating separator.
266  if( !envStr.EndsWith( sep ) )
267  envStr += sep;
268 
269  templatePath = envStr + wxT( "template" ) + sep;
270  }
271  else
272  {
273  // The standard path should be in the share directory for kicad. As
274  // it is normal on Windows to only have the share directory and not
275  // the kicad sub-directory we fall back to that if the directory
276  // doesn't exist
277  templatePath = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) +
278  sep + wxT( ".." ) + sep + wxT( "share" ) + sep + wxT( "kicad" ) +
279  sep + wxT( "template" ) + sep;
280 
281  if( !wxDirExists( templatePath.GetFullPath() ) )
282  {
283  templatePath = wxPathOnly( wxStandardPaths::Get().GetExecutablePath() ) + sep +
284  wxT( ".." ) + sep + wxT( "share" ) + sep + wxT( "template" ) + sep;
285  }
286  }
287 #else
288  // Use what is provided in the bundle data dir
289  templatePath = GetOSXKicadDataDir() + sep + wxT( "template" );
290 #endif
291 
292  ps->AddTemplatesPage( _( "System Templates" ), templatePath );
293 
294  // Add a new tab for user templates
295  wxFileName userPath = wxStandardPaths::Get().GetDocumentsDir() + sep + wxT( "kicad" ) +
296  sep + wxT( "template" ) + sep;
297 
298  ps->AddTemplatesPage( _( "User Templates" ), userPath );
299 
300  // Check to see if a custom template location is available and setup a
301  // new selection tab if there is.
302  envStr.clear();
303  wxGetEnv( wxT( "KICAD_PTEMPLATES" ), &envStr );
304 
305  if( !envStr.empty() )
306  {
307  if( !envStr.EndsWith( sep ) )
308  envStr += sep;
309 
310  wxFileName envPath = envStr;
311 
312  ps->AddTemplatesPage( _( "Portable Templates" ), envPath );
313  }
314 
315  // Show the project template selector dialog
316  if( ps->ShowModal() != wxID_OK )
317  return;
318 
319  if( ps->GetSelectedTemplate() == NULL )
320  {
321  wxMessageBox( _( "No project template was selected. Cannot generate new project." ),
322  _( "Error" ),
323  wxOK | wxICON_ERROR,
324  this );
325 
326  return;
327  }
328 
329  // Make sure the user has write permissions to the base path.
330  wxFileName prjPath = fn;
331 
332  while( !prjPath.DirExists() )
333  prjPath.RemoveLastDir();
334 
335  if( !prjPath.IsDirWritable() )
336  {
337  wxString msg;
338 
339  msg.Printf( _( "Cannot write to folder '%s'." ), prjPath.GetPath() );
340  wxMessageDialog msgDlg( this, msg, _( "Error!" ), wxICON_ERROR | wxOK | wxCENTER );
341  msgDlg.SetExtendedMessage( _( "Plese check your access permissions to this folder "
342  "and try again." ) );
343  msgDlg.ShowModal();
344  return;
345  }
346 
347  // Make sure we are not overwriting anything in the destination folder.
348  std::vector< wxFileName > destFiles;
349 
350  if( ps->GetSelectedTemplate()->GetDestinationFiles( fn, destFiles ) )
351  {
352  std::vector< wxFileName > overwrittenFiles;
353 
354  for( auto file : destFiles )
355  {
356  if( file.FileExists() )
357  overwrittenFiles.push_back( file );
358  }
359 
360  if( !overwrittenFiles.empty() )
361  {
362  wxString extendedMsg = _( "Overwriting files:" ) + "\n";
363 
364  for( auto file : overwrittenFiles )
365  {
366  extendedMsg += "\n" + file.GetFullName();
367  }
368 
369  wxMessageDialog owDlg( this,
370  _( "Are you sure you want to overwrite files in "
371  "the destination folder?" ),
372  _( "Warning!" ),
373  wxYES_NO | wxICON_QUESTION | wxCENTER );
374  owDlg.SetExtendedMessage( extendedMsg );
375  owDlg.SetYesNoLabels( _( "Overwrite" ), _( "Do Not Overwrite" ) );
376 
377  if( owDlg.ShowModal() == wxID_NO )
378  return;
379  }
380  }
381 
382  wxString errorMsg;
383 
384  // The selected template widget contains the template we're attempting to use to
385  // create a project
386  if( !ps->GetSelectedTemplate()->CreateProject( fn, &errorMsg ) )
387  {
388  wxMessageDialog createDlg( this,
389  _( "A problem occurred creating new project from template!" ),
390  _( "Template Error" ),
391  wxOK | wxICON_ERROR );
392 
393  if( !errorMsg.empty() )
394  createDlg.SetExtendedMessage( errorMsg );
395 
396  createDlg.ShowModal();
397  return;
398  }
399 
400  CreateNewProject( fn.GetFullPath() );
401  LoadProject( fn );
402 }
403 
404 
405 void KICAD_MANAGER_FRAME::OnSaveProject( wxCommandEvent& event )
406 {
407  if( !wxIsWritable( GetProjectFileName() ) )
408  return;
409 
410  Prj().ConfigSave( PgmTop().SysSearch(), GeneralGroupName, s_KicadManagerParams );
411 }
412 
413 
414 void KICAD_MANAGER_FRAME::OnUpdateRequiresProject( wxUpdateUIEvent& event )
415 {
416  event.Enable( m_active_project );
417 }
A list of parameters type.
VTBL_ENTRY bool PlayersClose(bool doForce)
Function PlayersClose calls the KIWAY_PLAYER::Close( bool force ) function on all the windows and if ...
Definition: kiway.cpp:374
VTBL_ENTRY void ConfigSave(const SEARCH_STACK &aSList, const wxString &aGroupName, const PARAM_CFG_ARRAY &aParams, const wxString &aFileName=wxEmptyString)
Function ConfigSave saves the current "project" parameters into the wxConfigBase* derivative...
Definition: project.cpp:307
void OnNewProject(wxCommandEvent &aEvent)
Definition: prjconfig.cpp:187
void SetMruPath(const wxString &aPath)
Definition: wxstruct.h:361
PARAM_CFG_ARRAY s_KicadManagerParams
Definition: prjconfig.cpp:58
This file is part of the common library.
const wxString ProjectFileExtension
PROJECT_TEMPLATE * GetSelectedTemplate()
PROJECT & Prj()
Definition: kicad.cpp:270
const wxString ProjectFileWildcard
#define SEP()
Definition: prjconfig.cpp:50
The common library.
void OnLoadProject(wxCommandEvent &event)
Load an exiting project (.pro) file.
Definition: prjconfig.cpp:165
void UpdateFileHistory(const wxString &FullFileName, wxFileHistory *aFileHistory=NULL)
Function UpdateFileHistory Updates the list of recently opened files.
Definition: basicframe.cpp:388
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString aExtraInfo)
Function DisplayErrorMessage displays an error message with aMessage.
Definition: confirm.cpp:85
void OnUpdateRequiresProject(wxUpdateUIEvent &event)
Definition: prjconfig.cpp:414
wxString GetBuildVersion()
Function GetBuildVersion Return the build version string.
KICAD_MANAGER_FRAME is the KiCad main frame.
The common library.
void OnCreateProjectFromTemplate(wxCommandEvent &event)
Creates a new project folder, copy a template into this new folder.
Definition: prjconfig.cpp:235
void ReCreateTreePrj()
Create or modify the tree showing project file names.
PGM_KICAD & PgmTop()
Definition: kicad.cpp:71
#define GeneralGroupName
Definition: prjconfig.cpp:56
const wxString SchematicFileExtension
const wxString GetProjectFileName()
Definition: mainframe.cpp:147
void SetProjectFileName(const wxString &aFullProjectProFileName)
Definition: mainframe.cpp:135
size_t GetDestinationFiles(const wxFileName &aNewProjectPath, std::vector< wxFileName > &aDestFiles)
Fetch the list of destination files to be copied when the new project is created. ...
bool CreateProject(wxFileName &aNewProjectPath, wxString *aErrorMsg=nullptr)
Copies and renames all template files to create a new project.
const wxString LegacyPcbFileExtension
TREE_PROJECT_FRAME * m_LeftWin
Definition: kicad.h:298
const wxString KiCadPcbFileExtension
void AddTemplatesPage(const wxString &aTitle, wxFileName &aPath)
Add a new page with aTitle, populated with templates from aPath.
VTBL_ENTRY bool ConfigLoad(const SEARCH_STACK &aSearchS, const wxString &aGroupName, const PARAM_CFG_ARRAY &aParams, const wxString &aForeignConfigFileName=wxEmptyString)
Function ConfigLoad reads a subset of parameters from the "project" file.
Definition: project.cpp:342
void LoadProject(const wxFileName &aProjectFileName)
Definition: prjconfig.cpp:61
bool m_active_project
Definition: kicad.h:308
wxString FindValidPath(const wxString &aFileName) const
Definition: search_stack.h:71
void CreateNewProject(const wxFileName &aProjectFileName)
Creates a new project by setting up and initial project, schematic, and board files.
Definition: prjconfig.cpp:108
wxFileHistory & GetFileHistory()
Definition: pgm_kicad.h:57
wxString GetMruPath() const
Definition: wxstruct.h:363
const SEARCH_STACK & sys_search() override
Function sys_search returns a SEARCH_STACK pertaining to entire program, and is overloaded in KICAD_M...
Definition: mainframe.cpp:189
void ClearMsg()
Erase the text panel.
Definition: mainframe.cpp:528
void PrintPrjInfo()
Prints the current working directory name and the projet name on the text panel.
Definition: mainframe.cpp:548
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Function IsOK displays a yes/no dialog with aMessage and returns the user response.
Definition: confirm.cpp:129
void OnSaveProject(wxCommandEvent &event)
Save the project (.pro) file containing the top level configuration parameters.
Definition: prjconfig.cpp:405
KIWAY Kiway