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 module report (pos and module descr) (ascii file)
27  */
28 
29 #include <fctsys.h>
30 #include <confirm.h>
31 #include <kicad_string.h>
32 #include <gestfich.h>
33 #include <pcb_edit_frame.h>
34 #include <pcbnew_settings.h>
35 #include <pgm_base.h>
36 #include <bitmaps.h>
37 #include <macros.h>
38 #include <reporter.h>
40 #include <class_board.h>
41 #include <class_module.h>
43 #include <kiface_i.h>
44 #include <wx_html_report_panel.h>
48 
49 
55 {
56 public:
59  m_parent( aParent ),
60  m_plotOpts( aParent->GetPlotSettings() )
61  {
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
150 
151 
152 
154 {
155  m_browseButton->SetBitmap( KiBitmap( folder_xpm ) );
156 
157  auto cfg = m_parent->GetPcbNewSettings();
158 
159  m_units = static_cast<EDA_UNITS>( cfg->m_PlaceFile.units );
160  m_fileOpt = cfg->m_PlaceFile.file_options;
161  m_fileFormat = cfg->m_PlaceFile.file_format;
162  m_includeBoardEdge = cfg->m_PlaceFile.include_board_edge;
163 
164  // Output directory
166 
167  // Update Options
168  m_radioBoxUnits->SetSelection( m_unitsOpt );
169  m_radioBoxFilesCount->SetSelection( m_fileOpt );
170  m_rbFormat->SetSelection( m_fileFormat );
172 
173 
174  // Update sizes and sizers:
175  m_messagesPanel->MsgPanelSetMinSize( wxSize( -1, 160 ) );
176  GetSizer()->SetSizeHints( this );
177 }
178 
180 {
181  // Build the absolute path of current output directory to preselect it in the file browser.
182  wxString path = ExpandEnvVarSubstitutions( m_outputDirectoryName->GetValue(), &Prj() );
183  path = Prj().AbsolutePath( path );
184 
185  wxDirDialog dirDialog( this, _( "Select Output Directory" ), path );
186 
187  if( dirDialog.ShowModal() == wxID_CANCEL )
188  return;
189 
190  wxFileName dirName = wxFileName::DirName( dirDialog.GetPath() );
191 
192  wxMessageDialog dialog( this, _( "Use a relative path?"),
193  _( "Plot Output Directory" ),
194  wxYES_NO | wxICON_QUESTION | wxYES_DEFAULT );
195 
196  if( dialog.ShowModal() == wxID_YES )
197  {
198  wxString boardFilePath = ( (wxFileName) m_parent->GetBoard()->GetFileName()).GetPath();
199 
200  if( !dirName.MakeRelativeTo( boardFilePath ) )
201  wxMessageBox( _( "Cannot make path relative (target volume different from board file volume)!" ),
202  _( "Plot Output Directory" ), wxOK | wxICON_ERROR );
203  }
204 
205  m_outputDirectoryName->SetValue( dirName.GetFullPath() );
206 }
207 
208 void DIALOG_GEN_FOOTPRINT_POSITION::OnGenerate( wxCommandEvent& event )
209 {
210  m_unitsOpt = m_radioBoxUnits->GetSelection();
211  m_fileOpt = m_radioBoxFilesCount->GetSelection();
212  m_fileFormat = m_rbFormat->GetSelection();
214 
215  auto cfg = m_parent->GetPcbNewSettings();
216 
217  cfg->m_PlaceFile.units = static_cast<int>( m_units );
218  cfg->m_PlaceFile.file_options = m_fileOpt;
219  cfg->m_PlaceFile.file_format = m_fileFormat;
220  cfg->m_PlaceFile.include_board_edge = m_includeBoardEdge;
221 
222  // Set output directory and replace backslashes with forward ones
223  // (Keep unix convention in cfg files)
224  wxString dirStr;
225  dirStr = m_outputDirectoryName->GetValue();
226  dirStr.Replace( wxT( "\\" ), wxT( "/" ) );
227 
228  m_plotOpts.SetOutputDirectory( dirStr );
230 
231  if( m_fileFormat == 2 )
233  else
235 }
236 
238 {
239  BOARD* brd = m_parent->GetBoard();
240  wxFileName fn;
241  wxString msg;
242  int fullcount = 0;
243 
244  // Create output directory if it does not exist. Also transform it in absolute path.
245  // Bail if it fails
247  wxFileName outputDir = wxFileName::DirName( path );
248  wxString boardFilename = m_parent->GetBoard()->GetFileName();
249 
251 
252  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, m_reporter ) )
253  {
254  msg.Printf( _( "Could not write plot files to folder \"%s\"." ),
255  outputDir.GetPath() );
256  DisplayError( this, msg );
257  return false;
258  }
259 
260  fn = m_parent->GetBoard()->GetFileName();
261  fn.SetPath( outputDir.GetPath() );
262 
263  // Create the the Front and Top side placement files. Gerber P&P files are always separated.
264  // Not also they include all footprints
265  PLACEFILE_GERBER_WRITER exporter( brd );
266  wxString filename = exporter.GetPlaceFileName( fn.GetFullPath(), F_Cu );
267 
268  int fpcount = exporter.CreatePlaceFile( filename, F_Cu, m_includeBoardEdge );
269 
270  if( fpcount < 0 )
271  {
272  msg.Printf( _( "Unable to create \"%s\"." ), fn.GetFullPath() );
273  wxMessageBox( msg );
275  return false;
276  }
277 
278  msg.Printf( _( "Front side (top side) place file: \"%s\"." ), filename );
280 
281  msg.Printf( _( "Component count: %d." ), fpcount );
283 
284  // Create the Back or Bottom side placement file
285  fullcount = fpcount;
286 
287  filename = exporter.GetPlaceFileName( fn.GetFullPath(), B_Cu );
288 
289  fpcount = exporter.CreatePlaceFile( filename, B_Cu, m_includeBoardEdge );
290 
291  if( fpcount < 0 )
292  {
293  msg.Printf( _( "Unable to create file \"%s\"." ), filename );
295  wxMessageBox( msg );
296  return false;
297  }
298 
299  // Display results
300  msg.Printf( _( "Back side (bottom side) place file: \"%s\"." ), filename );
302 
303  msg.Printf( _( "Component count: %d." ), fpcount );
304 
306 
307  fullcount += fpcount;
308  msg.Printf( _( "Full component count: %d\n" ), fullcount );
310 
311  m_reporter->Report( _( "Component Placement File generation OK." ), RPT_SEVERITY_ACTION );
312 
313  return true;
314 }
315 
316 
318 {
319  BOARD * brd = m_parent->GetBoard();
320  wxFileName fn;
321  wxString msg;
322  bool singleFile = OneFileOnly();
323  bool useCSVfmt = m_fileFormat == 1;
324  int fullcount = 0;
325  int top_side = true;
326  int bottom_side = true;
327 
328  // Test for any footprint candidate in list.
329  {
330  PLACE_FILE_EXPORTER exporter( brd, UnitsMM(), ExcludeAllTH(), top_side, bottom_side,
331  useCSVfmt );
332  exporter.GenPositionData();
333 
334  if( exporter.GetFootprintCount() == 0 )
335  {
336  wxMessageBox( _( "No footprint for automated placement." ) );
337  return false;
338  }
339  }
340 
341  // Create output directory if it does not exist.
342  // Also transform it in absolute path.
343  // Bail if it fails
344  wxFileName outputDir = wxFileName::DirName( m_plotOpts.GetOutputDirectory() );
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\"." ),
352  GetChars( outputDir.GetPath() ) );
353  DisplayError( this, msg );
354  return false;
355  }
356 
357  fn = m_parent->GetBoard()->GetFileName();
358  fn.SetPath( outputDir.GetPath() );
359 
360  // Create the the Front or Top side placement file, or a single file
361  top_side = true;
362  bottom_side = false;
363 
364  if( singleFile )
365  {
366  bottom_side = true;
367  fn.SetName( fn.GetName() + wxT( "-" ) + wxT("all") );
368  }
369  else
370  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetFrontSideName().c_str() );
371 
372 
373  if( useCSVfmt )
374  {
375  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
376  fn.SetExt( wxT( "csv" ) );
377  }
378  else
379  fn.SetExt( FootprintPlaceFileExtension );
380 
381  int fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(),
382  ExcludeAllTH(), top_side, bottom_side,
383  useCSVfmt );
384  if( fpcount < 0 )
385  {
386  msg.Printf( _( "Unable to create \"%s\"." ), fn.GetFullPath() );
387  wxMessageBox( msg );
389  return false;
390  }
391 
392  if( singleFile )
393  msg.Printf( _( "Place file: \"%s\"." ), fn.GetFullPath() );
394  else
395  msg.Printf( _( "Front side (top side) place file: \"%s\"." ),
396  fn.GetFullPath() );
398 
399  msg.Printf( _( "Component count: %d." ), fpcount );
401 
402  if( singleFile )
403  {
404  m_reporter->Report( _( "Component Placement File generation OK." ), RPT_SEVERITY_ACTION );
405  return true;
406  }
407 
408  // Create the Back or Bottom side placement file
409  fullcount = fpcount;
410  top_side = false;
411  bottom_side = true;
412  fn = brd->GetFileName();
413  fn.SetPath( outputDir.GetPath() );
414  fn.SetName( fn.GetName() + wxT( "-" ) + PLACE_FILE_EXPORTER::GetBackSideName().c_str() );
415 
416  if( useCSVfmt )
417  {
418  fn.SetName( fn.GetName() + wxT( "-" ) + FootprintPlaceFileExtension );
419  fn.SetExt( wxT( "csv" ) );
420  }
421  else
422  fn.SetExt( FootprintPlaceFileExtension );
423 
424  fpcount = m_parent->DoGenFootprintsPositionFile( fn.GetFullPath(), UnitsMM(), ExcludeAllTH(),
425  top_side, bottom_side, useCSVfmt );
426 
427  if( fpcount < 0 )
428  {
429  msg.Printf( _( "Unable to create file \"%s\"." ), fn.GetFullPath() );
431  wxMessageBox( msg );
432  return false;
433  }
434 
435  // Display results
436  if( !singleFile )
437  {
438  msg.Printf( _( "Back side (bottom side) place file: \"%s\"." ), fn.GetFullPath() );
440 
441  msg.Printf( _( "Component count: %d." ), fpcount );
442 
444  }
445 
446  if( !singleFile )
447  {
448  fullcount += fpcount;
449  msg.Printf( _( "Full component count: %d\n" ), fullcount );
451  }
452 
453  m_reporter->Report( _( "Component Placement File generation OK." ), RPT_SEVERITY_ACTION );
454 
455  return true;
456 }
457 
458 
460 {
461  PCB_EDIT_FRAME* editFrame = getEditFrame<PCB_EDIT_FRAME>();
462  DIALOG_GEN_FOOTPRINT_POSITION dlg( editFrame );
463 
464  dlg.ShowModal();
465  return 0;
466 }
467 
468 
469 int PCB_EDIT_FRAME::DoGenFootprintsPositionFile( const wxString& aFullFileName, bool aUnitsMM,
470  bool aForceSmdItems, bool aTopSide,
471  bool aBottomSide, bool aFormatCSV )
472 {
473  FILE * file = NULL;
474 
475  if( !aFullFileName.IsEmpty() )
476  {
477  file = wxFopen( aFullFileName, wxT( "wt" ) );
478 
479  if( file == NULL )
480  return -1;
481  }
482 
483  std::string data;
484  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, aForceSmdItems, aTopSide, aBottomSide,
485  aFormatCSV );
486  data = exporter.GenPositionData();
487 
488  // if aFullFileName is empty, the file is not created, only the
489  // count of footprints to place is returned
490  if( file )
491  {
492  // Creates a footprint position file
493  // aSide = 0 -> Back (bottom) side)
494  // aSide = 1 -> Front (top) side)
495  // aSide = 2 -> both sides
496  fputs( data.c_str(), file );
497  fclose( file );
498  }
499 
500  return exporter.GetFootprintCount();
501 }
502 
503 
504 void PCB_EDIT_FRAME::GenFootprintsReport( wxCommandEvent& event )
505 {
506  wxFileName fn;
507 
508  wxString boardFilePath = ( (wxFileName) GetBoard()->GetFileName() ).GetPath();
509  wxDirDialog dirDialog( this, _( "Select Output Directory" ), boardFilePath );
510 
511  if( dirDialog.ShowModal() == wxID_CANCEL )
512  return;
513 
514  fn = GetBoard()->GetFileName();
515  fn.SetPath( dirDialog.GetPath() );
516  fn.SetExt( wxT( "rpt" ) );
517 
518  bool unitMM = GetUserUnits() != EDA_UNITS::INCHES;
519  bool success = DoGenFootprintsReport( fn.GetFullPath(), unitMM );
520 
521  wxString msg;
522  if( success )
523  {
524  msg.Printf( _( "Footprint report file created:\n\"%s\"" ), fn.GetFullPath() );
525  wxMessageBox( msg, _( "Footprint Report" ), wxICON_INFORMATION );
526  }
527 
528  else
529  {
530  msg.Printf( _( "Unable to create \"%s\"" ), fn.GetFullPath() );
531  DisplayError( this, msg );
532  }
533 }
534 
535 /* Print a module report.
536  */
537 bool PCB_EDIT_FRAME::DoGenFootprintsReport( const wxString& aFullFilename, bool aUnitsMM )
538 {
539  FILE* rptfile = wxFopen( aFullFilename, wxT( "wt" ) );
540 
541  if( rptfile == NULL )
542  return false;
543 
544  std::string data;
545  PLACE_FILE_EXPORTER exporter( GetBoard(), aUnitsMM, false, true, true, false );
546  data = exporter.GenReportData();
547 
548  fputs( data.c_str(), rptfile );
549  fclose( rptfile );
550 
551  return true;
552 }
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:239
const BITMAP_OPAQUE folder_xpm[1]
Definition: folder.cpp:20
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)
Creates 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
PCBNEW_SETTINGS * GetPcbNewSettings()
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:581
REPORTER is 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: class_board.h:244
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)=0
Function Report is a pure virtual function to override in the derived object.
bool CreateAsciiFiles()
Creates files in text or csv format.
void onUpdateUIincludeBoardEdge(wxUpdateUIEvent &event) override
VTBL_ENTRY const wxString AbsolutePath(const wxString &aFileName) const
Function AbsolutePath fixes up aFileName if it is relative to the project's directory to be an absolu...
Definition: project.cpp:272
This file contains miscellaneous commonly used macros and functions.
wxBitmap KiBitmap(BITMAP_DEF aBitmap)
Construct a wxBitmap from a memory record, held in a BITMAP_DEF.
Definition: bitmap.cpp:80
bool DoGenFootprintsReport(const wxString &aFullFilename, bool aUnitsMM)
Function DoGenFootprintsReport Creates an ascii footprint report file giving some infos on footprints...
void GenFootprintsReport(wxCommandEvent &event)
Function GenFootprintsReport Calls DoGenFootprintsReport to create a footprint reprot file See DoGenF...
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
Function Prj returns 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:609
REPORTER & Reporter()
returns the reporter object that reports to this panel
TOOL_EVENT.
Definition: tool_event.h:171
Definition of file extensions used in Kicad.
virtual void SetPlotSettings(const PCB_PLOT_PARAMS &aSettings)
int GeneratePosFile(const TOOL_EVENT &aEvent)
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,...
PCB_PLOT_PARAMS handles plot parameters and options when plotting/printing a board.
void onUpdateUIExcludeTH(wxUpdateUIEvent &event) override
wxString GetOutputDirectory() const
EDA_UNITS m_units
Definition: dialog_shim.h:197
DIALOG_PLACE_FILE m_PlaceFile
const wxString GetPlaceFileName(const wxString &aFullBaseFilename, PCB_LAYER_ID aLayer) const
static const wxChar * GetChars(const wxString &s)
Function GetChars returns a wxChar* to the actual wxChar* data within a wxString, and is helpful for ...
Definition: macros.h:153
see class PGM_BASE
BOARD holds information pertinent to a Pcbnew printed circuit board.
Definition: class_board.h:178
#define _(s)
Definition: 3d_actions.cpp:33
PCB_EDIT_FRAME is the main frame for Pcbnew.
void MsgPanelSetMinSize(const wxSize &aMinSize)
Set the min size of the area which displays html messages:
const std::string FootprintPlaceFileExtension
BOARD * GetBoard() const
int DoGenFootprintsPositionFile(const wxString &aFullFileName, bool aUnitsMM, bool aForceSmdItems, bool aTopSide, bool aBottomSide, bool aFormatCSV=false)
Function DoGenFootprintsPositionFile Creates an ascii footprint position file.
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