KiCad PCB EDA Suite
dialog_gendrill.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) 1992-2019 Jean_Pierre Charras <jp.charras at wanadoo.fr>
5  * Copyright (C) 1992-2022 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 
25 #include <confirm.h>
26 #include <core/arraydim.h>
27 #include <pcb_edit_frame.h>
28 #include <pcbnew_settings.h>
29 #include <pcbplot.h>
31 #include <gendrill_gerber_writer.h>
32 #include <bitmaps.h>
34 #include <board.h>
35 #include <board_design_settings.h>
36 #include <footprint.h>
37 #include <pad.h>
38 #include <pcb_track.h>
39 #include <paths.h>
40 #include <project.h>
41 #include <dialog_gendrill.h>
43 #include <reporter.h>
44 #include <wx/msgdlg.h>
45 #include <wx/dirdlg.h>
46 #include <wx/filedlg.h>
47 
48 // list of allowed precision for EXCELLON files, for integer format:
49 // Due to difference between inches and mm,
50 // there are 2 precision values, one for inches and one for metric
51 // Note: for decimla format, the precision is not used
54 
55 
56 /* This function displays the dialog frame for drill tools
57  */
59 {
60  PCB_EDIT_FRAME* editFrame = getEditFrame<PCB_EDIT_FRAME>();
61  DIALOG_GENDRILL dlg( editFrame, editFrame );
62 
63  dlg.ShowModal();
64  return 0;
65 }
66 
67 
68 DIALOG_GENDRILL::DIALOG_GENDRILL( PCB_EDIT_FRAME* aPcbEditFrame, wxWindow* aParent ) :
69  DIALOG_GENDRILL_BASE( aParent )
70 {
71  m_pcbEditFrame = aPcbEditFrame;
74 
75  // We use a sdbSizer to get platform-dependent ordering of the action buttons, but
76  // that requires us to correct the button labels here.
77  m_sdbSizerOK->SetLabel( _( "Generate Drill File" ) );
78  m_sdbSizerApply->SetLabel( _( "Generate Map File" ) );
79  m_sdbSizerCancel->SetLabel( _( "Close" ) );
80  m_buttonsSizer->Layout();
81 
82  m_sdbSizerOK->SetDefault();
83  SetReturnCode( 1 );
84  initDialog();
85  GetSizer()->SetSizeHints( this );
86 }
87 
88 
89 // Static members of DIALOG_GENDRILL
90 int DIALOG_GENDRILL::m_UnitDrillIsInch = true; // Only for Excellon format
92 bool DIALOG_GENDRILL::m_MinimalHeader = false; // Only for Excellon format
93 bool DIALOG_GENDRILL::m_Mirror = false; // Only for Excellon format
94 bool DIALOG_GENDRILL::m_Merge_PTH_NPTH = false; // Only for Excellon format
95 int DIALOG_GENDRILL::m_mapFileType = 4; // The last choice in m_Choice_Drill_Map
97 bool DIALOG_GENDRILL::m_UseRouteModeForOvalHoles = true; // Use G00 route mode to "drill" oval holes
98 
100 {
101 }
102 
103 
105 {
106  auto cfg = m_pcbEditFrame->GetPcbNewSettings();
107 
108  m_Merge_PTH_NPTH = cfg->m_GenDrill.merge_pth_npth;
109  m_MinimalHeader = cfg->m_GenDrill.minimal_header;
110  m_Mirror = cfg->m_GenDrill.mirror;
111  m_UnitDrillIsInch = cfg->m_GenDrill.unit_drill_is_inch;
112  m_UseRouteModeForOvalHoles = cfg->m_GenDrill.use_route_for_oval_holes;
113  m_drillFileType = cfg->m_GenDrill.drill_file_type;
114  m_mapFileType = cfg->m_GenDrill.map_file_type;
115  m_ZerosFormat = cfg->m_GenDrill.zeros_format;
116 
118 
119  // Ensure validity of m_mapFileType
120  if( m_mapFileType < 0 || m_mapFileType >= (int)m_Choice_Drill_Map->GetCount() )
121  m_mapFileType = m_Choice_Drill_Map->GetCount() - 1; // last item in list = default = PDF
122 
124 }
125 
126 
128 {
130 
131  m_rbExcellon->SetValue( m_drillFileType == 0 );
132  m_rbGerberX2->SetValue( m_drillFileType == 1 );
133  m_Choice_Unit->SetSelection( m_UnitDrillIsInch ? 1 : 0 );
134  m_Choice_Zeros_Format->SetSelection( m_ZerosFormat );
136  m_Check_Minimal->SetValue( m_MinimalHeader );
137 
138  m_Choice_Drill_Offset->SetSelection( m_drillOriginIsAuxAxis ? 1 : 0 );
139 
140  m_Check_Mirror->SetValue( m_Mirror );
142  m_Choice_Drill_Map->SetSelection( m_mapFileType );
143  m_radioBoxOvalHoleMode->SetSelection( m_UseRouteModeForOvalHoles ? 0 : 1 );
144 
147  m_throughViasCount = 0;
148  m_microViasCount = 0;
150 
151  for( FOOTPRINT* footprint : m_board->Footprints() )
152  {
153  for( PAD* pad : footprint->Pads() )
154  {
155  if( pad->GetDrillShape() == PAD_DRILL_SHAPE_CIRCLE )
156  {
157  if( pad->GetDrillSize().x != 0 )
158  {
159  if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
161  else
163  }
164  }
165  else
166  {
167  if( pad->GetDrillSize().x != 0 && pad->GetDrillSize().y != 0 )
168  {
169  if( pad->GetAttribute() == PAD_ATTRIB::NPTH )
171  else
173  }
174  }
175  }
176  }
177 
178  for( PCB_TRACK* track : m_board->Tracks() )
179  {
180  const PCB_VIA *via = dynamic_cast<const PCB_VIA*>( track );
181 
182  if( via )
183  {
184  switch( via->GetViaType() )
185  {
186  case VIATYPE::THROUGH: m_throughViasCount++; break;
187  case VIATYPE::MICROVIA: m_microViasCount++; break;
189  default: break;
190  }
191  }
192  }
193 
194  // Display hole counts:
195  m_PlatedPadsCountInfoMsg->SetLabel( wxString() << m_platedPadsHoleCount );
196  m_NotPlatedPadsCountInfoMsg->SetLabel( wxString() << m_notplatedPadsHoleCount );
197  m_ThroughViasInfoMsg->SetLabel( wxString() << m_throughViasCount );
198  m_MicroViasInfoMsg->SetLabel( wxString() << m_microViasCount );
199  m_BuriedViasInfoMsg->SetLabel( wxString() << m_blindOrBuriedViasCount );
200 
201  // Output directory
203 
204  wxCommandEvent dummy;
206 }
207 
208 
209 void DIALOG_GENDRILL::onFileFormatSelection( wxCommandEvent& event )
210 {
211  bool enbl_Excellon = m_rbExcellon->GetValue();
212 
213  m_drillFileType = enbl_Excellon ? 0 : 1;
214 
215  m_Choice_Unit->Enable( enbl_Excellon );
216  m_Choice_Zeros_Format->Enable( enbl_Excellon );
217  m_Check_Mirror->Enable( enbl_Excellon );
218  m_Check_Minimal->Enable( enbl_Excellon );
219  m_Check_Merge_PTH_NPTH->Enable( enbl_Excellon );
220  m_radioBoxOvalHoleMode->Enable( enbl_Excellon );
221 
222  if( enbl_Excellon )
223  {
225  }
226  else
227  {
228  m_staticTextPrecision->Enable( true );
229  m_staticTextPrecision->SetLabel( m_plotOpts.GetGerberPrecision() == 6 ? wxT( "4.6" )
230  : wxT( "4.5" ) );
231  }
232 }
233 
234 
236 {
238 
239  auto cfg = m_pcbEditFrame->GetPcbNewSettings();
240 
242  cfg->m_GenDrill.minimal_header = m_MinimalHeader;
243  cfg->m_GenDrill.mirror = m_Mirror;
244  cfg->m_GenDrill.unit_drill_is_inch = m_UnitDrillIsInch;
245  cfg->m_GenDrill.use_route_for_oval_holes = m_UseRouteModeForOvalHoles;
246  cfg->m_GenDrill.drill_file_type = m_drillFileType;
247  cfg->m_GenDrill.map_file_type = m_mapFileType;
248  cfg->m_GenDrill.zeros_format = m_ZerosFormat;
249 }
250 
251 
252 void DIALOG_GENDRILL::OnSelDrillUnitsSelected( wxCommandEvent& event )
253 {
255 }
256 
257 
258 void DIALOG_GENDRILL::OnGenMapFile( wxCommandEvent& event )
259 {
260  GenDrillAndMapFiles( false, true );
261 }
262 
263 
264 void DIALOG_GENDRILL::OnGenDrillFile( wxCommandEvent& event )
265 {
266  GenDrillAndMapFiles( true, false );
267 }
268 
269 
270 void DIALOG_GENDRILL::OnSelZerosFmtSelected( wxCommandEvent& event )
271 {
273 }
274 
275 
277 {
278  if( m_Choice_Unit->GetSelection()== 1 )
279  {
280  // Units = inches
282  }
283  else
284  {
285  // metric options
287  }
288 
290  m_staticTextPrecision->Enable( false );
291  else
292  m_staticTextPrecision->Enable( true );
293 }
294 
295 
297 {
298  // Build the absolute path of current output directory to preselect it in the file browser.
299  wxString path = ExpandEnvVarSubstitutions( m_outputDirectoryName->GetValue(), &Prj() );
300  path = Prj().AbsolutePath( path );
301 
302  wxDirDialog dirDialog( this, _( "Select Output Directory" ), path );
303 
304  if( dirDialog.ShowModal() == wxID_CANCEL )
305  return;
306 
307  wxFileName dirName = wxFileName::DirName( dirDialog.GetPath() );
308  wxFileName fn( Prj().AbsolutePath( m_board->GetFileName() ) );
309  wxString defaultPath = fn.GetPathWithSep();
310  wxString msg;
311  msg.Printf( _( "Do you want to use a path relative to\n'%s'?" ), defaultPath );
312 
313  wxMessageDialog dialog( this, msg, _( "Plot Output Directory" ),
314  wxYES_NO | wxICON_QUESTION | wxYES_DEFAULT );
315 
316  if( dialog.ShowModal() == wxID_YES )
317  {
318  if( !dirName.MakeRelativeTo( defaultPath ) )
319  {
320  wxMessageBox( _( "Cannot make path relative (target volume different from file volume)!" ),
321  _( "Plot Output Directory" ), wxOK | wxICON_ERROR );
322  }
323  }
324 
325  m_outputDirectoryName->SetValue( dirName.GetFullPath() );
326 }
327 
328 
330 {
331  wxString msg;
332 
333  // Set output directory and replace backslashes with forward ones
334  wxString dirStr;
335  dirStr = m_outputDirectoryName->GetValue();
336  dirStr.Replace( wxT( "\\" ), wxT( "/" ) );
337  m_plotOpts.SetOutputDirectory( dirStr );
338  m_drillOriginIsAuxAxis = m_Choice_Drill_Offset->GetSelection() == 1;
340 
341  m_mapFileType = m_Choice_Drill_Map->GetSelection();
342 
343  m_UnitDrillIsInch = (m_Choice_Unit->GetSelection() == 0) ? false : true;
344  m_MinimalHeader = m_Check_Minimal->IsChecked();
345  m_Mirror = m_Check_Mirror->IsChecked();
347  m_ZerosFormat = m_Choice_Zeros_Format->GetSelection();
348  m_UseRouteModeForOvalHoles = m_radioBoxOvalHoleMode->GetSelection() == 0;
349 
350  if( m_Choice_Drill_Offset->GetSelection() == 0 )
351  m_DrillFileOffset = wxPoint( 0, 0 );
352  else
354 
355  if( m_UnitDrillIsInch )
357  else
359 
361  {
364  }
365 }
366 
367 
368 void DIALOG_GENDRILL::GenDrillAndMapFiles( bool aGenDrill, bool aGenMap )
369 {
370  UpdateConfig(); // set params and Save drill options
371 
374 
375  const PLOT_FORMAT filefmt[] = {
376  // Keep these format ids in the same order than m_Choice_Drill_Map choices
378  PLOT_FORMAT::GERBER, // Only X2 format because we need the .FileFunction attribute
382  };
383 
384  unsigned choice = (unsigned) m_Choice_Drill_Map->GetSelection();
385 
386  if( choice >= arrayDim( filefmt ) )
387  choice = arrayDim( filefmt )-1; // Last choice = PDF
388 
389  // Create output directory if it does not exist (also transform it in absolute form).
390  // Bail if it fails.
391 
392  std::function<bool( wxString* )> textResolver =
393  [&]( wxString* token ) -> bool
394  {
395  // Handles m_board->GetTitleBlock() *and* m_board->GetProject()
396  return m_board->ResolveTextVar( token, 0 );
397  };
398 
399  wxString path = m_plotOpts.GetOutputDirectory();
400  path = ExpandTextVars( path, &textResolver, nullptr, nullptr );
401  path = ExpandEnvVarSubstitutions( path, nullptr );
402 
403  wxFileName outputDir = wxFileName::DirName( path );
404  wxString boardFilename = m_board->GetFileName();
405 
406  if( !EnsureFileDirectoryExists( &outputDir, boardFilename, &reporter ) )
407  {
408  wxString msg;
409  msg.Printf( _( "Could not write drill and/or map files to folder '%s'." ),
410  outputDir.GetPath() );
411  DisplayError( this, msg );
412  return;
413  }
414 
415  if( m_drillFileType == 0 )
416  {
417  EXCELLON_WRITER excellonWriter( m_board );
422  excellonWriter.SetMapFileFormat( filefmt[choice] );
423 
424  excellonWriter.CreateDrillandMapFilesSet( outputDir.GetFullPath(), aGenDrill, aGenMap,
425  &reporter );
426  }
427  else
428  {
429  GERBER_WRITER gerberWriter( m_board );
430  // Set gerber precision: only 5 or 6 digits for mantissa are allowed
431  // (SetFormat() accept 5 or 6, and any other value set the precision to 5)
432  // the integer part precision is always 4, and units always mm
433  gerberWriter.SetFormat( m_plotOpts.GetGerberPrecision() );
434  gerberWriter.SetOptions( m_DrillFileOffset );
435  gerberWriter.SetMapFileFormat( filefmt[choice] );
436 
437  gerberWriter.CreateDrillandMapFilesSet( outputDir.GetFullPath(), aGenDrill, aGenMap,
438  &reporter );
439  }
440 }
441 
442 
443 void DIALOG_GENDRILL::OnGenReportFile( wxCommandEvent& event )
444 {
445  UpdateConfig(); // set params and Save drill options
446 
447  wxFileName fn = m_board->GetFileName();
448 
449  fn.SetName( fn.GetName() + wxT( "-drl" ) );
450  fn.SetExt( ReportFileExtension );
451 
452  wxString defaultPath = ExpandEnvVarSubstitutions( m_plotOpts.GetOutputDirectory(), &Prj() );
453  defaultPath = Prj().AbsolutePath( defaultPath );
454 
455  if( defaultPath.IsEmpty() )
456  defaultPath = PATHS::GetDefaultUserProjectsPath();
457 
458  wxFileDialog dlg( this, _( "Save Drill Report File" ), defaultPath, fn.GetFullName(),
459  ReportFileWildcard(), wxFD_SAVE );
460 
461  if( dlg.ShowModal() == wxID_CANCEL )
462  return;
463 
464  bool success;
465 
466  // Info is slightly different between Excellon and Gerber
467  // (file ext, Merge PTH/NPTH option)
468  if( m_drillFileType == 0 )
469  {
470  EXCELLON_WRITER excellonWriter( m_board );
471  excellonWriter.SetMergeOption( m_Merge_PTH_NPTH );
472  success = excellonWriter.GenDrillReportFile( dlg.GetPath() );
473  }
474  else
475  {
476  GERBER_WRITER gerberWriter( m_board );
477  success = gerberWriter.GenDrillReportFile( dlg.GetPath() );
478  }
479 
480  wxString msg;
481 
482  if( ! success )
483  {
484  msg.Printf( _( "Failed to create file '%s'." ), dlg.GetPath() );
485  m_messagesBox->AppendText( msg );
486  }
487  else
488  {
489  msg.Printf( _( "Report file '%s' created." ), dlg.GetPath() );
490  m_messagesBox->AppendText( msg );
491  }
492 }
static int m_UnitDrillIsInch
DIALOG_GENERATE_DRILL m_GenDrill
void DisplayError(wxWindow *aParent, const wxString &aText, int aDisplayTime)
Display an error or warning message box with aMessage.
Definition: confirm.cpp:279
wxStaticText * m_PlatedPadsCountInfoMsg
void OnModify() override
Must be called after a board change to set the modified flag.
void SetRouteModeForOvalHoles(bool aUseRouteModeForOvalHoles)
void OnGenDrillFile(wxCommandEvent &event) override
const PCB_PLOT_PARAMS & GetPlotOptions() const
Definition: board.h:539
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject)
Definition: common.cpp:57
void SetUseAuxOrigin(bool aAux)
This file is part of the common library.
wxRadioBox * m_Choice_Drill_Offset
void OnSelZerosFmtSelected(wxCommandEvent &event) override
Create Excellon drill, drill map, and drill report files.
wxCheckBox * m_Check_Merge_PTH_NPTH
void OnSelDrillUnitsSelected(wxCommandEvent &event) override
Class DIALOG_GENDRILL_BASE.
void SetOutputDirectory(const wxString &aDir)
static bool m_Merge_PTH_NPTH
static int m_ZerosFormat
static bool m_UseRouteModeForOvalHoles
void SetMergeOption(bool aMerge)
Set the option to make separate drill files for PTH and NPTH.
wxPoint m_DrillFileOffset
void SetFormat(int aRightDigits=6)
Initialize internal parameters to match the given format.
static int m_mapFileType
const wxString ExpandEnvVarSubstitutions(const wxString &aString, PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition: common.cpp:267
Used to create Gerber drill files.
virtual const PCB_PLOT_PARAMS & GetPlotSettings() const
Return the PCB_PLOT_PARAMS for the BOARD owned by this frame.
const wxString & GetFileName() const
Definition: board.h:229
wxStaticText * m_NotPlatedPadsCountInfoMsg
BOARD_DESIGN_SETTINGS & GetDesignSettings() const
Definition: board.cpp:590
Helper to handle drill precision format in excellon files.
A wrapper for reporting to a wxTextCtrl object.
Definition: reporter.h:137
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
void SetFormat(bool aMetric, ZEROS_FMT aZerosFmt=DECIMAL_FORMAT, int aLeftDigits=0, int aRightDigits=0)
Initialize internal parameters to match the given format.
Board plot function definition file.
static LIB_SYMBOL * dummy()
Used to draw a dummy shape when a LIB_SYMBOL is not found in library.
Definition: sch_symbol.cpp:72
wxRadioBox * m_radioBoxOvalHoleMode
static bool m_MinimalHeader
wxStaticText * m_MicroViasInfoMsg
like PAD_PTH, but not plated
int GetGerberPrecision() const
wxRadioButton * m_rbExcellon
void SetMapFileFormat(PLOT_FORMAT aMapFmt)
Initialize the format for the drill map file.
bool GenDrillReportFile(const wxString &aFullFileName)
Create a plain text report file giving a list of drill values and drill count for through holes,...
bool IsSameAs(const PCB_PLOT_PARAMS &aPcbPlotParams) const
Compare current settings to aPcbPlotParams, including not saved parameters in brd file.
wxStaticText * m_BuriedViasInfoMsg
wxString ReportFileWildcard()
wxStaticText * m_ThroughViasInfoMsg
PLOT_FORMAT
The set of supported output plot formats.
Definition: plotter.h:67
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
wxTextCtrl * m_outputDirectoryName
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:295
FOOTPRINTS & Footprints()
Definition: board.h:234
Generic, UI-independent tool event.
Definition: tool_event.h:152
void CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board filenames are computed from the board name,...
wxRadioBox * m_Choice_Zeros_Format
Definition of file extensions used in Kicad.
#define _(s)
constexpr std::size_t arrayDim(T const (&)[N]) noexcept
Returns # of elements in an array.
Definition: arraydim.h:31
void SetOptions(bool aMirror, bool aMinimalHeader, const wxPoint &aOffset, bool aMerge_PTH_NPTH)
Initialize internal parameters to match drill options.
PCB_PLOT_PARAMS m_plotOpts
void SetPlotOptions(const PCB_PLOT_PARAMS &aOptions)
Definition: board.h:540
static DRILL_PRECISION precisionListForMetric(3, 3)
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
virtual void ClearMsgPanel()
Clear all messages from the message panel.
DIALOG_GENDRILL(PCB_EDIT_FRAME *aPcbEditFrame, wxWindow *aParent)
wxBitmapButton * m_browseButton
wxString GetOutputDirectory() const
void SetOptions(const wxPoint &aOffset)
Initialize internal parameters to match drill options.
static bool m_Mirror
static wxString GetDefaultUserProjectsPath()
Gets the default path we point users to create projects.
Definition: paths.cpp:139
DRILL_PRECISION m_Precision
void onFileFormatSelection(wxCommandEvent &event) override
static int m_drillFileType
const wxPoint & GetAuxOrigin()
const std::string ReportFileExtension
The main frame for Pcbnew.
PCBNEW_SETTINGS * GetPcbNewSettings() const
Classes used in drill files, map files and report files generation.
void CreateDrillandMapFilesSet(const wxString &aPlotDirectory, bool aGenDrill, bool aGenMap, REPORTER *aReporter=nullptr)
Create the full set of Excellon drill file for the board.
wxStaticText * m_staticTextPrecision
Classes used in drill files, map files and report files generation.
void OnGenReportFile(wxCommandEvent &event) override
int GenerateDrillFiles(const TOOL_EVENT &aEvent)
BOARD * GetBoard() const
void UpdateDrillParams()
Update board drill/plot parameters.
bool GetUseAuxOrigin() const
Definition: pad.h:57
bool ResolveTextVar(wxString *token, int aDepth) const
Definition: board.cpp:240
void OnOutputDirectoryBrowseClicked(wxCommandEvent &event) override
void OnGenMapFile(wxCommandEvent &event) override
void GenDrillAndMapFiles(bool aGenDrill, bool aGenMap)
Call the functions to create EXCELLON drill files and/or drill map files.
wxRadioButton * m_rbGerberX2
TRACKS & Tracks()
Definition: board.h:231
static DRILL_PRECISION precisionListForInches(2, 4)
PCB_EDIT_FRAME * m_pcbEditFrame