1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2019 Jean-Pierre Charras, jp.charras at wanadoo.fr
5  * Copyright (C) 2012 SoftPLC Corporation, Dick Hollenbeck <dick@softplc.com>
6  * Copyright (C) 1992-2021 KiCad Developers, see AUTHORS.txt for contributors.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, you may find one here:
20  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
21  * or you may search the http://www.gnu.org website for the version 2 license,
22  * or you may write to the Free Software Foundation, Inc.,
23  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
24  */
25 
26 #include <kiface_base.h>
27 #include <confirm.h>
28 #include <pcb_edit_frame.h>
29 #include <pcbnew_settings.h>
30 #include <zones.h>
31 #include <bitmaps.h>
32 #include <widgets/unit_binder.h>
33 #include <zone.h>
34 #include <pad.h>
35 #include <board.h>
36 #include <trigo.h>
37 #include <eda_pattern_match.h>
38 
39 #include <dialog_copper_zones_base.h>
40 #include <string_utils.h>
41 
42 
43 class DIALOG_COPPER_ZONE : public DIALOG_COPPER_ZONE_BASE
44 {
45 public:
46     DIALOG_COPPER_ZONE( PCB_BASE_FRAME* aParent, ZONE_SETTINGS* aSettings );
47 
48 private:
49     using NET_FILTER = std::unique_ptr<EDA_PATTERN_MATCH>;
50     using NET_FILTER_LIST = std::vector<NET_FILTER>;
51 
52     static constexpr int INVALID_NET_CODE{ 0 };
53 
54     static constexpr int DEFAULT_SORT_CONFIG{ -1 };
55     static constexpr int NO_PERSISTENT_SORT_MODE{ 0 };
56     static constexpr int HIDE_ANONYMOUS_NETS{ 1 << 0 };
57     static constexpr int SORT_BY_PAD_COUNT{ 1 << 1 };
58 
59     PCB_BASE_FRAME*  m_Parent;
60 
61     bool             m_settingsExported;     // settings will be written to all other zones
62 
63     ZONE_SETTINGS    m_settings;
64     ZONE_SETTINGS*   m_ptr;
65     bool             m_netSortingByPadCount;
66     NET_FILTER_LIST  m_showNetsFilter;
67 
68     int              m_cornerSmoothingType;
69     int              m_maxNetCode;
70     int              m_currentlySelectedNetcode;
71 
72     UNIT_BINDER      m_cornerRadius;
73     UNIT_BINDER      m_clearance;
74     UNIT_BINDER      m_minWidth;
75     UNIT_BINDER      m_antipadClearance;
76     UNIT_BINDER      m_spokeWidth;
77 
78     UNIT_BINDER      m_gridStyleRotation;
79     UNIT_BINDER      m_gridStyleThickness;
80     UNIT_BINDER      m_gridStyleGap;
81     UNIT_BINDER      m_islandThreshold;
82     bool             m_hideAutoGeneratedNets;
83 
84     std::map<wxString, int>    m_netNameToNetCode;
85     std::vector<NETINFO_ITEM*> m_netInfoItemList;
86 
87     bool TransferDataToWindow() override;
88     bool TransferDataFromWindow() override;
89 
90     /**
91      * @param aUseExportableSetupOnly is true to use exportable parameters only (used to
92      *                                export this setup to other zones).
93      * @return bool - false if incorrect options, true if ok.
94      */
95     bool AcceptOptions( bool aUseExportableSetupOnly = false );
96 
97     void OnStyleSelection( wxCommandEvent& event ) override;
98     void OnLayerSelection( wxDataViewEvent& event ) override;
99     void OnNetSortingOptionSelected( wxCommandEvent& event ) override;
100     void ExportSetupToOtherCopperZones( wxCommandEvent& event ) override;
101     void OnShowNetNameFilterChange( wxCommandEvent& event ) override;
102     void OnUpdateUI( wxUpdateUIEvent& ) override;
103     void OnButtonCancelClick( wxCommandEvent& event ) override;
104     void OnClose( wxCloseEvent& event ) override;
105     void OnNetSelectionUpdated( wxCommandEvent& event ) override;
106     void OnRemoveIslandsSelection( wxCommandEvent& event ) override;
107 
108     void          readNetInformation();
109     void          readFilteringAndSortingCriteria();
110     void          buildListOfNets( const NETINFO_LIST& nets );
111     wxArrayString buildListOfNetsToDisplay();
112     void          sortNetsByPadCount( std::vector<NETINFO_ITEM*>& nets, const int maxNetCode );
113     void          updateDisplayedListOfNets();
114     int           ensureSelectedNetIsVisible( int selectedNetCode, wxArrayString& netsList );
115     void          displayNetsList( const wxArrayString& netNamesList, int selectIndex );
116     void          updateShowNetsFilter();
117     wxString      getUnescapedNetName( const NETINFO_ITEM* net );
118     void          sortNetsIfRequired();
119     wxArrayString getSortedNetNamesList();
120     wxArrayString applyShowFilter( const wxArrayString& sortedNetNames );
121     wxArrayString applyHideFilterIfRequired( const wxArrayString& netNames );
122     bool          isAutoGenerated( const wxString& netName );
123     void          updateCurrentNetSelection();
124     void          updateInfoBar();
125     void          handleRemoveIslandsSelection();
126     void          storePersistentNetSortConfigurations();
127     void          loadPersistentNetSortConfigurations();
128 };
129 
130 
InvokeCopperZonesEditor(PCB_BASE_FRAME * aCaller,ZONE_SETTINGS * aSettings)131 int InvokeCopperZonesEditor( PCB_BASE_FRAME* aCaller, ZONE_SETTINGS* aSettings )
132 {
133     DIALOG_COPPER_ZONE dlg( aCaller, aSettings );
134 
135     return dlg.ShowQuasiModal();
136 }
137 
138 
139 // The pad count for each netcode, stored in a buffer for a fast access.
140 // This is needed by the sort function sortNetsByNodes()
141 static std::vector<int> padCountListByNet;
142 
143 
144 // Sort nets by decreasing pad count.
145 // For same pad count, sort by alphabetic names
sortNetsByNodes(const NETINFO_ITEM * a,const NETINFO_ITEM * b)146 static bool sortNetsByNodes( const NETINFO_ITEM* a, const NETINFO_ITEM* b )
147 {
148     int countA = padCountListByNet[a->GetNetCode()];
149     int countB = padCountListByNet[b->GetNetCode()];
150 
151     if( countA == countB )
152         return a->GetNetname() < b->GetNetname();
153     else
154         return countB < countA;
155 }
156 
157 
158 // Sort nets by alphabetic names
sortNetsByNames(const NETINFO_ITEM * a,const NETINFO_ITEM * b)159 static bool sortNetsByNames( const NETINFO_ITEM* a, const NETINFO_ITEM* b )
160 {
161     return a->GetNetname() < b->GetNetname();
162 }
163 
164 
DIALOG_COPPER_ZONE(PCB_BASE_FRAME * aParent,ZONE_SETTINGS * aSettings)165 DIALOG_COPPER_ZONE::DIALOG_COPPER_ZONE( PCB_BASE_FRAME* aParent, ZONE_SETTINGS* aSettings ) :
166         DIALOG_COPPER_ZONE_BASE( aParent ),
167         m_cornerSmoothingType( ZONE_SETTINGS::SMOOTHING_UNDEFINED ),
168         m_cornerRadius( aParent, m_cornerRadiusLabel, m_cornerRadiusCtrl, m_cornerRadiusUnits ),
169         m_clearance( aParent, m_clearanceLabel, m_clearanceCtrl, m_clearanceUnits ),
170         m_minWidth( aParent, m_minWidthLabel, m_minWidthCtrl, m_minWidthUnits ),
171         m_antipadClearance( aParent, m_antipadLabel, m_antipadCtrl, m_antipadUnits ),
172         m_spokeWidth( aParent, m_spokeWidthLabel, m_spokeWidthCtrl, m_spokeWidthUnits ),
173         m_gridStyleRotation( aParent, m_staticTextGrindOrient, m_tcGridStyleOrientation,
174                              m_staticTextRotUnits ),
175         m_gridStyleThickness( aParent, m_staticTextStyleThickness, m_tcGridStyleThickness,
176                               m_GridStyleThicknessUnits ),
177         m_gridStyleGap( aParent, m_staticTextGridGap, m_tcGridStyleGap, m_GridStyleGapUnits ),
178         m_islandThreshold( aParent, m_islandThresholdLabel, m_tcIslandThreshold,
179                            m_islandThresholdUnits ),
180         m_hideAutoGeneratedNets{ false }
181 {
182     m_Parent = aParent;
183 
184     m_ptr = aSettings;
185     m_settings = *aSettings;
186     m_settings.SetupLayersList( m_layers, m_Parent, true );
187 
188     m_settingsExported = false;
189     m_currentlySelectedNetcode = INVALID_NET_CODE;
190     m_maxNetCode = INVALID_NET_CODE;
191 
192     m_netSortingByPadCount = true;      // false = alphabetic sort, true = pad count sort
193 
194     m_sdbSizerOK->SetDefault();
195     m_ShowNetNameFilter->SetHint( _( "Filter" ) );
196 
197     m_cbRemoveIslands->Bind( wxEVT_CHOICE,
198             [&]( wxCommandEvent& )
__anon112208b20102( wxCommandEvent& ) 199             {
200                 // Area mode is index 2
201                 bool val = m_cbRemoveIslands->GetSelection() == 2;
202 
203                 m_tcIslandThreshold->Enable( val );
204                 m_islandThresholdLabel->Enable( val );
205                 m_islandThresholdUnits->Enable( val );
206             } );
207 
208     finishDialogSettings();
209 }
210 
211 
TransferDataToWindow()212 bool DIALOG_COPPER_ZONE::TransferDataToWindow()
213 {
214     m_constrainOutline->SetValue( m_settings.m_Zone_45_Only );
215     m_cbLocked->SetValue( m_settings.m_Locked );
216     m_cornerSmoothingChoice->SetSelection( m_settings.GetCornerSmoothingType() );
217     m_cornerRadius.SetValue( m_settings.GetCornerRadius() );
218     m_PriorityLevelCtrl->SetValue( m_settings.m_ZonePriority );
219 
220     switch( m_settings.m_ZoneBorderDisplayStyle )
221     {
222     case ZONE_BORDER_DISPLAY_STYLE::NO_HATCH:      m_OutlineDisplayCtrl->SetSelection( 0 ); break;
223     case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_EDGE: m_OutlineDisplayCtrl->SetSelection( 1 ); break;
224     case ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_FULL: m_OutlineDisplayCtrl->SetSelection( 2 ); break;
225     }
226 
227     m_clearance.SetValue( m_settings.m_ZoneClearance );
228     m_minWidth.SetValue( m_settings.m_ZoneMinThickness );
229 
230     switch( m_settings.GetPadConnection() )
231     {
232     default:
233     case ZONE_CONNECTION::THERMAL:     m_PadInZoneOpt->SetSelection( 1 ); break;
234     case ZONE_CONNECTION::THT_THERMAL: m_PadInZoneOpt->SetSelection( 2 ); break;
235     case ZONE_CONNECTION::NONE:        m_PadInZoneOpt->SetSelection( 3 ); break;
236     case ZONE_CONNECTION::FULL:        m_PadInZoneOpt->SetSelection( 0 ); break;
237     }
238 
239     // Do not enable/disable antipad clearance and spoke width.  They might be needed if
240     // a footprint or pad overrides the zone to specify a thermal connection.
241     m_antipadClearance.SetValue( m_settings.m_ThermalReliefGap );
242     m_spokeWidth.SetValue( m_settings.m_ThermalReliefSpokeWidth );
243 
244     m_islandThreshold.SetDataType( EDA_DATA_TYPE::AREA );
245     m_islandThreshold.SetDoubleValue( static_cast<double>( m_settings.GetMinIslandArea() ) );
246 
247     m_cbRemoveIslands->SetSelection( static_cast<int>( m_settings.GetIslandRemovalMode() ) );
248 
249     bool val = m_settings.GetIslandRemovalMode() == ISLAND_REMOVAL_MODE::AREA;
250 
251     m_tcIslandThreshold->Enable( val );
252     m_islandThresholdLabel->Enable( val );
253     m_islandThresholdUnits->Enable( val );
254 
255     loadPersistentNetSortConfigurations();
256 
257     m_sortByPadsOpt->SetValue( m_netSortingByPadCount );
258     m_hideAutoGenNetNamesOpt->SetValue( m_hideAutoGeneratedNets );
259 
260     m_currentlySelectedNetcode = m_settings.m_NetcodeSelection;
261 
262     // Initialize information required to display nets list
263     readNetInformation();
264 
265     switch( m_settings.m_FillMode )
266     {
267     case ZONE_FILL_MODE::HATCH_PATTERN: m_GridStyleCtrl->SetSelection( 1 ); break;
268     default:                            m_GridStyleCtrl->SetSelection( 0 ); break;
269     }
270 
271     m_gridStyleRotation.SetUnits( EDA_UNITS::DEGREES );
272     m_gridStyleRotation.SetValue( m_settings.m_HatchOrientation * 10 ); // IU is decidegree
273 
274     // Gives a reasonable value to grid style parameters, if currently there are no defined
275     // parameters for grid pattern thickness and gap (if the value is 0)
276     // the grid pattern thickness default value is (arbitrary) m_ZoneMinThickness * 4
277     // or 1mm
278     // the grid pattern gap default value is (arbitrary) m_ZoneMinThickness * 6
279     // or 1.5 mm
280     int bestvalue = m_settings.m_HatchThickness;
281 
282     if( bestvalue <= 0 )     // No defined value for m_HatchThickness
283         bestvalue = std::max( m_settings.m_ZoneMinThickness * 4, Millimeter2iu( 1.0 ) );
284 
285     m_gridStyleThickness.SetValue( std::max( bestvalue, m_settings.m_ZoneMinThickness ) );
286 
287     bestvalue = m_settings.m_HatchGap;
288 
289     if( bestvalue <= 0 )     // No defined value for m_HatchGap
290         bestvalue = std::max( m_settings.m_ZoneMinThickness * 6, Millimeter2iu( 1.5 ) );
291 
292     m_gridStyleGap.SetValue( std::max( bestvalue, m_settings.m_ZoneMinThickness ) );
293 
294     m_spinCtrlSmoothLevel->SetValue( m_settings.m_HatchSmoothingLevel );
295     m_spinCtrlSmoothValue->SetValue( m_settings.m_HatchSmoothingValue );
296 
297     m_tcZoneName->SetValue( m_settings.m_Name );
298 
299     updateInfoBar();
300     handleRemoveIslandsSelection();
301 
302     updateDisplayedListOfNets();
303 
304     SetInitialFocus( m_ShowNetNameFilter );
305 
306     // Enable/Disable some widgets
307     wxCommandEvent event;
308     OnStyleSelection( event );
309 
310     Fit();
311 
312     return true;
313 }
314 
315 
readNetInformation()316 void DIALOG_COPPER_ZONE::readNetInformation()
317 {
318     NETINFO_LIST& netInfoList = m_Parent->GetBoard()->GetNetInfo();
319 
320     if( netInfoList.GetNetCount() > 0 )
321     {
322         buildListOfNets( netInfoList );
323     }
324 }
325 
326 
buildListOfNets(const NETINFO_LIST & nets)327 void DIALOG_COPPER_ZONE::buildListOfNets( const NETINFO_LIST& nets )
328 {
329     m_netInfoItemList.clear();
330     m_netInfoItemList.reserve( nets.GetNetCount() );
331 
332     m_netNameToNetCode.clear();
333     m_netNameToNetCode[wxT( "<no net>" )] = INVALID_NET_CODE;
334 
335     m_maxNetCode = INVALID_NET_CODE;
336 
337     for( NETINFO_ITEM* net : nets )
338     {
339         const int& netCode = net->GetNetCode();
340         const wxString& netName = getUnescapedNetName( net );
341 
342         m_netNameToNetCode[netName] = netCode;
343 
344         if( netCode > INVALID_NET_CODE && net->IsCurrent() )
345         {
346             m_netInfoItemList.push_back( net );
347             m_maxNetCode = std::max( netCode, m_maxNetCode );
348         }
349     }
350 }
351 
352 
OnUpdateUI(wxUpdateUIEvent &)353 void DIALOG_COPPER_ZONE::OnUpdateUI( wxUpdateUIEvent& )
354 {
355     if( m_cornerSmoothingType != m_cornerSmoothingChoice->GetSelection() )
356     {
357         m_cornerSmoothingType = m_cornerSmoothingChoice->GetSelection();
358 
359         if( m_cornerSmoothingChoice->GetSelection() == ZONE_SETTINGS::SMOOTHING_CHAMFER )
360             m_cornerRadiusLabel->SetLabel( _( "Chamfer distance:" ) );
361         else
362             m_cornerRadiusLabel->SetLabel( _( "Fillet radius:" ) );
363     }
364 
365     m_cornerRadiusCtrl->Enable(m_cornerSmoothingType > ZONE_SETTINGS::SMOOTHING_NONE );
366 }
367 
368 
OnButtonCancelClick(wxCommandEvent & event)369 void DIALOG_COPPER_ZONE::OnButtonCancelClick( wxCommandEvent& event )
370 {
371     // After an "Export Settings to Other Zones" cancel and close must return
372     // ZONE_EXPORT_VALUES instead of wxID_CANCEL.
373     Close( true );
374 }
375 
376 
OnNetSelectionUpdated(wxCommandEvent & event)377 void DIALOG_COPPER_ZONE::OnNetSelectionUpdated( wxCommandEvent& event )
378 {
379     updateCurrentNetSelection();
380 
381     updateInfoBar();
382 
383     // When info bar is updated, the nets-list shrinks.
384     // Therefore, we need to reestablish the list and maintain the
385     // correct selection
386     updateDisplayedListOfNets();
387 
388     handleRemoveIslandsSelection();
389 }
390 
391 
OnRemoveIslandsSelection(wxCommandEvent & event)392 void DIALOG_COPPER_ZONE::OnRemoveIslandsSelection( wxCommandEvent& event )
393 {
394     handleRemoveIslandsSelection();
395 }
396 
397 
handleRemoveIslandsSelection()398 void DIALOG_COPPER_ZONE::handleRemoveIslandsSelection()
399 {
400     bool noNetSelected = m_currentlySelectedNetcode == INVALID_NET_CODE;
401     bool enableSize = !noNetSelected && ( m_cbRemoveIslands->GetSelection() == 2 );
402 
403     // Zones with no net never have islands removed
404     m_cbRemoveIslands->Enable( !noNetSelected );
405     m_islandThresholdLabel->Enable( enableSize );
406     m_islandThresholdUnits->Enable( enableSize );
407     m_tcIslandThreshold->Enable( enableSize );
408 }
409 
410 
TransferDataFromWindow()411 bool DIALOG_COPPER_ZONE::TransferDataFromWindow()
412 {
413     if( m_GridStyleCtrl->GetSelection() > 0 )
414         m_settings.m_FillMode = ZONE_FILL_MODE::HATCH_PATTERN;
415     else
416         m_settings.m_FillMode = ZONE_FILL_MODE::POLYGONS;
417 
418     if( !AcceptOptions() )
419         return false;
420 
421     m_settings.m_HatchOrientation = m_gridStyleRotation.GetValue() / 10.0; // value is returned in deci-degree
422     m_settings.m_HatchThickness = m_gridStyleThickness.GetValue();
423     m_settings.m_HatchGap = m_gridStyleGap.GetValue();
424     m_settings.m_HatchSmoothingLevel = m_spinCtrlSmoothLevel->GetValue();
425     m_settings.m_HatchSmoothingValue = m_spinCtrlSmoothValue->GetValue();
426 
427     *m_ptr = m_settings;
428     return true;
429 }
430 
431 
OnClose(wxCloseEvent & event)432 void DIALOG_COPPER_ZONE::OnClose( wxCloseEvent& event )
433 {
434     SetReturnCode( m_settingsExported ? ZONE_EXPORT_VALUES : wxID_CANCEL );
435     event.Skip();
436 }
437 
438 
AcceptOptions(bool aUseExportableSetupOnly)439 bool DIALOG_COPPER_ZONE::AcceptOptions( bool aUseExportableSetupOnly )
440 {
441     if( !m_clearance.Validate( 0, Mils2iu( ZONE_CLEARANCE_MAX_VALUE_MIL ) ) )
442         return false;
443 
444     if( !m_minWidth.Validate( Mils2iu( ZONE_THICKNESS_MIN_VALUE_MIL ), INT_MAX ) )
445         return false;
446 
447     if( !m_cornerRadius.Validate( 0, INT_MAX ) )
448         return false;
449 
450     if( !m_spokeWidth.Validate( 0, INT_MAX ) )
451         return false;
452 
453     m_gridStyleRotation.SetValue( NormalizeAngle180( m_gridStyleRotation.GetValue() ) );
454 
455     if( m_settings.m_FillMode == ZONE_FILL_MODE::HATCH_PATTERN )
456     {
457         int minThickness = m_minWidth.GetValue();
458 
459         if( !m_gridStyleThickness.Validate( minThickness, INT_MAX ) )
460             return false;
461 
462         if( !m_gridStyleGap.Validate( minThickness, INT_MAX ) )
463             return false;
464     }
465 
466     switch( m_PadInZoneOpt->GetSelection() )
467     {
468     case 3: m_settings.SetPadConnection( ZONE_CONNECTION::NONE );        break;
469     case 2: m_settings.SetPadConnection( ZONE_CONNECTION::THT_THERMAL ); break;
470     case 1: m_settings.SetPadConnection( ZONE_CONNECTION::THERMAL );     break;
471     case 0: m_settings.SetPadConnection( ZONE_CONNECTION::FULL );        break;
472     }
473 
474     switch( m_OutlineDisplayCtrl->GetSelection() )
475     {
476     case 0: m_settings.m_ZoneBorderDisplayStyle = ZONE_BORDER_DISPLAY_STYLE::NO_HATCH;      break;
477     case 1: m_settings.m_ZoneBorderDisplayStyle = ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_EDGE; break;
478     case 2: m_settings.m_ZoneBorderDisplayStyle = ZONE_BORDER_DISPLAY_STYLE::DIAGONAL_FULL; break;
479     }
480 
481     PCBNEW_SETTINGS* cfg = m_Parent->GetPcbNewSettings();
482 
483     cfg->m_Zones.hatching_style = static_cast<int>( m_settings.m_ZoneBorderDisplayStyle );
484 
485     m_settings.m_ZoneClearance = m_clearance.GetValue();
486     m_settings.m_ZoneMinThickness = m_minWidth.GetValue();
487 
488     m_settings.SetCornerSmoothingType( m_cornerSmoothingChoice->GetSelection() );
489 
490     m_settings.SetCornerRadius( m_settings.GetCornerSmoothingType() == ZONE_SETTINGS::SMOOTHING_NONE
491                                 ? 0 : m_cornerRadius.GetValue() );
492 
493     m_settings.m_ZonePriority = m_PriorityLevelCtrl->GetValue();
494 
495     m_settings.m_Zone_45_Only = m_constrainOutline->GetValue();
496     m_settings.m_Locked = m_cbLocked->GetValue();
497 
498     m_settings.m_ThermalReliefGap = m_antipadClearance.GetValue();
499     m_settings.m_ThermalReliefSpokeWidth = m_spokeWidth.GetValue();
500 
501     if( m_settings.m_ThermalReliefSpokeWidth < m_settings.m_ZoneMinThickness )
502     {
503         DisplayError( this, _( "Thermal spoke width cannot be smaller than the minimum width." ) );
504         return false;
505     }
506 
507     storePersistentNetSortConfigurations();
508     cfg->m_Zones.clearance                   = Iu2Mils( m_settings.m_ZoneClearance );
509     cfg->m_Zones.min_thickness               = Iu2Mils( m_settings.m_ZoneMinThickness );
510     cfg->m_Zones.thermal_relief_gap          = Iu2Mils( m_settings.m_ThermalReliefGap );
511     cfg->m_Zones.thermal_relief_copper_width = Iu2Mils( m_settings.m_ThermalReliefSpokeWidth );
512 
513     m_settings.SetIslandRemovalMode(
514             static_cast<ISLAND_REMOVAL_MODE>( m_cbRemoveIslands->GetSelection() ) );
515     m_settings.SetMinIslandArea( m_islandThreshold.GetValue() );
516 
517     // If we use only exportable to others zones parameters, exit here:
518     if( aUseExportableSetupOnly )
519         return true;
520 
521     // Get the layer selection for this zone
522     int layers = 0;
523 
524     for( int ii = 0; ii < m_layers->GetItemCount(); ++ii )
525     {
526         if( m_layers->GetToggleValue( (unsigned) ii, 0 ) )
527             layers++;
528     }
529 
530     if( layers == 0 )
531     {
532         DisplayError( this, _( "No layer selected." ) );
533         return false;
534     }
535 
536     m_settings.m_NetcodeSelection = m_currentlySelectedNetcode;
537 
538     m_settings.m_Name = m_tcZoneName->GetValue();
539 
540     return true;
541 }
542 
543 
updateCurrentNetSelection()544 void DIALOG_COPPER_ZONE::updateCurrentNetSelection()
545 {
546     const int netSelection{ m_ListNetNameSelection->GetSelection() };
547 
548     if( netSelection )
549     {
550         const wxString& selectedNetName = m_ListNetNameSelection->GetString( netSelection );
551         m_currentlySelectedNetcode = m_netNameToNetCode[selectedNetName];
552     }
553     else
554     {
555         m_currentlySelectedNetcode = INVALID_NET_CODE;
556     }
557 }
558 
559 
OnStyleSelection(wxCommandEvent & event)560 void DIALOG_COPPER_ZONE::OnStyleSelection( wxCommandEvent& event )
561 {
562     bool enable = m_GridStyleCtrl->GetSelection() >= 1;
563     m_tcGridStyleThickness->Enable( enable );
564     m_tcGridStyleGap->Enable( enable );
565     m_tcGridStyleOrientation->Enable( enable );
566     m_spinCtrlSmoothLevel->Enable( enable );
567     m_spinCtrlSmoothValue->Enable( enable );
568 }
569 
570 
OnLayerSelection(wxDataViewEvent & event)571 void DIALOG_COPPER_ZONE::OnLayerSelection( wxDataViewEvent& event )
572 {
573     if( event.GetColumn() != 0 )
574         return;
575 
576     int row = m_layers->ItemToRow( event.GetItem() );
577 
578     bool checked = m_layers->GetToggleValue( row, 0 );
579 
580     wxVariant layerID;
581     m_layers->GetValue( layerID, row, 2 );
582 
583     m_settings.m_Layers.set( ToLAYER_ID( layerID.GetInteger() ), checked );
584 }
585 
586 
OnNetSortingOptionSelected(wxCommandEvent & event)587 void DIALOG_COPPER_ZONE::OnNetSortingOptionSelected( wxCommandEvent& event )
588 {
589     updateDisplayedListOfNets();
590 }
591 
592 
storePersistentNetSortConfigurations()593 void DIALOG_COPPER_ZONE::storePersistentNetSortConfigurations()
594 {
595     // These configurations are persistent across multiple invokations of
596     // this dialog
597     int newConfig{ NO_PERSISTENT_SORT_MODE };
598 
599     if( m_hideAutoGeneratedNets )
600     {
601         newConfig |= HIDE_ANONYMOUS_NETS;
602     }
603 
604     if( m_netSortingByPadCount )
605     {
606         newConfig |= SORT_BY_PAD_COUNT;
607     }
608 
609     PCBNEW_SETTINGS* cfg = m_Parent->GetPcbNewSettings();
610     cfg->m_Zones.net_sort_mode = newConfig;
611 }
612 
613 
loadPersistentNetSortConfigurations()614 void DIALOG_COPPER_ZONE::loadPersistentNetSortConfigurations()
615 {
616     PCBNEW_SETTINGS* cfg{ m_Parent->GetPcbNewSettings() };
617     int savedConfig{ cfg->m_Zones.net_sort_mode };
618 
619     if( savedConfig == DEFAULT_SORT_CONFIG )
620     {
621         savedConfig = HIDE_ANONYMOUS_NETS;
622     }
623 
624     m_hideAutoGeneratedNets = ( savedConfig & HIDE_ANONYMOUS_NETS );
625     m_netSortingByPadCount = ( savedConfig & SORT_BY_PAD_COUNT );
626 }
627 
628 
ExportSetupToOtherCopperZones(wxCommandEvent & event)629 void DIALOG_COPPER_ZONE::ExportSetupToOtherCopperZones( wxCommandEvent& event )
630 {
631     if( !AcceptOptions( true ) )
632         return;
633 
634     // Export settings ( but layer and netcode ) to others copper zones
635     BOARD* pcb = m_Parent->GetBoard();
636 
637     for( ZONE* zone : pcb->Zones() )
638     {
639         // Cannot export settings from a copper zone
640         // to a zone keepout:
641         if( zone->GetIsRuleArea() )
642             continue;
643 
644         m_settings.ExportSetting( *zone, false );  // false = partial export
645         m_settingsExported = true;
646         m_Parent->OnModify();
647     }
648 }
649 
650 
OnShowNetNameFilterChange(wxCommandEvent & event)651 void DIALOG_COPPER_ZONE::OnShowNetNameFilterChange( wxCommandEvent& event )
652 {
653     updateDisplayedListOfNets();
654 }
655 
656 
updateDisplayedListOfNets()657 void DIALOG_COPPER_ZONE::updateDisplayedListOfNets()
658 {
659     readFilteringAndSortingCriteria();
660 
661     wxArrayString listOfNets = buildListOfNetsToDisplay();
662 
663     const int selectedNet = ensureSelectedNetIsVisible( m_currentlySelectedNetcode, listOfNets );
664 
665     displayNetsList( listOfNets, selectedNet );
666 }
667 
668 
readFilteringAndSortingCriteria()669 void DIALOG_COPPER_ZONE::readFilteringAndSortingCriteria()
670 {
671     updateShowNetsFilter();
672 
673     // Hide nets filter criteria
674     m_hideAutoGeneratedNets = m_hideAutoGenNetNamesOpt->GetValue();
675 
676     // Nets sort criteria
677     m_netSortingByPadCount = m_sortByPadsOpt->GetValue();
678 }
679 
680 
updateShowNetsFilter()681 void DIALOG_COPPER_ZONE::updateShowNetsFilter()
682 {
683     wxString netNameShowFilter = m_ShowNetNameFilter->GetValue();
684 
685     if( netNameShowFilter.Len() == 0 )
686     {
687         netNameShowFilter = wxT( "*" );
688     }
689 
690     wxStringTokenizer showFilters( netNameShowFilter.Lower(), "," );
691 
692     m_showNetsFilter.clear();
693 
694     while( showFilters.HasMoreTokens() )
695     {
696         wxString filter = showFilters.GetNextToken();
697         filter.Trim( false );
698         filter.Trim( true );
699 
700         if( !filter.IsEmpty() )
701         {
702             m_showNetsFilter.emplace_back( std::make_unique<EDA_PATTERN_MATCH_WILDCARD>() );
703             m_showNetsFilter.back()->SetPattern( filter );
704         }
705     }
706 }
707 
708 
buildListOfNetsToDisplay()709 wxArrayString DIALOG_COPPER_ZONE::buildListOfNetsToDisplay()
710 {
711     sortNetsIfRequired();
712 
713     const wxArrayString sortedNetNames = getSortedNetNamesList();
714 
715     const wxArrayString netsAfterShowFilter = applyShowFilter( sortedNetNames );
716 
717     wxArrayString filteredNetNames = applyHideFilterIfRequired( netsAfterShowFilter );
718 
719     return filteredNetNames;
720 }
721 
722 
sortNetsIfRequired()723 void DIALOG_COPPER_ZONE::sortNetsIfRequired()
724 {
725     if( m_netSortingByPadCount )
726     {
727         sortNetsByPadCount( m_netInfoItemList, m_maxNetCode );
728     }
729     else
730     {
731         sort( m_netInfoItemList.begin(), m_netInfoItemList.end(), sortNetsByNames );
732     }
733 }
734 
735 
sortNetsByPadCount(std::vector<NETINFO_ITEM * > & nets,const int maxNetCode)736 void DIALOG_COPPER_ZONE::sortNetsByPadCount( std::vector<NETINFO_ITEM*>& nets,
737                                              const int                   maxNetCode )
738 {
739     const std::vector<PAD*> pads = m_Parent->GetBoard()->GetPads();
740 
741     padCountListByNet.clear();
742 
743     // +1 is required for <no-net> item
744     padCountListByNet.assign( maxNetCode + 1, 0 );
745 
746     for( PAD* pad : pads )
747     {
748         const int netCode = pad->GetNetCode();
749 
750         if( netCode > INVALID_NET_CODE )
751             padCountListByNet[netCode]++;
752     }
753 
754     sort( nets.begin(), nets.end(), sortNetsByNodes );
755 }
756 
757 
getSortedNetNamesList()758 wxArrayString DIALOG_COPPER_ZONE::getSortedNetNamesList()
759 {
760     wxArrayString sortedNetNames;
761 
762     for( NETINFO_ITEM* net : m_netInfoItemList )
763     {
764         const wxString& netName = getUnescapedNetName( net );
765         sortedNetNames.Add( netName );
766     }
767 
768     return sortedNetNames;
769 }
770 
771 
applyShowFilter(const wxArrayString & netNames)772 wxArrayString DIALOG_COPPER_ZONE::applyShowFilter( const wxArrayString& netNames )
773 {
774     wxArrayString netsAfterShowFilter;
775 
776     for( const wxString& netName : netNames )
777     {
778         for( const NET_FILTER& filter : m_showNetsFilter )
779         {
780             if( filter->Find( netName.Lower() ) )
781             {
782                 netsAfterShowFilter.Add( netName );
783             }
784         }
785     }
786 
787     return netsAfterShowFilter;
788 }
789 
790 
applyHideFilterIfRequired(const wxArrayString & netNames)791 wxArrayString DIALOG_COPPER_ZONE::applyHideFilterIfRequired( const wxArrayString& netNames )
792 {
793     wxArrayString filteredNetNames;
794 
795     if( m_hideAutoGeneratedNets )
796     {
797         for( const wxString& netName : netNames )
798         {
799             if( !isAutoGenerated( netName ) )
800             {
801                 filteredNetNames.Add( netName );
802             }
803         }
804     }
805     else
806     {
807         filteredNetNames = netNames;
808     }
809 
810     filteredNetNames.Insert( wxT( "<no net>" ), INVALID_NET_CODE );
811 
812     return filteredNetNames;
813 }
814 
815 
isAutoGenerated(const wxString & netName)816 bool DIALOG_COPPER_ZONE::isAutoGenerated( const wxString& netName )
817 {
818     return netName.StartsWith( "Net-(" ) || netName.StartsWith( "unconnected-(" );
819 }
820 
821 
displayNetsList(const wxArrayString & netNamesList,int selectIndex)822 void DIALOG_COPPER_ZONE::displayNetsList( const wxArrayString& netNamesList, int selectIndex )
823 {
824     m_ListNetNameSelection->Clear();
825     m_ListNetNameSelection->InsertItems( netNamesList, 0 );
826     m_ListNetNameSelection->SetSelection( selectIndex );
827     m_ListNetNameSelection->EnsureVisible( selectIndex );
828 }
829 
830 
ensureSelectedNetIsVisible(int selectedNetCode,wxArrayString & netsList)831 int DIALOG_COPPER_ZONE::ensureSelectedNetIsVisible( int selectedNetCode, wxArrayString& netsList )
832 {
833     int selectedIndex = 0;
834     if( selectedNetCode > INVALID_NET_CODE )
835     {
836         NETINFO_ITEM* selectedNet = m_Parent->GetBoard()->FindNet( selectedNetCode );
837 
838         if( selectedNet )
839         {
840             const wxString& netName = getUnescapedNetName( selectedNet );
841             selectedIndex = netsList.Index( netName );
842 
843             if( wxNOT_FOUND == selectedIndex )
844             {
845                 // the currently selected net must *always* be visible.
846 		        // <no net> is the zero'th index, so pick next lowest
847                 netsList.Insert( netName, 1 );
848                 selectedIndex = 1;
849             }
850         }
851     }
852 
853     return selectedIndex;
854 }
855 
856 
getUnescapedNetName(const NETINFO_ITEM * net)857 wxString DIALOG_COPPER_ZONE::getUnescapedNetName( const NETINFO_ITEM* net )
858 {
859     return UnescapeString( net->GetNetname() );
860 }
861 
862 
updateInfoBar()863 void DIALOG_COPPER_ZONE::updateInfoBar()
864 {
865     if( m_currentlySelectedNetcode <= INVALID_NET_CODE && !m_copperZoneInfo->IsShown() )
866     {
867         m_copperZoneInfo->ShowMessage(
868                 _( "Selecting <no net> will create an isolated copper island." ), wxICON_WARNING );
869     }
870     else if( m_currentlySelectedNetcode > INVALID_NET_CODE && m_copperZoneInfo->IsShown() )
871     {
872         m_copperZoneInfo->Dismiss();
873     }
874 }
875