KiCad PCB EDA Suite
Loading...
Searching...
No Matches
constraint_rules_list.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * 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, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <board.h>
23#include <confirm.h>
24#include <dialog_shim.h>
25#include <pcb_edit_frame.h>
26#include <drc/drc_engine.h>
27#include <drc/drc_rule.h>
29#include <drc/drc_rule_parser.h>
31#include <base_units.h>
32#include <eda_units.h>
38#include <netclass.h>
39#include <project.h>
42#include <tool/actions.h>
43#include <tool/tool_manager.h>
44#include <tools/drc_tool.h>
45#include <bitmaps.h>
47#include <widgets/ui_common.h>
48#include <wx/stattext.h>
49#include <wx/button.h>
50#include <wx/dcclient.h>
51#include <wx/regex.h>
52#include <wx/settings.h>
53#include <wx/listctrl.h>
54#include <wx/scrolwin.h>
55#include <wx/sizer.h>
56#include <wx/toplevel.h>
57#include <algorithm>
58
59
61 DRC_RULE_EDITOR_CONSTRAINT_NAME aType, const wxString& aTitle ) :
63 m_frame( aFrame ),
64 m_document( aDocument ),
65 m_type( aType ),
66 m_title( aTitle ),
67 m_titleWindow( nullptr ),
68 m_editor( nullptr )
69{
70 m_list->AppendColumn( wxS( "#" ), wxLIST_FORMAT_RIGHT, 36 );
71 m_list->AppendColumn( _( "Name" ), wxLIST_FORMAT_LEFT, 160 );
72 m_list->AppendColumn( _( "Condition" ), wxLIST_FORMAT_LEFT, 280 );
73 m_list->AppendColumn( _( "Layers" ), wxLIST_FORMAT_LEFT, 120 );
74 m_list->AppendColumn( _( "Constraint" ), wxLIST_FORMAT_LEFT, 240 );
75
76 m_emptyLabel->SetFont( KIUI::GetInfoFont( this ).Italic() );
77
83
84 m_primaryBtn->SetMinSize( wxSize( m_primaryBtn->GetBestSize().x + FromDIP( 16 ), -1 ) );
85
86 m_primaryBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onPrimary, this );
87 m_newBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onNewRule, this );
88 m_upBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onMoveUp, this );
89 m_downBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onMoveDown, this );
90 m_duplicateBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onDuplicate, this );
91 m_removeBtn->Bind( wxEVT_BUTTON, &CONSTRAINT_RULES_LIST::onRemove, this );
92
93 // The editor is rebuilt per rule, so undo would keep pointers to destroyed controls
94 if( DIALOG_SHIM* dlg = dynamic_cast<DIALOG_SHIM*>( wxGetTopLevelParent( this ) ) )
95 dlg->ExcludeFromControlUndoRedo( m_editorHost );
96
97 m_list->Bind( wxEVT_SIZE,
98 [this]( wxSizeEvent& aEvent )
99 {
100 // Fitting toggles the horizontal scrollbar, which resizes the list again
101 if( m_list->GetClientSize().x != m_fittedWidth )
102 fitColumns();
103
104 aEvent.Skip();
105 } );
106 m_list->Bind( wxEVT_LIST_ITEM_SELECTED,
107 [this]( wxListEvent& )
108 {
109 if( !m_refreshing && selectedIndex() >= 0 && selectedIndex() != editingIndex()
110 && !EditRule( selectedIndex() ) )
111 {
112 if( editingIndex() >= 0 )
113 {
114 selectIndex( editingIndex() );
115 }
116 else
117 {
118 for( long i = 0; i < m_list->GetItemCount(); ++i )
119 m_list->SetItemState( i, 0, wxLIST_STATE_SELECTED );
120 }
121 }
122
124 } );
125 m_list->Bind( wxEVT_LIST_ITEM_ACTIVATED,
126 [this]( wxListEvent& aEvent )
127 {
128 long row = aEvent.GetIndex();
129
130 if( row >= 0 && row < (long) m_rowToIndex.size() && m_rowToIndex[row] == NETCLASS_ROW )
131 {
132 if( PAGED_DIALOG* dialog = PAGED_DIALOG::GetDialog( this ) )
133 dialog->ShowPage( _( "Net Classes" ) );
134
135 return;
136 }
137
138 aEvent.Skip();
139 } );
140 m_list->Bind( wxEVT_LIST_ITEM_DESELECTED,
141 [this]( wxListEvent& )
142 {
143 updateButtons();
144 } );
145 m_list->Bind( wxEVT_LIST_KEY_DOWN,
146 [this]( wxListEvent& aEvent )
147 {
148 wxCommandEvent dummy;
149
150 switch( aEvent.GetKeyCode() )
151 {
152 case WXK_DELETE:
153 case WXK_BACK: onRemove( dummy ); break;
154 default: aEvent.Skip();
155 }
156 } );
157
158 showNewRule();
159 RefreshRules();
160}
161
162
164{
165 wxString blocker;
166
167 if( m_frame->GetBoard()->GetDesignRulesPath().IsEmpty() )
168 blocker = _( "Design rules cannot be added without a project" );
169 else if( m_document->HasUnparsedText() )
170 blocker = _( "The custom rules text does not parse. Fix it on the Custom Rules page first." );
171
172 m_refreshing = true;
173 m_list->DeleteAllItems();
174 m_rowToIndex.clear();
175
176 // A net class value is read before any rule written here, so it is listed above them
177 int row = addNetclassRows();
178 int rules = 0;
179
180 if( blocker.IsEmpty() )
181 {
182 for( int index : m_document->IndicesFor( m_type ) )
183 {
184 const DRC_RE_LOADED_PANEL_ENTRY& entry = m_document->Entries()[index];
185
186 long item = m_list->InsertItem( row, wxString::Format( wxS( "%d" ), ++rules ) );
187 m_list->SetItem( item, 1, entry.ruleName );
188 m_list->SetItem( item, 2, entry.condition );
189 m_list->SetItem( item, 3, layersText( entry ) );
190 m_list->SetItem( item, 4,
191 ConstraintText( entry, m_type, m_frame ) + severityText( entry )
192 + sharedWithText( index ) );
193
194 m_rowToIndex.push_back( index );
195 row++;
196 }
197 }
198
199 bool anyRows = !m_rowToIndex.empty();
200 bool anyRules = rules > 0;
201
202 // The count is of the rules this page writes. A net class value is listed, not written here.
203 if( m_titleWindow )
204 m_titleWindow->SetLabel( anyRules ? wxString::Format( wxS( "%s (%d)" ), m_title, rules ) : m_title );
205
206 m_emptyLabel->SetLabel( blocker.IsEmpty() ? _( "No rules yet." ) : blocker );
207
208 m_list->Show( anyRows );
209 m_emptyLabel->Show( !anyRows );
210 m_editorHost->Show( blocker.IsEmpty() );
211 m_primaryBtn->Show( blocker.IsEmpty() );
212 m_newBtn->Show( blocker.IsEmpty() );
213 m_upBtn->Show( anyRules );
214 m_downBtn->Show( anyRules );
215 m_duplicateBtn->Show( anyRules );
216 m_removeBtn->Show( anyRules );
217
218 if( editingIndex() >= 0 )
219 {
220 // A sibling page may have changed the rule's name, condition or layers since the form was filled
221 if( m_editor && !m_editor->IsModified() )
222 {
223 copyRuleData( *m_editor->GetConstraintData(), *m_editingData );
224 m_editor->TransferDataToWindow();
225 }
226
228 }
229 else if( m_editingData && !m_editingData->IsNew() )
230 {
231 showNewRule();
232 }
233 else
234 {
235 for( long i = 0; i < m_list->GetItemCount(); ++i )
236 m_list->SetItemState( i, 0, wxLIST_STATE_SELECTED );
237 }
238
239 m_refreshing = false;
240
241 fitColumns();
243 relayout();
244}
245
246
248{
249 m_fittedWidth = m_list->GetClientSize().x;
250
251 wxClientDC dc( m_list );
252 dc.SetFont( m_list->GetFont() );
253
254 for( int col : { 1, 3, 4 } )
255 {
256 wxListItem header;
257 header.SetMask( wxLIST_MASK_TEXT );
258 m_list->GetColumn( col, header );
259
260 int width = dc.GetTextExtent( header.GetText() ).x;
261
262 for( long row = 0; row < m_list->GetItemCount(); ++row )
263 width = std::max( width, dc.GetTextExtent( m_list->GetItemText( row, col ) ).x );
264
265 m_list->SetColumnWidth( col, std::max( width + 40, 90 ) );
266 }
267
268 // Give the name and value columns a share of the width and let the condition take what
269 // is left, so the last column is never pushed off the edge.
270 int client = m_list->GetClientSize().x - 4;
271
272 m_list->SetColumnWidth( 1, std::min( m_list->GetColumnWidth( 1 ), client / 4 ) );
273 m_list->SetColumnWidth( 4, std::min( m_list->GetColumnWidth( 4 ), client * 2 / 5 ) );
274
275 int others = m_list->GetColumnWidth( 0 ) + m_list->GetColumnWidth( 1 ) + m_list->GetColumnWidth( 3 )
276 + m_list->GetColumnWidth( 4 );
277
278 m_list->SetColumnWidth( 2, std::max( client - others, 160 ) );
279}
280
281
282void CONSTRAINT_RULES_LIST::SetNetclasses( std::function<std::optional<int>( const NETCLASS& )> aValue,
284{
285 m_netclassValue = std::move( aValue );
286 m_netclassPart = aPart;
287}
288
289
291{
292 if( !m_netclassValue )
293 return 0;
294
295 const NET_SETTINGS& netSettings = *m_frame->Prj().GetProjectFile().NetSettings();
296 int row = 0;
297
298 // The default class first, then the rest, which is the order DRC builds them in
299 std::vector<std::shared_ptr<NETCLASS>> classes = { netSettings.GetDefaultNetclass() };
300
301 for( const auto& [name, netclass] : netSettings.GetNetclasses() )
302 classes.push_back( netclass );
303
304 for( const std::shared_ptr<NETCLASS>& netclass : classes )
305 {
306 if( !netclass )
307 continue;
308
309 std::optional<int> value = m_netclassValue( *netclass );
310
311 if( !value )
312 continue;
313
314 // The condition DRC gives the rule it builds for the class, so the row reads like a rule
315 wxString condition = wxString::Format( wxS( "A.hasExactNetclass('%s')" ), netclass->GetName() );
316
317 // A class raises the minimum for some constraints and asks for a value in others, and the
318 // row has to say which, since only the first displaces the board default. The clause is
319 // written the way the rule rows below it write theirs.
320 wxString constraint = wxString::Format( m_netclassPart == NETCLASS_CONSTRAINT_PART::MINIMUM ? wxS( "(min %s)" )
321 : wxS( "(opt %s)" ),
322 m_frame->StringFromValue( *value, true ) );
323
324 long item = m_list->InsertItem( row, wxEmptyString );
325 m_list->SetItem( item, 1, wxString::Format( _( "Net class '%s'" ), netclass->GetName() ) );
326 m_list->SetItem( item, 2, condition );
327 m_list->SetItem( item, 3, _( "Any" ) );
328 m_list->SetItem( item, 4, constraint );
329
330 // The row is not a rule of this document and cannot be edited here, so it is muted
331 m_list->SetItemTextColour( item, wxSystemSettings::GetColour( wxSYS_COLOUR_GRAYTEXT ) );
332
333 m_rowToIndex.push_back( NETCLASS_ROW );
334 row++;
335 }
336
337 return row;
338}
339
340
342{
343 return aEntry.layerSource.IsEmpty() ? _( "Any" ) : aEntry.layerSource;
344}
345
346
347wxString CONSTRAINT_RULES_LIST::inUserUnits( const wxString& aClause, UNITS_PROVIDER* aUnits )
348{
349 // Rule text carries the units it was typed with. Show every number the way the rest of the
350 // page shows one, so a column read down does not mix "0.25mm" with "0.13 mm".
351 static wxRegEx units( wxS( "([0-9]+(\\.[0-9]+)?)(mm|um|mil|in)\\b" ), wxRE_ADVANCED );
352
353 wxString result;
354 wxString rest = aClause;
355
356 while( units.Matches( rest ) )
357 {
358 size_t start, length;
359 units.GetMatch( &start, &length );
360
361 double value =
363
364 result << rest.Left( start ) << aUnits->StringFromValue( value, true );
365 rest = rest.Mid( start + length );
366 }
367
368 return result + rest;
369}
370
371
374{
375 if( aEntry.panelType == CUSTOM_RULE )
376 {
377 auto custom = std::dynamic_pointer_cast<DRC_RE_CUSTOM_RULE_CONSTRAINT_DATA>( aEntry.constraintData );
378 wxString text = custom ? custom->GetRuleText() : aEntry.originalRuleText;
379 wxString code = DRC_RULE_EDITOR_UTILS::ConstraintToKicadDrc( aType );
380 size_t start = DRC_RULE_DOCUMENT::FindConstraintClause( text, code );
381
382 if( start == wxString::npos )
383 return _( "Custom rule" );
384
385 size_t body = start + wxString( wxS( "(constraint" ) ).length();
386
387 while( body < text.length() && wxIsspace( text[body] ) )
388 body++;
389
390 body += code.length();
391
392 int depth = 0;
393
394 for( size_t i = start; i < text.length(); ++i )
395 {
396 if( text[i] == '(' )
397 depth++;
398 else if( text[i] == ')' && --depth == 0 )
399 {
400 wxString clause = text.Mid( body, i - body );
401 clause.Replace( wxS( "\n" ), wxS( " " ) );
402 clause.Replace( wxS( "\t" ), wxS( " " ) );
403 return inUserUnits( clause.Trim( true ).Trim( false ), aUnits ) + _( " (text rule)" );
404 }
405 }
406
407 return _( "Custom rule" );
408 }
409
411 context.ruleName = aEntry.ruleName;
412 context.conditionExpression = aEntry.condition;
414
415 const wxString opener = wxS( "(constraint " );
416 std::vector<wxString> clauses = aEntry.constraintData->GetConstraintClauses( context );
417 wxString text;
418
419 for( wxString clause : clauses )
420 {
421 if( clause.StartsWith( opener ) && clause.EndsWith( wxS( ")" ) ) )
422 {
423 wxString body = clause.Mid( opener.length(), clause.length() - opener.length() - 1 );
424 wxString code = body.BeforeFirst( ' ' );
425 wxString rest = body.AfterFirst( ' ' );
426
427 clause = clauses.size() > 1 ? code + wxS( " " ) + rest : rest;
428 }
429
430 if( !text.IsEmpty() )
431 text << wxS( " " );
432
433 text << clause;
434 }
435
436 return inUserUnits( text, aUnits );
437}
438
439
441{
442 long row = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED );
443
444 if( row < 0 || row >= (long) m_rowToIndex.size() )
445 return -1;
446
447 return m_rowToIndex[row];
448}
449
450
452{
453 // NETCLASS_ROW would match a row that is not a rule of this document
454 if( aIndex < 0 )
455 {
457 return;
458 }
459
460 for( size_t row = 0; row < m_rowToIndex.size(); ++row )
461 {
462 if( m_rowToIndex[row] == aIndex )
463 {
464 m_list->SetItemState( (long) row, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
465 m_list->EnsureVisible( (long) row );
466 break;
467 }
468 }
469
471}
472
473
475{
476 bool editingExisting = editingIndex() >= 0;
477 bool hasSelection = selectedIndex() >= 0;
478
479 wxString label = editingExisting ? _( "Apply" ) : _( "Add Rule" );
480
481 m_primaryBtn->SetToolTip( editingExisting ? _( "Save the form back to the selected rule." )
482 : _( "Check the form and add it to the list of rules above." ) );
483
484 if( m_primaryBtn->GetLabel() != label )
485 {
486 m_primaryBtn->SetLabel( label );
487 m_primaryBtn->SetBitmap( KiBitmapBundle( editingExisting ? BITMAPS::small_edit : BITMAPS::small_plus ) );
488 }
489
490 m_newBtn->Enable( editingExisting );
491
492 m_upBtn->Enable( hasSelection );
493 m_downBtn->Enable( hasSelection );
494 m_duplicateBtn->Enable( hasSelection );
495 m_removeBtn->Enable( hasSelection );
496}
497
498
499void CONSTRAINT_RULES_LIST::onPrimary( wxCommandEvent& aEvent )
500{
501 if( m_editor )
502 m_editor->Save( aEvent );
503}
504
505
506void CONSTRAINT_RULES_LIST::onNewRule( wxCommandEvent& aEvent )
507{
508 if( !ConfirmPendingRule() )
509 return;
510
511 showNewRule();
512 RefreshRules();
513}
514
515
517{
518 return m_editor && m_editor->IsModified();
519}
520
521
523{
524 if( !HasPendingRule() )
525 return true;
526
527 if( !m_editor->ValidateRule() )
528 {
529 reportError( m_editor->GetValidationMessage() );
530 return false;
531 }
532
533 if( editingIndex() >= 0 )
534 applyRule();
535 else
536 addRule();
537
538 return true;
539}
540
541
543{
544 if( !HasPendingRule() )
545 return true;
546
547 bool existing = editingIndex() >= 0;
548
550 existing ? _( "Changes to this rule are still in the form. Only the rules in "
551 "the list apply." )
552 : _( "This rule is still in the form. Only the rules in the "
553 "list apply." ),
554 existing ? _( "Rule Not Applied" ) : _( "Rule Not Added" ),
555 wxYES_NO | wxCANCEL | wxYES_DEFAULT | wxICON_WARNING | wxCENTRE );
556
557 dlg.SetYesNoCancelLabels( existing ? _( "Apply" ) : _( "Add Rule" ), _( "Discard" ), _( "Cancel" ) );
558
559 int choice = dlg.ShowModal();
560
561 if( choice == wxID_YES )
562 return ApplyPendingRule();
563
564 if( choice == wxID_CANCEL )
565 return false;
566
568
569 return true;
570}
571
572
574{
575 // Taking the values back from the document is what drops anything typed since, and it leaves
576 // the page showing what the rule actually holds.
577 if( int index = editingIndex(); index >= 0 )
578 showRule( index );
579 else
580 showNewRule();
581}
582
583
585{
586 int index = selectedIndex();
587
588 if( index < 0 )
589 return;
590
591 // The move renumbers the entries, so the rule is found again by its data rather than its
592 // old index.
593 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> data = m_document->Entries()[index].constraintData;
594
595 if( m_document->Move( index, aDelta, m_type ) )
596 {
598 selectIndex( indexOf( data ) );
599 }
600}
601
602
603void CONSTRAINT_RULES_LIST::onMoveUp( wxCommandEvent& aEvent )
604{
605 moveSelected( -1 );
606}
607
608
609void CONSTRAINT_RULES_LIST::onMoveDown( wxCommandEvent& aEvent )
610{
611 moveSelected( 1 );
612}
613
614
615void CONSTRAINT_RULES_LIST::onDuplicate( wxCommandEvent& aEvent )
616{
617 int index = selectedIndex();
618
619 if( index < 0 )
620 return;
621
622 // Applying the form can renumber the entries, so the rule is found again by its data
623 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> source = m_document->Entries()[index].constraintData;
624
625 if( !ConfirmPendingRule() )
626 return;
627
628 int copy = m_document->Duplicate( indexOf( source ) );
629
630 if( copy < 0 )
631 return;
632
633 showRule( copy );
635}
636
637
638void CONSTRAINT_RULES_LIST::onRemove( wxCommandEvent& aEvent )
639{
640 int index = selectedIndex();
641
642 if( index < 0 )
643 return;
644
645 const DRC_RE_LOADED_PANEL_ENTRY& entry = m_document->Entries()[index];
646 wxString question;
647
648 if( entry.panelType == CUSTOM_RULE )
649 {
650 question = _( "Delete rule '%s'? It is a text rule and every constraint it sets goes with it." );
651 }
652 else if( !sharedWithText( index ).IsEmpty() )
653 {
654 question = _( "Remove this constraint from rule '%s'? The rule keeps the constraints it shares "
655 "with other pages." );
656 }
657 else
658 {
659 question = _( "Delete rule '%s'?" );
660 }
661
662 if( !IsOK( this, wxString::Format( question, entry.ruleName ) ) )
663 return;
664
665 m_document->Remove( index );
666 showNewRule();
668}
669
670
672{
673 if( !m_editor )
674 return;
675
676 wxString boardDefault;
677
678 // A section with one default is named by the section itself. One with several carries a name
679 // per value, or the note would quote one number under both names.
680 for( const auto& [name, read] : m_defaults )
681 {
682 wxString shown = read ? read() : wxString();
683
684 if( shown.IsEmpty() )
685 continue;
686
687 wxString value = wxString::Format( wxS( "%s %s" ), name, shown );
688
689 boardDefault = boardDefault.IsEmpty() ? value : wxString::Format( _( "%s and %s" ), boardDefault, value );
690 }
691
692 if( boardDefault.IsEmpty() || m_editingType == CUSTOM_RULE )
693 {
694 m_editor->SetOverrideNote( wxEmptyString );
695 return;
696 }
697
698 int index = editingIndex();
699
700 // A rule the form is still writing is not in the document, so it displaces nothing yet and
701 // there is no scope to describe.
702 if( index < 0 || index >= (int) m_document->Entries().size() )
703 {
704 m_editor->SetOverrideNote( wxEmptyString );
705 return;
706 }
707
708 // The scope comes from the form rather than from the entry it was loaded from, so the note
709 // describes the rule being written rather than the one last applied.
710 wxString condition = m_editor->GetCondition();
711 wxString layers = m_editor->GetLayerSource();
712
713 wxString note;
714
715 if( condition.IsEmpty() && layers.IsEmpty() )
716 {
717 note = wxString::Format( _( "Overrides the board default, %s, everywhere" ), boardDefault );
718 }
719 else if( condition.IsEmpty() )
720 {
721 note = wxString::Format( _( "Overrides the board default, %s, on %s" ), boardDefault, layers );
722 }
723 else if( layers.IsEmpty() )
724 {
725 note = wxString::Format( _( "Overrides the board default, %s, where %s" ), boardDefault, condition );
726 }
727 else
728 {
729 note = wxString::Format( _( "Overrides the board default, %s, on %s where %s" ), boardDefault, layers,
730 condition );
731 }
732
733 m_editor->SetOverrideNote( note );
734}
735
736
738 const DRC_RE_BASE_CONSTRAINT_DATA& aSource )
739{
740 // CopyFrom leaves the name alone so a duplicate can keep its own
741 aTarget.CopyFrom( aSource );
742 aTarget.SetRuleName( aSource.GetRuleName() );
743}
744
745
746void CONSTRAINT_RULES_LIST::buildEditor( const std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA>& aData,
748{
749 if( m_editor )
750 {
751 m_editorSizer->Detach( m_editor );
752 m_editor->Destroy();
753 }
754
755 m_editingData = aData;
756 m_editingType = aPanelType;
757
758 // The form edits a copy, so a rejected or discarded value never reaches the document
759 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> draft =
761 copyRuleData( *draft, *aData );
762
763 m_editor = new PANEL_DRC_RULE_EDITOR( m_editorHost, m_frame->GetBoard(), aPanelType, draft );
764 m_editorSizer->Insert( 0, m_editor, 0, wxEXPAND | wxRIGHT, 8 );
765 m_editor->TransferDataToWindow();
766
768
769 // The editor calls back from its own event handlers, so never destroy it inside one.
770 m_editor->SetFieldChangeCallback(
771 [this]()
772 {
774 } );
775 m_editor->SetSaveCallback(
776 [this]( int )
777 {
778 CallAfter(
779 [this]()
780 {
781 if( editingIndex() >= 0 )
782 applyRule();
783 else
784 addRule();
785 } );
786 } );
787 m_editor->SetRuleNameValidationCallback(
788 [this]( int, const wxString& aName )
789 {
790 return m_document->IsRuleNameUnique( aName, m_type, editingIndex() );
791 } );
792 m_editor->SetShowMatchesCallBack(
793 [this]( int )
794 {
795 return showMatches();
796 } );
797
798 relayout();
799}
800
801
803{
804 DRC_RE_BASE_CONSTRAINT_DATA base( m_document->NextId(), m_document->UniqueRuleName( m_title ) );
805 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> data = DRC_RULE_EDITOR_UTILS::CreateConstraintData( m_type, base );
806
807 data->SetConstraintCode( DRC_RULE_EDITOR_UTILS::ConstraintToKicadDrc( m_type ) );
808 data->SetIsNew( true );
809
810 buildEditor( data, m_type );
811
812 if( long selected = m_list->GetNextItem( -1, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED ); selected != wxNOT_FOUND )
813 m_list->SetItemState( selected, 0, wxLIST_STATE_SELECTED );
814
816}
817
818
820{
821 if( aIndex < 0 || aIndex >= (int) m_document->Entries().size() )
822 return false;
823
824 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> target = m_document->Entries()[aIndex].constraintData;
825
826 if( target != m_editingData && !ConfirmPendingRule() )
827 return false;
828
829 // Opened before it is selected, so the selection event finds it already in the editor
830 showRule( indexOf( target ) );
831 selectIndex( indexOf( target ) );
832 return true;
833}
834
835
837{
838 if( aIndex < 0 || aIndex >= (int) m_document->Entries().size() )
839 return;
840
841 const DRC_RE_LOADED_PANEL_ENTRY& entry = m_document->Entries()[aIndex];
842
843 buildEditor( entry.constraintData, entry.panelType );
845}
846
847
849{
850 if( !m_editor->GetIsValidationSucceeded() )
851 {
852 reportError( m_editor->GetValidationMessage() );
853 return;
854 }
855
856 m_editor->TransferDataFromWindow();
857
858 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> data = m_editingData;
859
860 copyRuleData( *data, *m_editor->GetConstraintData() );
861 data->SetIsNew( false );
862
863 DRC_RE_LOADED_PANEL_ENTRY entry( m_type, data, data->GetRuleName(), data->GetRuleCondition(), data->GetSeverity(),
864 LSET( data->GetLayers() ) );
865
866 entry.layerSource = data->GetLayerSource();
867 entry.wasEdited = true;
868 m_document->Add( entry );
870 m_editor->ClearModified();
871}
872
873
875{
876 int index = editingIndex();
877
878 if( index < 0 )
879 return;
880
881 if( !m_editor->GetIsValidationSucceeded() )
882 {
883 reportError( m_editor->GetValidationMessage() );
884 return;
885 }
886
887 m_editor->TransferDataFromWindow();
888
889 DRC_RE_LOADED_PANEL_ENTRY& entry = m_document->Entries()[index];
890 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> data = entry.constraintData;
891
892 // A rule applied with nothing changed stays as it was read.
893 if( !m_editor->IsModified() )
894 return;
895
896 copyRuleData( *data, *m_editor->GetConstraintData() );
897
898 DRC_RE_LOADED_PANEL_ENTRY edited = entry;
899
900 edited.ruleName = data->GetRuleName();
901 edited.condition = data->GetRuleCondition();
902 edited.layerCondition = LSET( data->GetLayers() );
903 edited.layerSource = data->GetLayerSource();
904 edited.severity = data->GetSeverity();
905
906 m_document->UpdateEntry( index, edited );
908 m_editor->ClearModified();
909}
910
911
913{
914 if( !m_editor )
915 return -1;
916
917 // The form edits a copy of the rule, so taking the typed values does not touch the document
918 m_editor->TransferDataFromWindow();
919
920 wxString ruleText = m_editor->GetConstraintData()->GetGeneratedRule();
921
922 if( ruleText.IsEmpty() )
923 {
924 m_frame->FocusOnItems( {} );
925 return 0;
926 }
927
928 std::shared_ptr<DRC_RULE> rule;
929
930 try
931 {
932 std::vector<std::shared_ptr<DRC_RULE>> rules;
933 DRC_RULES_PARSER parser( wxS( "(version 2)\n" ) + ruleText, wxS( "ShowMatches" ) );
934 parser.Parse( rules, nullptr );
935
936 if( rules.empty() )
937 {
938 m_frame->FocusOnItems( {} );
939 return 0;
940 }
941
942 rule = rules[0];
943
944 if( rule->m_Condition && !rule->m_Condition->GetExpression().IsEmpty()
945 && !rule->m_Condition->Compile( nullptr ) )
946 {
947 return -1;
948 }
949 }
950 catch( PARSE_ERROR& )
951 {
952 return -1;
953 }
954
955 DRC_TOOL* drcTool = m_frame->GetToolManager()->GetTool<DRC_TOOL>();
956 std::vector<BOARD_ITEM*> matches;
957
958 for( BOARD_ITEM* item : drcTool->GetDRCEngine()->GetItemsMatchingRule( rule, nullptr ) )
959 {
960 switch( item->Type() )
961 {
962 case PCB_NETINFO_T:
963 case PCB_GENERATOR_T:
964 case PCB_GROUP_T: continue;
965
966 default: matches.push_back( item );
967 }
968 }
969
970 m_frame->GetToolManager()->RunAction( ACTIONS::selectionClear );
971
972 if( !matches.empty() )
973 {
974 std::vector<EDA_ITEM*> selectItems( matches.begin(), matches.end() );
975
976 m_frame->GetToolManager()->RunAction( ACTIONS::selectItems, &selectItems );
977 m_frame->GetToolManager()->RunAction( ACTIONS::zoomFitSelection );
978 }
979
980 m_frame->FocusOnItems( matches );
981
982 return (int) matches.size();
983}
984
985
991
992
993void CONSTRAINT_RULES_LIST::reportError( const wxString& aMessage )
994{
995 if( PAGED_DIALOG* dialog = PAGED_DIALOG::GetDialog( this ) )
996 dialog->SetError( aMessage, this, nullptr );
997 else
998 DisplayErrorMessage( this, aMessage );
999}
1000
1001
1002int CONSTRAINT_RULES_LIST::indexOf( const std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA>& aData ) const
1003{
1004 if( !aData )
1005 return -1;
1006
1007 const std::vector<DRC_RE_LOADED_PANEL_ENTRY>& entries = m_document->Entries();
1008
1009 for( size_t i = 0; i < entries.size(); ++i )
1010 {
1011 if( entries[i].constraintData == aData )
1012 return (int) i;
1013 }
1014
1015 return -1;
1016}
1017
1018
1020{
1021 return indexOf( m_editingData );
1022}
1023
1024
1026{
1027 if( m_onChanged )
1028 m_onChanged();
1029 else
1030 RefreshRules();
1031}
1032
1033
1035{
1036 switch( aEntry.severity )
1037 {
1038 case RPT_SEVERITY_IGNORE: return _( ", not checked" );
1039 case RPT_SEVERITY_WARNING: return _( ", warning only" );
1040 case RPT_SEVERITY_EXCLUSION: return _( ", excluded" );
1041 default: return wxEmptyString;
1042 }
1043}
1044
1045
1046wxString CONSTRAINT_RULES_LIST::sharedWithText( int aIndex ) const
1047{
1048 const std::vector<DRC_RE_LOADED_PANEL_ENTRY>& entries = m_document->Entries();
1049 const DRC_RE_LOADED_PANEL_ENTRY& entry = entries[aIndex];
1050 wxArrayString codes;
1051 wxRegEx code( wxS( "\\(constraint ([a-z_]+)" ) );
1052
1053 for( size_t i = 0; i < entries.size(); ++i )
1054 {
1055 const DRC_RE_LOADED_PANEL_ENTRY& other = entries[i];
1056
1057 if( (int) i == aIndex || other.ruleGroupId <= 0 || other.ruleGroupId != entry.ruleGroupId
1058 || !other.constraintData )
1059 {
1060 continue;
1061 }
1062
1064 ctx.ruleName = other.ruleName;
1065 ctx.conditionExpression = other.condition;
1067
1068 wxString text = other.constraintData->GenerateRule( ctx );
1069
1070 for( const wxString& clause : other.constraintData->GetConstraintClauses( ctx ) )
1071 text << wxS( "\n" ) << clause;
1072
1073 while( code.Matches( text ) )
1074 {
1075 size_t start, length;
1076 code.GetMatch( &start, &length );
1077
1078 if( codes.Index( code.GetMatch( text, 1 ) ) == wxNOT_FOUND )
1079 codes.Add( code.GetMatch( text, 1 ) );
1080
1081 text = text.Mid( start + length );
1082 }
1083 }
1084
1085 if( codes.empty() )
1086 return wxEmptyString;
1087
1088 wxString joined;
1089
1090 for( const wxString& item : codes )
1091 joined << ( joined.IsEmpty() ? wxS( "" ) : wxS( ", " ) ) << item;
1092
1093 return wxString::Format( _( ", shared with %s" ), joined );
1094}
int index
const char * name
constexpr EDA_IU_SCALE pcbIUScale
Definition base_units.h:128
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:106
static TOOL_ACTION zoomFitSelection
Definition actions.h:141
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
static TOOL_ACTION selectItems
Select a list of items (specified as the event parameter)
Definition actions.h:229
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
CONSTRAINT_RULES_LIST_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxTAB_TRAVERSAL, const wxString &name=wxEmptyString)
bool ConfirmPendingRule()
Asks what to do with a rule left in the form.
std::function< void()> m_onChanged
wxString sharedWithText(int aIndex) const
bool EditRule(int aIndex)
Selects a rule and opens it in the editor. False if a rule left in the form kept it closed.
static wxString inUserUnits(const wxString &aClause, UNITS_PROVIDER *aUnits)
void onDuplicate(wxCommandEvent &aEvent)
static wxString ConstraintText(const DRC_RE_LOADED_PANEL_ENTRY &aEntry, DRC_RULE_EDITOR_CONSTRAINT_NAME aType, UNITS_PROVIDER *aUnits)
The constraint a rule sets, written the way the rule table shows it.
int addNetclassRows()
Fills the leading rows with the net class values, and returns how many it added.
std::vector< int > m_rowToIndex
The document index each row shows, or NETCLASS_ROW where the row is a net class value.
void onNewRule(wxCommandEvent &aEvent)
bool ApplyPendingRule()
Adds or updates the rule the form holds.
NETCLASS_CONSTRAINT_PART m_netclassPart
void buildEditor(const std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > &aData, DRC_RULE_EDITOR_CONSTRAINT_NAME aPanelType)
static constexpr int NETCLASS_ROW
What m_rowToIndex holds for a row that is not a rule of this document.
bool HasPendingRule() const
True while the form holds typing that has not been added to the list.
void onRemove(wxCommandEvent &aEvent)
int indexOf(const std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > &aData) const
static void copyRuleData(DRC_RE_BASE_CONSTRAINT_DATA &aTarget, const DRC_RE_BASE_CONSTRAINT_DATA &aSource)
Copies everything the form edits, the rule name included.
void onMoveUp(wxCommandEvent &aEvent)
DRC_RULE_DOCUMENT * m_document
std::function< std::optional< int >(const NETCLASS &)> m_netclassValue
void SetNetclasses(std::function< std::optional< int >(const NETCLASS &)> aValue, NETCLASS_CONSTRAINT_PART aPart)
Lists the net class values for this constraint above the rules, where a class can set one.
std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > m_editingData
DRC_RULE_EDITOR_CONSTRAINT_NAME m_editingType
static wxString layersText(const DRC_RE_LOADED_PANEL_ENTRY &aEntry)
DRC_RULE_EDITOR_CONSTRAINT_NAME m_type
CONSTRAINT_RULES_LIST(wxWindow *aParent, PCB_EDIT_FRAME *aFrame, DRC_RULE_DOCUMENT *aDocument, DRC_RULE_EDITOR_CONSTRAINT_NAME aType, const wxString &aTitle)
PANEL_DRC_RULE_EDITOR * m_editor
std::vector< std::pair< wxString, std::function< wxString()> > > m_defaults
void onPrimary(wxCommandEvent &aEvent)
void reportError(const wxString &aMessage)
void DiscardPendingRule()
Reloads the form from the document, dropping whatever was typed.
void onMoveDown(wxCommandEvent &aEvent)
static wxString severityText(const DRC_RE_LOADED_PANEL_ENTRY &aEntry)
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
Definition dialog_shim.h:81
std::vector< BOARD_ITEM * > GetItemsMatchingRule(const std::shared_ptr< DRC_RULE > &aRule, REPORTER *aReporter=nullptr)
virtual std::vector< wxString > GetConstraintClauses(const RULE_GENERATION_CONTEXT &aContext) const
Returns just the constraint clauses without the rule wrapper.
void CopyFrom(const ICopyable &aSource) override
virtual wxString GenerateRule(const RULE_GENERATION_CONTEXT &aContext)
void Parse(std::vector< std::shared_ptr< DRC_RULE > > &aRules, REPORTER *aReporter)
The custom rules of one board, held in memory while Board Setup is open.
static size_t FindConstraintClause(const wxString &aText, const wxString &aCode)
Position of the constraint clause for aCode in rule text, or npos.
static wxString ConstraintToKicadDrc(DRC_RULE_EDITOR_CONSTRAINT_NAME aType)
Convert a constraint type into the keyword used in a .kicad_drc file.
static std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > CreateConstraintData(DRC_RULE_EDITOR_CONSTRAINT_NAME aType, const DRC_RE_BASE_CONSTRAINT_DATA &aBase)
Create the data object that holds a rule of the given constraint type, taking the identity fields fro...
std::shared_ptr< DRC_ENGINE > GetDRCEngine()
Definition drc_tool.h:79
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
A collection of nets and the parameters used to route or test these nets.
Definition netclass.h:44
NET_SETTINGS stores various net-related settings in a project context.
const std::map< wxString, std::shared_ptr< NETCLASS > > & GetNetclasses() const
Gets all netclasses.
std::shared_ptr< NETCLASS > GetDefaultNetclass() const
Gets the default netclass for the project.
static PAGED_DIALOG * GetDialog(wxWindow *aWindow)
static void LayoutAncestors(wxWindow *aWindow)
Lays out aWindow's parents, out to the page it scrolls in.
The main frame for Pcbnew.
void SetRuleName(wxString aRuleName)
Set the name of the rule.
wxString GetRuleName() const
Get the name of the rule.
wxString StringFromValue(double aValue, bool aAddUnitLabel=false, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts aValue in internal units into a united string.
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define KICAD_MESSAGE_DIALOG_BASE
Definition confirm.h:46
DRC_RULE_EDITOR_CONSTRAINT_NAME
#define _(s)
std::string source
KICOMMON_API double DoubleValueFromString(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits, const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE)
Convert aTextValue to a double.
KICOMMON_API wxFont GetInfoFont(wxWindow *aWindow)
NETCLASS_CONSTRAINT_PART
What a net class value does to a constraint, which is not always raise its minimum.
@ MINIMUM
Raises the minimum, as a net class clearance does.
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_EXCLUSION
@ RPT_SEVERITY_IGNORE
std::vector< FAB_LAYER_COLOR > dummy
Represents a rule loaded from a .kicad_dru file and mapped to a panel.
wxString ruleName
wxString originalRuleText
wxString condition
bool wasEdited
wxString layerSource
Original layer text: "inner", "outer", or layer name.
LSET layerCondition
int ruleGroupId
Shared by entries split out of one rule. Zero when the entry stands alone.
std::shared_ptr< DRC_RE_BASE_CONSTRAINT_DATA > constraintData
DRC_RULE_EDITOR_CONSTRAINT_NAME panelType
SEVERITY severity
A filename or source description, a problem input line, a line number, a byte offset,...
DATABASE_CONNECTION dc(odbcBackend(cs))
wxString result
Test unit parsing edge cases and error handling.
@ PCB_GENERATOR_T
class PCB_GENERATOR, generator on a layer
Definition typeinfo.h:83
@ PCB_GROUP_T
class PCB_GROUP, a set of BOARD_ITEMs
Definition typeinfo.h:103
@ PCB_NETINFO_T
class NETINFO_ITEM, a description of a net
Definition typeinfo.h:102
Functions to provide common constants and other functions to assist in making a consistent UI.