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-2021 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 <string_utils.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_base.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:
78  void initDialog();
79  void OnOutputDirectoryBrowseClicked( wxCommandEvent& event ) override;
80  void OnGenerate( wxCommandEvent& event ) override;
81 
82  void onUpdateUIUnits( wxUpdateUIEvent& event ) override
83  {
84  m_radioBoxUnits->Enable( m_rbFormat->GetSelection() != 2 );
85  }
86 
87  void onUpdateUIFileOpt( wxUpdateUIEvent& event ) override
88  {
89  m_radioBoxFilesCount->Enable( m_rbFormat->GetSelection() != 2 );
90  }
91 
92  void onUpdateUIOnlySMD( wxUpdateUIEvent& event ) override
93  {
94  if( m_rbFormat->GetSelection() == 2 )
95  {
96  m_onlySMD->SetValue( false );
97  m_onlySMD->Enable( false );
98  }
99  else
100  {
101  m_onlySMD->Enable( true );
102  }
103  }
104 
105  void onUpdateUIExcludeTH( wxUpdateUIEvent& event ) override
106  {
107  if( m_rbFormat->GetSelection() == 2 )
108  {
109  m_excludeTH->SetValue( false );
110  m_excludeTH->Enable( false );
111  }
112  else
113  {
114  m_excludeTH->Enable( true );
115  }
116  }
117 
118  void onUpdateUIincludeBoardEdge( wxUpdateUIEvent& event ) override
119  {
120  m_cbIncludeBoardEdge->Enable( m_rbFormat->GetSelection() == 2 );
121  }
122 
126  bool CreateAsciiFiles();
127 
131  bool CreateGerberFiles();
132 
133  // accessors to options:
134  bool UnitsMM()
135  {
136  return m_radioBoxUnits->GetSelection() == 1;
137  }
138 
139  bool OneFileOnly()
140  {
141  return m_radioBoxFilesCount->GetSelection() == 1;
142  }
143 
144  bool OnlySMD()
145  {
146  return m_onlySMD->GetValue();
147  }
148 
150  {
151  return m_excludeTH->GetValue();
152  }
153 
157 
158  static int m_unitsOpt;
159  static int m_fileOpt;
160  static int m_fileFormat;
161  static bool m_includeBoardEdge;
162  static bool m_excludeTHOpt;
163  static bool m_onlySMDOpt;
164 };
165 
166 
167 // Static members to remember choices
173 
174 
176 {
178 
180 
185 
186  // Output directory
188 
189  // Update Options
190  m_radioBoxUnits->SetSelection( cfg->m_PlaceFile.units );
191  m_radioBoxFilesCount->SetSelection( m_fileOpt );
192  m_rbFormat->SetSelection( m_fileFormat );
195  m_onlySMD->SetValue( m_onlySMDOpt );
196  m_excludeTH->SetValue( m_excludeTHOpt );
197 
198  // Update sizes and sizers:
199  m_messagesPanel->MsgPanelSetMinSize( wxSize( -1, 160 ) );
200  GetSizer()->SetSizeHints( this );
201 }
202 
204 {
205  // Build the absolute path of current output directory to preselect it in the file browser.
206  wxString path = ExpandEnvVarSubstitutions( m_outputDirectoryName->GetValue(), &Prj() );
207  path = Prj().AbsolutePath( path );
208 
209  wxDirDialog dirDialog( this, _( "Select Output Directory" ), path );
210 
211  if( dirDialog.ShowModal() == wxID_CANCEL )
212  return;
213 
214  wxFileName dirName = wxFileName::DirName( dirDialog.GetPath() );
215 
216  wxMessageDialog dialog( this, _( "Use a relative path?"),
217  _( "Plot Output Directory" ),
218  wxYES_NO | wxICON_QUESTION | wxYES_DEFAULT );
219 
220  if( dialog.ShowModal() == wxID_YES )
221  {
222  wxString boardFilePath = ( (wxFileName) m_parent->GetBoard()->GetFileName() ).GetPath();
223 
224  if( !dirName.MakeRelativeTo( boardFilePath ) )
225  wxMessageBox( _( "Cannot make path relative (target volume different from board "
226  "file volume)!" ),
227  _( "Plot Output Directory" ), wxOK | wxICON_ERROR );
228  }
229 
230  m_outputDirectoryName->SetValue( dirName.GetFullPath() );
231 }
232 
233 
234 void DIALOG_GEN_FOOTPRINT_POSITION::OnGenerate( wxCommandEvent& event )
235 {
236  m_fileOpt = m_radioBoxFilesCount->GetSelection();
237  m_fileFormat = m_rbFormat->GetSelection();
239  m_onlySMDOpt = m_onlySMD->GetValue();
240  m_excludeTHOpt = m_excludeTH->GetValue();
241 
242  auto cfg = m_parent->GetPcbNewSettings();
244 
245  cfg->m_PlaceFile.units = m_units == EDA_UNITS::INCHES ? 0 : 1;
246  cfg->m_PlaceFile.file_options = m_fileOpt;
247  cfg->m_PlaceFile.file_format = m_fileFormat;
248  cfg->m_PlaceFile.include_board_edge = m_includeBoardEdge;
249  cfg->m_PlaceFile.use_aux_origin = m_useDrillPlaceOrigin->GetValue();
250 
251  // Set output directory and replace backslashes with forward ones
252  // (Keep unix convention in cfg files)
253  wxString dirStr;
254  dirStr = m_outputDirectoryName->GetValue();
255  dirStr.Replace( wxT( "\\" ), wxT( "/" ) );
256 
257  m_plotOpts.SetOutputDirectory( dirStr );
259 
260  if( m_fileFormat == 2 )
262  else
264 }
265 
266 
268 {
269  BOARD* brd = m_parent->GetBoard();
270  wxFileName fn;
271  wxString msg;
272  int fullcount = 0;
273 
274  // Create output directory if it does not exist. Also transform it in absolute path.
275  // Bail if it fails
277  wxFileName outputDir = wxFileName::DirName( path );
278  wxString boardFilename = m_parent->GetBoard()->GetFileName();
279 
281 
282  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, m_reporter ) )
283  {
284  msg.Printf( _( "Could not write plot files to folder '%s'." ),
285  outputDir.GetPath() );
286  DisplayError( this, msg );
287  return false;
288  }
289 
290  fn = m_parent->GetBoard()->GetFileName();
291  fn.SetPath( outputDir.GetPath() );
292 
293  // Create the Front and Top side placement files. Gerber P&P files are always separated.
294  // Not also they include all footprints
295  PLACEFILE_GERBER_WRITER exporter( brd );
296  wxString filename = exporter.GetPlaceFileName( fn.GetFullPath(), F_Cu );
297 
298  int fpcount = exporter.CreatePlaceFile( filename, F_Cu, m_includeBoardEdge );
299 
300  if( fpcount < 0 )
301  {
302  msg.Printf( _( "Failed to create file '%s'." ), fn.GetFullPath() );
303  wxMessageBox( msg );
305  return false;
306  }
307 
308  msg.Printf( _( "Front (top side) placement file: '%s'." ), filename );
310 
311  msg.Printf( _( "Component count: %d." ), fpcount );
313 
314  // Create the Back or Bottom side placement file
315  fullcount = fpcount;
316 
317  filename = exporter.GetPlaceFileName( fn.GetFullPath(), B_Cu );
318 
319  fpcount = exporter.CreatePlaceFile( filename, B_Cu, m_includeBoardEdge );
320 
321  if( fpcount < 0 )
322  {
323  msg.Printf( _( "Failed to create file '%s'." ), filename );
325  wxMessageBox( msg );
326  return false;
327  }
328 
329  // Display results
330  msg.Printf( _( "Back (bottom side) placement file: '%s'." ), filename );
332 
333  msg.Printf( _( "Component count: %d." ), fpcount );
335 
336  fullcount += fpcount;
337  msg.Printf( _( "Full component count: %d." ), fullcount );
339 
340  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_INFO );
341 
342  return true;
343 }
344 
345 
347 {
348  BOARD * brd = m_parent->GetBoard();
349  wxFileName fn;
350  wxString msg;
351  bool singleFile = OneFileOnly();
352  bool useCSVfmt = m_fileFormat == 1;
353  bool useAuxOrigin = m_useDrillPlaceOrigin->GetValue();
354  int fullcount = 0;
355  int topSide = true;
356  int bottomSide = true;
357 
358  // Test for any footprint candidate in list.
359  {
360  PLACE_FILE_EXPORTER exporter( brd, UnitsMM(), OnlySMD(), ExcludeAllTH(), topSide,
361  bottomSide, useCSVfmt, useAuxOrigin );
362  exporter.GenPositionData();
363 
364  if( exporter.GetFootprintCount() == 0 )
365  {
366  wxMessageBox( _( "No footprint for automated placement." ) );
367  return false;
368  }
369  }
370 
371  // Create output directory if it does not exist.
372  // Also transform it in absolute path.
373  // Bail if it fails
375  wxFileName outputDir = wxFileName::DirName( path );
376  wxString boardFilename = m_parent->GetBoard()->GetFileName();
377 
379 
380  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, m_reporter ) )
381  {
382  msg.Printf( _( "Could not write plot files to folder '%s'." ), outputDir.GetPath() );
383  DisplayError( this, msg );
384  return false;
385  }
386 
387  fn = m_parent->GetBoard()->GetFileName();
388  fn.SetPath( outputDir.GetPath() );
389 
390  // Create the Front or Top side placement file, or a single file
391  topSide = true;
392  bottomSide = false;
393 
394  if( singleFile )
395  {
396  bottomSide = true;
397  fn.SetName( fn.GetName() + wxT( "-" ) + wxT( "all" ) );
398  }
399  else
400  {
401  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetFrontSideName().c_str() );
402  }
403 
404 
405  if( useCSVfmt )
406  {
407  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
408  fn.SetExt( wxT( "csv" ) );
409  }
410  else
411  {
412  fn.SetExt( FootprintPlaceFileExtension );
413  }
414 
415  int fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(), OnlySMD(),
416  ExcludeAllTH(), topSide, bottomSide,
417  useCSVfmt, useAuxOrigin );
418  if( fpcount < 0 )
419  {
420  msg.Printf( _( "Failed to create file '%s'." ), fn.GetFullPath() );
421  wxMessageBox( msg );
423  return false;
424  }
425 
426  if( singleFile )
427  msg.Printf( _( "Placement file: '%s'." ), fn.GetFullPath() );
428  else
429  msg.Printf( _( "Front (top side) placement file: '%s'." ), fn.GetFullPath() );
430 
432 
433  msg.Printf( _( "Component count: %d." ), fpcount );
435 
436  if( singleFile )
437  {
438  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_INFO );
439  return true;
440  }
441 
442  // Create the Back or Bottom side placement file
443  fullcount = fpcount;
444  topSide = false;
445  bottomSide = true;
446  fn = brd->GetFileName();
447  fn.SetPath( outputDir.GetPath() );
448  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetBackSideName().c_str() );
449 
450  if( useCSVfmt )
451  {
452  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
453  fn.SetExt( wxT( "csv" ) );
454  }
455  else
456  {
457  fn.SetExt( FootprintPlaceFileExtension );
458  }
459 
460  fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(), OnlySMD(),
461  ExcludeAllTH(), topSide, bottomSide, useCSVfmt,
462  useAuxOrigin );
463 
464  if( fpcount < 0 )
465  {
466  msg.Printf( _( "Failed to create file '%s'." ), fn.GetFullPath() );
468  wxMessageBox( msg );
469  return false;
470  }
471 
472  // Display results
473  if( !singleFile )
474  {
475  msg.Printf( _( "Back (bottom side) placement file: '%s'." ), fn.GetFullPath() );
477 
478  msg.Printf( _( "Component count: %d." ), fpcount );
480  }
481 
482  if( !singleFile )
483  {
484  fullcount += fpcount;
485  msg.Printf( _( "Full component count: %d." ), fullcount );
487  }
488 
489  m_reporter->Report( _( "File generation successful." ), RPT_SEVERITY_INFO );
490 
491  return true;
492 }
493 
494 
496 {
497  PCB_EDIT_FRAME* editFrame = getEditFrame<PCB_EDIT_FRAME>();
498  DIALOG_GEN_FOOTPRINT_POSITION dlg( editFrame );
499 
500  dlg.ShowModal();
501  return 0;
502 }
503 
504 
505 int PCB_EDIT_FRAME::DoGenFootprintsPositionFile( const wxString& aFullFileName, bool aUnitsMM,
506  bool aOnlySMD, bool aNoTHItems, bool aTopSide,
507  bool aBottomSide, bool aFormatCSV,
508  bool aUseAuxOrigin )
509 {
510  FILE * file = nullptr;
511 
512  if( !aFullFileName.IsEmpty() )
513  {
514  file = wxFopen( aFullFileName, wxT( "wt" ) );
515 
516  if( file == nullptr )
517  return -1;
518  }
519 
520  std::string data;
521  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, aOnlySMD, aNoTHItems, aTopSide, aBottomSide,
522  aFormatCSV, aUseAuxOrigin );
523  data = exporter.GenPositionData();
524 
525  // if aFullFileName is empty, the file is not created, only the
526  // count of footprints to place is returned
527  if( file )
528  {
529  // Creates a footprint position file
530  // aSide = 0 -> Back (bottom) side)
531  // aSide = 1 -> Front (top) side)
532  // aSide = 2 -> both sides
533  fputs( data.c_str(), file );
534  fclose( file );
535  }
536 
537  return exporter.GetFootprintCount();
538 }
539 
540 
541 void PCB_EDIT_FRAME::GenFootprintsReport( wxCommandEvent& event )
542 {
543  wxFileName fn;
544 
545  wxString boardFilePath = ( (wxFileName) GetBoard()->GetFileName() ).GetPath();
546  wxDirDialog dirDialog( this, _( "Select Output Directory" ), boardFilePath );
547 
548  if( dirDialog.ShowModal() == wxID_CANCEL )
549  return;
550 
551  fn = GetBoard()->GetFileName();
552  fn.SetPath( dirDialog.GetPath() );
553  fn.SetExt( wxT( "rpt" ) );
554 
555  bool unitMM = GetUserUnits() == EDA_UNITS::MILLIMETRES;
556  bool success = DoGenFootprintsReport( fn.GetFullPath(), unitMM );
557 
558  wxString msg;
559 
560  if( success )
561  {
562  msg.Printf( _( "Footprint report file created:\n'%s'." ), fn.GetFullPath() );
563  wxMessageBox( msg, _( "Footprint Report" ), wxICON_INFORMATION );
564  }
565 
566  else
567  {
568  msg.Printf( _( "Failed to create file '%s'." ), fn.GetFullPath() );
569  DisplayError( this, msg );
570  }
571 }
572 
573 
574 bool PCB_EDIT_FRAME::DoGenFootprintsReport( const wxString& aFullFilename, bool aUnitsMM )
575 {
576  FILE* rptfile = wxFopen( aFullFilename, wxT( "wt" ) );
577 
578  if( rptfile == nullptr )
579  return false;
580 
581  std::string data;
582  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, false, false, true, true, false, true );
583  data = exporter.GenReportData();
584 
585  fputs( data.c_str(), rptfile );
586  fclose( rptfile );
587 
588  return true;
589 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:271
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.
void OnOutputDirectoryBrowseClicked(wxCommandEvent &event) override
void onUpdateUIUnits(wxUpdateUIEvent &event) override
int DoGenFootprintsPositionFile(const wxString &aFullFileName, bool aUnitsMM, bool aOnlySMD, bool aNoTHItems, bool aTopSide, bool aBottomSide, bool aFormatCSV, bool aUseAuxOrigin)
Create an ASCII footprint position file.
void SetOutputDirectory(const wxString &aDir)
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:70
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:269
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.
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)
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
DIALOG_PLACE_FILE m_PlaceFile
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
Information pertinent to a Pcbnew printed circuit board.
Definition: board.h:190
Definition: layer_ids.h:70
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
void SetFileName(const wxString &aReportFileName)
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()
void onUpdateUIOnlySMD(wxUpdateUIEvent &event) override
EDA_UNITS GetUserUnits() const
Return the user units currently in use.
void OnGenerate(wxCommandEvent &event) override