KiCad PCB EDA Suite
gen_footprints_placefile.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) 2015-2020 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 /*
25  * 1 - create ascii files for automatic placement of smd components
26  * 2 - create a footprint report (pos and footprint descr) (ascii file)
27  */
28 
29 #include <confirm.h>
30 #include <kicad_string.h>
31 #include <gestfich.h>
32 #include <pcb_edit_frame.h>
33 #include <pcbnew_settings.h>
34 #include <bitmaps.h>
35 #include <reporter.h>
37 #include <board.h>
38 #include <footprint.h>
40 #include <kiface_i.h>
41 #include <wx_html_report_panel.h>
45 
46 #include <wx/dirdlg.h>
47 
48 
54 {
55 public:
58  m_parent( aParent ),
59  m_plotOpts( aParent->GetPlotSettings() )
60  {
61  m_messagesPanel->SetFileName( Prj().GetProjectPath() + wxT( "report.txt" ) );
63  initDialog();
64 
65  // We use a sdbSizer to get platform-dependent ordering of the action buttons, but
66  // that requires us to correct the button labels here.
67  m_sdbSizerOK->SetLabel( _( "Generate Position File" ) );
68  m_sdbSizerCancel->SetLabel( _( "Close" ) );
69  m_sdbSizer->Layout();
70 
71  m_sdbSizerOK->SetDefault();
72 
73  GetSizer()->SetSizeHints(this);
74  Centre();
75  }
76 
77 private:
81 
82  static int m_unitsOpt;
83  static int m_fileOpt;
84  static int m_fileFormat;
85  static bool m_includeBoardEdge;
86 
87  void initDialog();
88  void OnOutputDirectoryBrowseClicked( wxCommandEvent& event ) override;
89  void OnGenerate( wxCommandEvent& event ) override;
90 
91  void onUpdateUIUnits( wxUpdateUIEvent& event ) override
92  {
93  m_radioBoxUnits->Enable( m_rbFormat->GetSelection() != 2 );
94  }
95 
96  void onUpdateUIFileOpt( wxUpdateUIEvent& event ) override
97  {
98  m_radioBoxFilesCount->Enable( m_rbFormat->GetSelection() != 2 );
99  }
100 
101  void onUpdateUIExcludeTH( wxUpdateUIEvent& event ) override
102  {
103  if( m_rbFormat->GetSelection() == 2 )
104  {
105  m_excludeTH->SetValue( false );
106  m_excludeTH->Enable( false );
107  }
108  else
109  {
110  m_excludeTH->Enable( true );
111  }
112  }
113 
114  void onUpdateUIincludeBoardEdge( wxUpdateUIEvent& event ) override
115  {
116  m_cbIncludeBoardEdge->Enable( m_rbFormat->GetSelection() == 2 );
117  }
118 
121  bool CreateAsciiFiles();
122 
125  bool CreateGerberFiles();
126 
127  // accessors to options:
128  bool UnitsMM()
129  {
130  return m_radioBoxUnits->GetSelection() == 1;
131  }
132 
133  bool OneFileOnly()
134  {
135  return m_radioBoxFilesCount->GetSelection() == 1;
136  }
137 
139  {
140  return m_excludeTH->GetValue();
141  }
142 };
143 
144 
145 // Static members to remember choices
149 
150 
151 
153 {
155 
156  auto cfg = m_parent->GetPcbNewSettings();
157 
158  m_units = cfg->m_PlaceFile.units == 0 ? EDA_UNITS::INCHES : EDA_UNITS::MILLIMETRES;
159  m_fileOpt = cfg->m_PlaceFile.file_options;
160  m_fileFormat = cfg->m_PlaceFile.file_format;
161  m_includeBoardEdge = cfg->m_PlaceFile.include_board_edge;
162 
163  // Output directory
165 
166  // Update Options
167  m_radioBoxUnits->SetSelection( cfg->m_PlaceFile.units );
168  m_radioBoxFilesCount->SetSelection( m_fileOpt );
169  m_rbFormat->SetSelection( m_fileFormat );
171 
172 
173  // Update sizes and sizers:
174  m_messagesPanel->MsgPanelSetMinSize( wxSize( -1, 160 ) );
175  GetSizer()->SetSizeHints( this );
176 }
177 
179 {
180  // Build the absolute path of current output directory to preselect it in the file browser.
181  wxString path = ExpandEnvVarSubstitutions( m_outputDirectoryName->GetValue(), &Prj() );
182  path = Prj().AbsolutePath( path );
183 
184  wxDirDialog dirDialog( this, _( "Select Output Directory" ), path );
185 
186  if( dirDialog.ShowModal() == wxID_CANCEL )
187  return;
188 
189  wxFileName dirName = wxFileName::DirName( dirDialog.GetPath() );
190 
191  wxMessageDialog dialog( this, _( "Use a relative path?"),
192  _( "Plot Output Directory" ),
193  wxYES_NO | wxICON_QUESTION | wxYES_DEFAULT );
194 
195  if( dialog.ShowModal() == wxID_YES )
196  {
197  wxString boardFilePath = ( (wxFileName) m_parent->GetBoard()->GetFileName() ).GetPath();
198 
199  if( !dirName.MakeRelativeTo( boardFilePath ) )
200  wxMessageBox( _( "Cannot make path relative (target volume different from board file volume)!" ),
201  _( "Plot Output Directory" ), wxOK | wxICON_ERROR );
202  }
203 
204  m_outputDirectoryName->SetValue( dirName.GetFullPath() );
205 }
206 
207 void DIALOG_GEN_FOOTPRINT_POSITION::OnGenerate( wxCommandEvent& event )
208 {
209  m_fileOpt = m_radioBoxFilesCount->GetSelection();
210  m_fileFormat = m_rbFormat->GetSelection();
212 
213  auto cfg = m_parent->GetPcbNewSettings();
215 
216  cfg->m_PlaceFile.units = m_units == EDA_UNITS::INCHES ? 0 : 1;
217  cfg->m_PlaceFile.file_options = m_fileOpt;
218  cfg->m_PlaceFile.file_format = m_fileFormat;
219  cfg->m_PlaceFile.include_board_edge = m_includeBoardEdge;
220 
221  // Set output directory and replace backslashes with forward ones
222  // (Keep unix convention in cfg files)
223  wxString dirStr;
224  dirStr = m_outputDirectoryName->GetValue();
225  dirStr.Replace( wxT( "\\" ), wxT( "/" ) );
226 
227  m_plotOpts.SetOutputDirectory( dirStr );
229 
230  if( m_fileFormat == 2 )
232  else
234 }
235 
237 {
238  BOARD* brd = m_parent->GetBoard();
239  wxFileName fn;
240  wxString msg;
241  int fullcount = 0;
242 
243  // Create output directory if it does not exist. Also transform it in absolute path.
244  // Bail if it fails
246  wxFileName outputDir = wxFileName::DirName( path );
247  wxString boardFilename = m_parent->GetBoard()->GetFileName();
248 
250 
251  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, m_reporter ) )
252  {
253  msg.Printf( _( "Could not write plot files to folder '%s'." ),
254  outputDir.GetPath() );
255  DisplayError( this, msg );
256  return false;
257  }
258 
259  fn = m_parent->GetBoard()->GetFileName();
260  fn.SetPath( outputDir.GetPath() );
261 
262  // Create the Front and Top side placement files. Gerber P&P files are always separated.
263  // Not also they include all footprints
264  PLACEFILE_GERBER_WRITER exporter( brd );
265  wxString filename = exporter.GetPlaceFileName( fn.GetFullPath(), F_Cu );
266 
267  int fpcount = exporter.CreatePlaceFile( filename, F_Cu, m_includeBoardEdge );
268 
269  if( fpcount < 0 )
270  {
271  msg.Printf( _( "Unable to create '%s'." ), fn.GetFullPath() );
272  wxMessageBox( msg );
274  return false;
275  }
276 
277  msg.Printf( _( "Front (top side) placement file: '%s'." ), filename );
279 
280  msg.Printf( _( "Component count: %d." ), fpcount );
282 
283  // Create the Back or Bottom side placement file
284  fullcount = fpcount;
285 
286  filename = exporter.GetPlaceFileName( fn.GetFullPath(), B_Cu );
287 
288  fpcount = exporter.CreatePlaceFile( filename, B_Cu, m_includeBoardEdge );
289 
290  if( fpcount < 0 )
291  {
292  msg.Printf( _( "Unable to create file '%s'." ), filename );
294  wxMessageBox( msg );
295  return false;
296  }
297 
298  // Display results
299  msg.Printf( _( "Back (bottom side) placement file: '%s'." ), filename );
301 
302  msg.Printf( _( "Component count: %d." ), fpcount );
303 
305 
306  fullcount += fpcount;
307  msg.Printf( _( "Full component count: %d.\n" ), fullcount );
309 
310  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_ACTION );
311 
312  return true;
313 }
314 
315 
317 {
318  BOARD * brd = m_parent->GetBoard();
319  wxFileName fn;
320  wxString msg;
321  bool singleFile = OneFileOnly();
322  bool useCSVfmt = m_fileFormat == 1;
323  int fullcount = 0;
324  int top_side = true;
325  int bottom_side = true;
326 
327  // Test for any footprint candidate in list.
328  {
329  PLACE_FILE_EXPORTER exporter( brd, UnitsMM(), ExcludeAllTH(), top_side, bottom_side,
330  useCSVfmt );
331  exporter.GenPositionData();
332 
333  if( exporter.GetFootprintCount() == 0 )
334  {
335  wxMessageBox( _( "No footprint for automated placement." ) );
336  return false;
337  }
338  }
339 
340  // Create output directory if it does not exist.
341  // Also transform it in absolute path.
342  // Bail if it fails
344  wxFileName outputDir = wxFileName::DirName( path );
345  wxString boardFilename = m_parent->GetBoard()->GetFileName();
346 
348 
349  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, m_reporter ) )
350  {
351  msg.Printf( _( "Could not write plot files to folder '%s'." ), outputDir.GetPath() );
352  DisplayError( this, msg );
353  return false;
354  }
355 
356  fn = m_parent->GetBoard()->GetFileName();
357  fn.SetPath( outputDir.GetPath() );
358 
359  // Create the Front or Top side placement file, or a single file
360  top_side = true;
361  bottom_side = false;
362 
363  if( singleFile )
364  {
365  bottom_side = true;
366  fn.SetName( fn.GetName() + wxT( "-" ) + wxT("all") );
367  }
368  else
369  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetFrontSideName().c_str() );
370 
371 
372  if( useCSVfmt )
373  {
374  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
375  fn.SetExt( wxT( "csv" ) );
376  }
377  else
378  fn.SetExt( FootprintPlaceFileExtension );
379 
380  int fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(),
381  ExcludeAllTH(), top_side, bottom_side,
382  useCSVfmt );
383  if( fpcount < 0 )
384  {
385  msg.Printf( _( "Unable to create '%s'." ), fn.GetFullPath() );
386  wxMessageBox( msg );
388  return false;
389  }
390 
391  if( singleFile )
392  msg.Printf( _( "Placement file: '%s'." ), fn.GetFullPath() );
393  else
394  msg.Printf( _( "Front (top side) placement file: '%s'." ),
395  fn.GetFullPath() );
397 
398  msg.Printf( _( "Component count: %d." ), fpcount );
400 
401  if( singleFile )
402  {
403  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_ACTION );
404  return true;
405  }
406 
407  // Create the Back or Bottom side placement file
408  fullcount = fpcount;
409  top_side = false;
410  bottom_side = true;
411  fn = brd->GetFileName();
412  fn.SetPath( outputDir.GetPath() );
413  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetBackSideName().c_str() );
414 
415  if( useCSVfmt )
416  {
417  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
418  fn.SetExt( wxT( "csv" ) );
419  }
420  else
421  fn.SetExt( FootprintPlaceFileExtension );
422 
423  fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(), ExcludeAllTH(),
424  top_side, bottom_side, useCSVfmt );
425 
426  if( fpcount < 0 )
427  {
428  msg.Printf( _( "Unable to create file '%s'." ), fn.GetFullPath() );
430  wxMessageBox( msg );
431  return false;
432  }
433 
434  // Display results
435  if( !singleFile )
436  {
437  msg.Printf( _( "Back (bottom side) placement file: '%s'." ), fn.GetFullPath() );
439 
440  msg.Printf( _( "Component count: %d." ), fpcount );
441 
443  }
444 
445  if( !singleFile )
446  {
447  fullcount += fpcount;
448  msg.Printf( _( "Full component count: %d.\n" ), fullcount );
450  }
451 
452  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_ACTION );
453 
454  return true;
455 }
456 
457 
459 {
460  PCB_EDIT_FRAME* editFrame = getEditFrame<PCB_EDIT_FRAME>();
461  DIALOG_GEN_FOOTPRINT_POSITION dlg( editFrame );
462 
463  dlg.ShowModal();
464  return 0;
465 }
466 
467 
468 int PCB_EDIT_FRAME::DoGenFootprintsPositionFile( const wxString& aFullFileName, bool aUnitsMM,
469  bool aForceSmdItems, bool aTopSide,
470  bool aBottomSide, bool aFormatCSV )
471 {
472  FILE * file = NULL;
473 
474  if( !aFullFileName.IsEmpty() )
475  {
476  file = wxFopen( aFullFileName, wxT( "wt" ) );
477 
478  if( file == NULL )
479  return -1;
480  }
481 
482  std::string data;
483  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, aForceSmdItems, aTopSide, aBottomSide,
484  aFormatCSV );
485  data = exporter.GenPositionData();
486 
487  // if aFullFileName is empty, the file is not created, only the
488  // count of footprints to place is returned
489  if( file )
490  {
491  // Creates a footprint position file
492  // aSide = 0 -> Back (bottom) side)
493  // aSide = 1 -> Front (top) side)
494  // aSide = 2 -> both sides
495  fputs( data.c_str(), file );
496  fclose( file );
497  }
498 
499  return exporter.GetFootprintCount();
500 }
501 
502 
503 void PCB_EDIT_FRAME::GenFootprintsReport( wxCommandEvent& event )
504 {
505  wxFileName fn;
506 
507  wxString boardFilePath = ( (wxFileName) GetBoard()->GetFileName() ).GetPath();
508  wxDirDialog dirDialog( this, _( "Select Output Directory" ), boardFilePath );
509 
510  if( dirDialog.ShowModal() == wxID_CANCEL )
511  return;
512 
513  fn = GetBoard()->GetFileName();
514  fn.SetPath( dirDialog.GetPath() );
515  fn.SetExt( wxT( "rpt" ) );
516 
517  bool unitMM = GetUserUnits() == EDA_UNITS::MILLIMETRES;
518  bool success = DoGenFootprintsReport( fn.GetFullPath(), unitMM );
519 
520  wxString msg;
521  if( success )
522  {
523  msg.Printf( _( "Footprint report file created:\n'%s'." ), fn.GetFullPath() );
524  wxMessageBox( msg, _( "Footprint Report" ), wxICON_INFORMATION );
525  }
526 
527  else
528  {
529  msg.Printf( _( "Unable to create '%s'." ), fn.GetFullPath() );
530  DisplayError( this, msg );
531  }
532 }
533 
534 /* Print a footprint report.
535  */
536 bool PCB_EDIT_FRAME::DoGenFootprintsReport( const wxString& aFullFilename, bool aUnitsMM )
537 {
538  FILE* rptfile = wxFopen( aFullFilename, wxT( "wt" ) );
539 
540  if( rptfile == NULL )
541  return false;
542 
543  std::string data;
544  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, false, true, true, false );
545  data = exporter.GenReportData();
546 
547  fputs( data.c_str(), rptfile );
548  fclose( rptfile );
549 
550  return true;
551 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:252
std::string GenPositionData()
build a string filled with the position data
Classes used in place file generation.
int CreatePlaceFile(wxString &aFullFilename, PCB_LAYER_ID aLayer, bool aIncludeBrdEdges)
Create an pnp gerber file.
This file is part of the common library TODO brief description.
This file is part of the common library.
void OnOutputDirectoryBrowseClicked(wxCommandEvent &event) override
void onUpdateUIUnits(wxUpdateUIEvent &event) override
int GeneratePosFile(const TOOL_EVENT &aEvent)
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:279
A pure virtual class used to derive REPORTER objects from.
Definition: reporter.h:64
Class DIALOG_GEN_FOOTPRINT_POSITION_BASE.
const wxString & GetFileName() const
Definition: board.h:228
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Report a string with a given severity.
bool CreateAsciiFiles()
Creates files in text or csv format.
void onUpdateUIincludeBoardEdge(wxUpdateUIEvent &event) override
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:271
bool DoGenFootprintsReport(const wxString &aFullFilename, bool aUnitsMM)
Create an ASCII footprint report file giving some infos on footprints and board outlines.
void GenFootprintsReport(wxCommandEvent &event)
Call DoGenFootprintsReport to create a footprint report file.
DIALOG_GEN_FOOTPRINT_POSITION(PCB_EDIT_FRAME *aParent)
bool CreateGerberFiles()
Creates placement files in gerber format.
#define NULL
void onUpdateUIFileOpt(wxUpdateUIEvent &event) override
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
bool EnsureFileDirectoryExists(wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter)
Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist.
Definition: common.cpp:307
Generic, UI-independent tool event.
Definition: tool_event.h:152
Definition of file extensions used in Kicad.
#define _(s)
virtual void SetPlotSettings(const PCB_PLOT_PARAMS &aSettings)
void SetOutputDirectory(wxString aDir)
The ASCII format of the kicad place file is:
std::string GenReportData()
build a string filled with the pad report data This report does not used options aForceSmdItems,...
wxBitmap KiBitmap(BITMAPS aBitmap, int aHeightTag)
Construct a wxBitmap from an image identifier Returns the image from the active theme if the image ha...
Definition: bitmap.cpp:105
Parameters and options when plotting/printing a board.
void onUpdateUIExcludeTH(wxUpdateUIEvent &event) override
wxString GetOutputDirectory() const
EDA_UNITS m_units
Definition: dialog_shim.h:198
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
The main frame for Pcbnew.
PCBNEW_SETTINGS * GetPcbNewSettings() const
void MsgPanelSetMinSize(const wxSize &aMinSize)
returns the reporter object that reports to this panel
const std::string FootprintPlaceFileExtension
BOARD * GetBoard() const
int DoGenFootprintsPositionFile(const wxString &aFullFileName, bool aUnitsMM, bool aForceSmdItems, bool aTopSide, bool aBottomSide, bool aFormatCSV=false)
Create an ASCII footprint position file.
void SetFileName(const wxString &aReportFileName)
PLACEFILE_GERBER_WRITER is a class mainly used to create Gerber drill files.
The dialog to create footprint position files and choose options (one or 2 files, units and force all...
static std::string GetBackSideName()
static std::string GetFrontSideName()
EDA_UNITS GetUserUnits() const
Return the user units currently in use.
void OnGenerate(wxCommandEvent &event) override