KiCad PCB EDA Suite
Loading...
Searching...
No Matches
panel_setup_rules.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
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, see <https://www.gnu.org/licenses/>.
18 */
19
21#include <bitmaps.h>
22#include <common.h>
25#include <pcb_edit_frame.h>
26#include <pcbexpr_evaluator.h>
27#include <board.h>
29#include <drc/drc_engine.h>
32#include <project.h>
33#include <string_utils.h>
34#include <tool/tool_manager.h>
35#include <panel_setup_rules.h>
38#include <scintilla_tricks.h>
39#include <drc/drc_rule.h>
41#include <drc/drc_rule_parser.h>
42#include <tools/drc_tool.h>
43#include <pgm_base.h>
44#include <regex>
45#include <unordered_map>
46#include <properties/property.h>
48
49PANEL_SETUP_RULES::PANEL_SETUP_RULES( wxWindow* aParentWindow, PCB_EDIT_FRAME* aFrame, DRC_RULE_DOCUMENT* aDocument ) :
50 PANEL_SETUP_RULES_BASE( aParentWindow ),
51 m_frame( aFrame ),
52 m_document( aDocument ),
53 m_scintillaTricks( nullptr ),
54 m_helpWindow( nullptr )
55{
56 m_scintillaTricks = new SCINTILLA_TRICKS( m_textEditor, wxT( "()" ), false,
57 // onAcceptFn
58 [this]( wxKeyEvent& aEvent )
59 {
60 wxPostEvent( PAGED_DIALOG::GetDialog( this ),
61 wxCommandEvent( wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK ) );
62 },
63 // onCharFn
64 [this]( wxStyledTextEvent& aEvent )
65 {
66 onScintillaCharAdded( aEvent );
67 } );
68
69 m_textEditor->AutoCompSetSeparator( '|' );
70
71 m_netClassRegex.Compile( "^NetClass\\s*[!=]=\\s*$", wxRE_ADVANCED );
72 m_netNameRegex.Compile( "^NetName\\s*[!=]=\\s*$", wxRE_ADVANCED );
73 m_typeRegex.Compile( "^Type\\s*[!=]=\\s*$", wxRE_ADVANCED );
74 m_viaTypeRegex.Compile( "^Via_Type\\s*[!=]=\\s*$", wxRE_ADVANCED );
75 m_padTypeRegex.Compile( "^Pad_Type\\s*[!=]=\\s*$", wxRE_ADVANCED );
76 m_pinTypeRegex.Compile( "^Pin_Type\\s*[!=]=\\s*$", wxRE_ADVANCED );
77 m_fabPropRegex.Compile( "^Fabrication_Property\\s*[!=]=\\s*$", wxRE_ADVANCED );
78 m_shapeRegex.Compile( "^Shape\\s*[!=]=\\s*$", wxRE_ADVANCED );
79 m_padShapeRegex.Compile( "^Pad_Shape\\s*[!=]=\\s*$", wxRE_ADVANCED );
80 m_padConnectionsRegex.Compile( "^Pad_Connections\\s*[!=]=\\s*$", wxRE_ADVANCED );
81 m_zoneConnStyleRegex.Compile( "^Zone_Connection_Style\\s*[!=]=\\s*$", wxRE_ADVANCED );
82 m_lineStyleRegex.Compile( "^Line_Style\\s*[!=]=\\s*$", wxRE_ADVANCED );
83 m_hJustRegex.Compile( "^Horizontal_Justification\\s*[!=]=\\s*$", wxRE_ADVANCED );
84 m_vJustRegex.Compile( "^Vertical_Justification\\s*[!=]=\\s*$", wxRE_ADVANCED );
85
87
88 m_textEditor->SetZoom( Pgm().GetCommonSettings()->m_Appearance.text_editor_zoom );
89
90 m_textEditor->UsePopUp( 0 );
91 m_textEditor->Bind( wxEVT_CHAR_HOOK, &PANEL_SETUP_RULES::onCharHook, this );
92}
93
94
96{
97 m_textEditor->Unbind( wxEVT_CHAR_HOOK, &PANEL_SETUP_RULES::onCharHook, this );
99
100 delete m_scintillaTricks;
101 m_scintillaTricks = nullptr;
102
103 if( m_helpWindow )
104 m_helpWindow->Destroy();
105};
106
107
108void PANEL_SETUP_RULES::onCharHook( wxKeyEvent& aEvent )
109{
110 // Route Escape through the dialog's cancel handler so unsaved rules get a discard prompt
111 if( aEvent.GetKeyCode() == WXK_ESCAPE && !m_textEditor->AutoCompActive() )
112 {
113 wxPostEvent( PAGED_DIALOG::GetDialog( this ), wxCommandEvent( wxEVT_COMMAND_BUTTON_CLICKED, wxID_CANCEL ) );
114 return;
115 }
116
117 aEvent.Skip();
118}
119
120
122{
123 if( m_frame->Prj().IsNullProject() || !m_frame->GetBoard() )
124 return false;
125
126 return m_originalText != m_textEditor->GetText();
127}
128
129
130void PANEL_SETUP_RULES::OnContextMenu(wxMouseEvent &event)
131{
132 wxMenu menu;
133
134 menu.Append( wxID_UNDO, _( "Undo" ) );
135 menu.Append( wxID_REDO, _( "Redo" ) );
136
137 menu.AppendSeparator();
138
139 menu.Append( 1, _( "Cut" ) ); // Don't use wxID_CUT, wxID_COPY, etc. On Mac (at least),
140 menu.Append( 2, _( "Copy" ) ); // wxWidgets never delivers them to us.
141 menu.Append( 3, _( "Paste" ) );
142 menu.Append( 4, _( "Delete" ) );
143
144 menu.AppendSeparator();
145
146 menu.Append( 5, _( "Select All" ) );
147
148 menu.AppendSeparator();
149
150 menu.Append( wxID_ZOOM_IN, _( "Zoom In" ) );
151 menu.Append( wxID_ZOOM_OUT, _( "Zoom Out" ) );
152
153 menu.AppendSeparator();
154
155 menu.Append( 6, _( "Show Matching Items" ) );
156
157 switch( GetPopupMenuSelectionFromUser( menu ) )
158 {
159 case wxID_UNDO:
160 m_textEditor->Undo();
161 break;
162 case wxID_REDO:
163 m_textEditor->Redo();
164 break;
165
166 case 1:
167 m_textEditor->Cut();
168 break;
169 case 2:
170 m_textEditor->Copy();
171 break;
172 case 3:
173 m_textEditor->Paste();
174 break;
175 case 4:
176 {
177 long from, to;
178 m_textEditor->GetSelection( &from, &to );
179
180 if( to > from )
181 m_textEditor->DeleteRange( from, to );
182
183 break;
184 }
185
186 case 5:
187 m_textEditor->SelectAll();
188 break;
189
190 case wxID_ZOOM_IN:
191 m_textEditor->ZoomIn();
192 break;
193 case wxID_ZOOM_OUT:
194 m_textEditor->ZoomOut();
195 break;
196
197 case 6: OnShowMatching(); break;
198 }
199}
200
201
203{
204 m_errorsReport->Clear();
205
206 if( m_frame->Prj().IsNullProject() )
207 {
208 m_errorsReport->Report( _( "Cannot show matching items without an open project." ), RPT_SEVERITY_ERROR );
209 m_errorsReport->Flush();
210 return;
211 }
212
213 const wxString text = m_textEditor->GetText();
214 const int cursorPos = m_textEditor->GetCurrentPos();
215 const int cursorLine = m_textEditor->LineFromPosition( cursorPos ) + 1;
216 const int cursorCol = cursorPos - m_textEditor->PositionFromLine( cursorLine - 1 ) + 1;
217
218 std::vector<std::shared_ptr<DRC_RULE>> rules;
219
220 try
221 {
222 std::function<bool( wxString* )> resolver =
223 [&]( wxString* token ) -> bool
224 {
225 if( IsComponentClassSelector( *token ) )
226 return false;
227
228 return m_frame->GetBoard()->ResolveTextVar( token, 0 );
229 };
230
231 wxString rulesText = m_frame->GetBoard()->ConvertCrossReferencesToKIIDs( text );
232 rulesText = ExpandTextVars( rulesText, &resolver, RESOLVED );
233
234 DRC_RULES_PARSER parser( rulesText, _( "DRC rules" ) );
235 parser.Parse( rules, m_errorsReport );
236 }
237 catch( PARSE_ERROR& pe )
238 {
239 m_errorsReport->Report( wxString::Format( wxT( "%s <a href='%d:%d'>%s</a>%s" ), _( "ERROR:" ), pe.lineNumber,
240 pe.byteIndex, pe.ParseProblem(), wxEmptyString ),
242 m_errorsReport->Flush();
243 return;
244 }
245
246 wxString targetRuleName;
247 bool foundRule = false;
248
249 try
250 {
251 std::string utf8( text.mb_str( wxConvUTF8 ) );
252 DRC_RULES_LEXER lex( utf8, _( "DRC rules" ) );
253
254 struct RuleFrame
255 {
256 int depth;
257 int startLine;
258 int startCol;
259 wxString name;
260 };
261
262 std::vector<RuleFrame> ruleStack;
263 int depth = 0;
264
265 for( ;; )
266 {
267 int tok = lex.NextTok();
268
269 if( tok == DSN_EOF )
270 break;
271
272 if( tok == DSN_LEFT )
273 {
274 int leftLine = lex.CurLineNumber();
275 int leftCol = lex.CurOffset();
276
277 depth++;
278
279 int sub = lex.NextTok();
280
281 if( sub == DRCRULE_T::T_rule )
282 {
283 wxString name;
284 int nameTok = lex.NextTok();
285
286 if( DSNLEXER::IsSymbol( nameTok ) )
287 name = wxString::FromUTF8( lex.CurText() );
288
289 ruleStack.push_back( { depth, leftLine, leftCol, name } );
290 }
291 else if( sub == DSN_LEFT )
292 {
293 depth++;
294 }
295 else if( sub == DSN_RIGHT )
296 {
297 depth--;
298 }
299 else if( sub == DSN_EOF )
300 {
301 break;
302 }
303 }
304 else if( tok == DSN_RIGHT )
305 {
306 if( !ruleStack.empty() && ruleStack.back().depth == depth )
307 {
308 RuleFrame opened = ruleStack.back();
309 ruleStack.pop_back();
310
311 int endLine = lex.CurLineNumber();
312 int endCol = lex.CurOffset();
313
314 bool afterStart = cursorLine > opened.startLine
315 || ( cursorLine == opened.startLine && cursorCol >= opened.startCol );
316 bool beforeEnd = cursorLine < endLine || ( cursorLine == endLine && cursorCol <= endCol );
317
318 if( afterStart && beforeEnd )
319 {
320 targetRuleName = opened.name;
321 foundRule = true;
322 break;
323 }
324 }
325
326 depth--;
327 }
328 }
329 }
330 catch( IO_ERROR& e )
331 {
332 m_errorsReport->Report( wxString::Format( _( "Could not scan rules text: %s" ), e.What() ),
334 m_errorsReport->Flush();
335 return;
336 }
337
338 if( !foundRule )
339 {
340 m_errorsReport->Report( _( "Place the cursor inside a (rule ...) block to show matching "
341 "items." ),
343 m_errorsReport->Flush();
344 return;
345 }
346
347 if( targetRuleName.IsEmpty() )
348 {
349 m_errorsReport->Report( _( "The rule under the cursor has no name; add a name to identify "
350 "it." ),
352 m_errorsReport->Flush();
353 return;
354 }
355
356 std::shared_ptr<DRC_RULE> targetRule;
357
358 for( const auto& rule : rules )
359 {
360 if( rule->m_Name == targetRuleName )
361 {
362 targetRule = rule;
363 break;
364 }
365 }
366
367 if( !targetRule )
368 {
369 m_errorsReport->Report( wxString::Format( _( "Rule '%s' could not be located after "
370 "parsing." ),
371 targetRuleName ),
373 m_errorsReport->Flush();
374 return;
375 }
376
377 if( targetRule->m_Condition && !targetRule->m_Condition->GetExpression().IsEmpty()
378 && !targetRule->m_Condition->Compile( m_errorsReport ) )
379 {
380 m_errorsReport->Flush();
381 return;
382 }
383
384 std::shared_ptr<DRC_ENGINE> engine = m_frame->GetBoard()->GetDesignSettings().m_DRCEngine;
385
386 if( !engine )
387 {
388 m_errorsReport->Report( _( "DRC engine not available." ), RPT_SEVERITY_ERROR );
389 m_errorsReport->Flush();
390 return;
391 }
392
393 std::vector<BOARD_ITEM*> allMatches = engine->GetItemsMatchingRule( targetRule, m_errorsReport );
394
395 std::vector<BOARD_ITEM*> matches;
396
397 for( BOARD_ITEM* item : allMatches )
398 {
399 switch( item->Type() )
400 {
401 case PCB_NETINFO_T:
402 case PCB_GENERATOR_T:
403 case PCB_GROUP_T: continue;
404 default: matches.push_back( item ); break;
405 }
406 }
407
408 m_frame->FocusOnItems( matches );
409
410 m_errorsReport->Report(
411 wxString::Format( _( "Rule '%s': %zu matching item(s)." ), targetRule->m_Name, matches.size() ),
413 m_errorsReport->Flush();
414}
415
416
417void PANEL_SETUP_RULES::onScintillaCharAdded( wxStyledTextEvent &aEvent )
418{
419 if( aEvent.GetModifiers() == wxMOD_CONTROL && aEvent.GetKey() == ' ' )
420 {
421 // This is just a short-cut for do-auto-complete
422 }
423 else
424 {
426 }
427
428 m_textEditor->SearchAnchor();
429
430 int currentPos = m_textEditor->GetCurrentPos();
431 int startPos = 0;
432
433 for( int line = m_textEditor->LineFromPosition( currentPos ); line > 0; line-- )
434 {
435 int lineStart = m_textEditor->PositionFromLine( line );
436 wxString beginning = m_textEditor->GetTextRange( lineStart, lineStart + 10 );
437
438 if( beginning.StartsWith( wxT( "(rule " ) ) )
439 {
440 startPos = lineStart;
441 break;
442 }
443 }
444
445 enum
446 {
447 NO_CONTEXT,
448 STRING,
449 SEXPR_OPEN,
450 SEXPR_TOKEN,
451 SEXPR_STRING,
452 STRUCT_REF
453 };
454
455 auto isDisallowToken =
456 []( const wxString& token ) -> bool
457 {
458 return token == wxT( "blind_via" )
459 || token == wxT( "buried_via" )
460 || token == wxT( "graphic" )
461 || token == wxT( "hole" )
462 || token == wxT( "micro_via" )
463 || token == wxT( "pad" )
464 || token == wxT( "text" )
465 || token == wxT( "through_via" )
466 || token == wxT( "track" )
467 || token == wxT( "via" )
468 || token == wxT( "zone" );
469 };
470
471 auto isConstraintTypeToken =
472 []( const wxString& token ) -> bool
473 {
474 return token == wxT( "annular_width" )
475 || token == wxT( "assertion" )
476 || token == wxT( "clearance" )
477 || token == wxT( "connection_width" )
478 || token == wxT( "courtyard_clearance" )
479 || token == wxT( "diff_pair_gap" )
480 || token == wxT( "diff_pair_uncoupled" )
481 || token == wxT( "disallow" )
482 || token == wxT( "edge_clearance" )
483 || token == wxT( "length" )
484 || token == wxT( "line_width" )
485 || token == wxT( "hole_clearance" )
486 || token == wxT( "hole_size" )
487 || token == wxT( "hole_to_hole" )
488 || token == wxT( "min_resolved_spokes" )
489 || token == wxT( "physical_clearance" )
490 || token == wxT( "physical_hole_clearance" )
491 || token == wxT( "silk_clearance" )
492 || token == wxT( "skew" )
493 || token == wxT( "solder_mask_expansion" )
494 || token == wxT( "solder_paste_abs_margin" )
495 || token == wxT( "solder_paste_rel_margin" )
496 || token == wxT( "text_height" )
497 || token == wxT( "text_thickness" )
498 || token == wxT( "thermal_relief_gap" )
499 || token == wxT( "thermal_spoke_width" )
500 || token == wxT( "track_width" )
501 || token == wxT( "track_angle" )
502 || token == wxT( "track_segment_length" )
503 || token == wxT( "via_count" )
504 || token == wxT( "via_diameter" )
505 || token == wxT( "zone_connection" );
506 };
507
508 std::stack<wxString> sexprs;
509 wxString partial;
510 wxString last;
511 wxString constraintType;
512 int context = NO_CONTEXT;
513 int expr_context = NO_CONTEXT;
514
515 for( int i = startPos; i < currentPos; ++i )
516 {
517 wxChar c = m_textEditor->GetCharAt( i );
518
519 if( c == '\\' )
520 {
521 i++; // skip escaped char
522 }
523 else if( context == STRING )
524 {
525 if( c == '"' )
526 {
527 context = NO_CONTEXT;
528 }
529 else
530 {
531 if( expr_context == STRING )
532 {
533 if( c == '\'' )
534 expr_context = NO_CONTEXT;
535 else
536 partial += c;
537 }
538 else if( c == '\'' )
539 {
540 last = partial;
541 partial = wxEmptyString;
542 expr_context = STRING;
543 }
544 else if( c == '.' )
545 {
546 partial = wxEmptyString;
547 expr_context = STRUCT_REF;
548 }
549 else
550 {
551 partial += c;
552 }
553 }
554 }
555 else if( c == '"' )
556 {
557 last = partial;
558 partial = wxEmptyString;
559 context = STRING;
560 }
561 else if( c == '(' )
562 {
563 if( context == SEXPR_OPEN && !partial.IsEmpty() )
564 {
565 m_textEditor->AutoCompCancel();
566 sexprs.push( partial );
567 }
568
569 partial = wxEmptyString;
570 context = SEXPR_OPEN;
571 }
572 else if( c == ')' )
573 {
574 while( !sexprs.empty() && ( sexprs.top() == wxT( "assertion" )
575 || sexprs.top() == wxT( "disallow" )
576 || isDisallowToken( sexprs.top() )
577 || sexprs.top() == wxT( "min_resolved_spokes" )
578 || sexprs.top() == wxT( "zone_connection" ) ) )
579 {
580 sexprs.pop();
581 }
582
583 if( !sexprs.empty() )
584 {
585 // Ignore argument-less tokens
586 if( partial == wxT( "within_diff_pairs" ) )
587 {
588 partial = wxEmptyString;
589 }
590 else
591 {
592 if( sexprs.top() == wxT( "constraint" ) )
593 {
594 constraintType = wxEmptyString;
595 }
596
597 sexprs.pop();
598 }
599 }
600
601 context = NO_CONTEXT;
602 }
603 else if( c == ' ' )
604 {
605 if( context == SEXPR_OPEN && !partial.IsEmpty() )
606 {
607 m_textEditor->AutoCompCancel();
608 sexprs.push( partial );
609
610 if( partial == wxT( "constraint" )
611 || partial == wxT( "layer" )
612 || partial == wxT( "severity" ) )
613 {
614 context = SEXPR_TOKEN;
615 }
616 else if( partial == wxT( "rule" )
617 || partial == wxT( "condition" ) )
618 {
619 context = SEXPR_STRING;
620 }
621 else
622 {
623 context = NO_CONTEXT;
624 }
625
626 partial = wxEmptyString;
627 continue;
628 }
629 else if( partial == wxT( "disallow" )
630 || isDisallowToken( partial )
631 || partial == wxT( "min_resolved_spokes" )
632 || partial == wxT( "zone_connection" ) )
633 {
634 m_textEditor->AutoCompCancel();
635 sexprs.push( partial );
636
637 partial = wxEmptyString;
638 context = SEXPR_TOKEN;
639 continue;
640 }
641 else if( partial == wxT( "assertion" ) )
642 {
643 m_textEditor->AutoCompCancel();
644 sexprs.push( partial );
645
646 partial = wxEmptyString;
647 context = SEXPR_STRING;
648 continue;
649 }
650 else if( isConstraintTypeToken( partial ) )
651 {
652 constraintType = partial;
653 }
654
655 context = NO_CONTEXT;
656 }
657 else
658 {
659 partial += c;
660 }
661 }
662
663 wxString tokens;
664
665 if( context == SEXPR_OPEN )
666 {
667 if( sexprs.empty() )
668 {
669 tokens = wxT( "rule|"
670 "version" );
671 }
672 else if( sexprs.top() == wxT( "rule" ) )
673 {
674 tokens = wxT( "condition|"
675 "constraint|"
676 "layer|"
677 "severity" );
678 }
679 else if( sexprs.top() == wxT( "constraint" ) )
680 {
681 if( constraintType == wxT( "skew" ) )
682 tokens = wxT( "max|min|opt|within_diff_pairs" );
683 else
684 tokens = wxT( "max|min|opt" );
685 }
686 }
687 else if( context == SEXPR_TOKEN )
688 {
689 if( sexprs.empty() )
690 {
691 /* badly formed grammar */
692 }
693 else if( sexprs.top() == wxT( "constraint" ) )
694 {
695 tokens = wxT( "annular_width|"
696 "assertion|"
697 "bridged_mask|"
698 "clearance|"
699 "connection_width|"
700 "courtyard_clearance|"
701 "creepage|"
702 "diff_pair_gap|"
703 "diff_pair_uncoupled|"
704 "disallow|"
705 "edge_clearance|"
706 "length|"
707 "line_width|"
708 "hole_clearance|"
709 "hole_size|"
710 "hole_to_hole|"
711 "min_resolved_spokes|"
712 "physical_clearance|"
713 "physical_hole_clearance|"
714 "silk_clearance|"
715 "skew|"
716 "solder_mask_expansion|"
717 "solder_paste_abs_margin|"
718 "solder_paste_rel_margin|"
719 "text_height|"
720 "thermal_relief_gap|"
721 "thermal_spoke_width|"
722 "track_width|"
723 "track_angle|"
724 "track_segment_length|"
725 "via_count|"
726 "via_diameter|"
727 "zone_connection" );
728 }
729 else if( sexprs.top() == wxT( "disallow" ) || isDisallowToken( sexprs.top() ) )
730 {
731 tokens = wxT( "blind_via|"
732 "buried_via|"
733 "footprint|"
734 "graphic|"
735 "hole|"
736 "micro_via|"
737 "pad|"
738 "text|"
739 "through_via|"
740 "track|"
741 "via|"
742 "zone" );
743 }
744 else if( sexprs.top() == wxT( "zone_connection" ) )
745 {
746 tokens = wxT( "none|solid|thermal_reliefs" );
747 }
748 else if( sexprs.top() == wxT( "min_resolved_spokes" ) )
749 {
750 tokens = wxT( "0|1|2|3|4" );
751 }
752 else if( sexprs.top() == wxT( "layer" ) )
753 {
754 tokens = wxT( "inner|outer|\"x\"" );
755 }
756 else if( sexprs.top() == wxT( "severity" ) )
757 {
758 tokens = wxT( "warning|error|ignore|exclusion" );
759 }
760 }
761 else if( context == SEXPR_STRING && !sexprs.empty()
762 && ( sexprs.top() == wxT( "condition" ) || sexprs.top() == wxT( "assertion" ) ) )
763 {
764 m_textEditor->AddText( wxT( "\"" ) );
765 }
766 else if( context == STRING && !sexprs.empty()
767 && ( sexprs.top() == wxT( "condition" ) || sexprs.top() == wxT( "assertion" ) ) )
768 {
769 if( expr_context == STRUCT_REF )
770 {
772 std::set<wxString> propNames;
773
774 for( const PROPERTY_MANAGER::CLASS_INFO& cls : propMgr.GetAllClasses() )
775 {
776 const std::vector<PROPERTY_BASE*>& props = propMgr.GetProperties( cls.type );
777
778 for( PROPERTY_BASE* prop : props )
779 {
780 // TODO: It would be nice to replace IsHiddenFromRulesEditor with a nickname
781 // system, so that two different properies don't need to be created. This is
782 // a bigger change than I want to make right now, though.
783 if( prop->IsHiddenFromRulesEditor() )
784 continue;
785
786 wxString ref( prop->Name() );
787 ref.Replace( wxT( " " ), wxT( "_" ) );
788 propNames.insert( ref );
789 }
790 }
791
792 for( const wxString& propName : propNames )
793 tokens += wxT( "|" ) + propName;
794
796
797 for( const wxString& funcSig : functions.GetSignatures() )
798 {
799 if( !funcSig.Contains( "DEPRECATED" ) )
800 tokens += wxT( "|" ) + funcSig;
801 }
802 }
803 else if( expr_context == STRING )
804 {
805 if( m_netClassRegex.Matches( last ) )
806 {
807 std::shared_ptr<NET_SETTINGS>& netSettings = m_frame->GetBoard()->GetDesignSettings().m_NetSettings;
808
809 for( const auto& [name, netclass] : netSettings->GetNetclasses() )
810 tokens += wxT( "|" ) + name;
811 }
812 else if( m_netNameRegex.Matches( last ) )
813 {
814 BOARD* board = m_frame->GetBoard();
815
816 for( const wxString& netnameCandidate : board->GetNetClassAssignmentCandidates() )
817 tokens += wxT( "|" ) + netnameCandidate;
818 }
819 else if( m_typeRegex.Matches( last ) )
820 {
821 tokens = wxT( "Bitmap|"
822 "Dimension|"
823 "Footprint|"
824 "Graphic|"
825 "Group|"
826 "Leader|"
827 "Pad|"
828 "Target|"
829 "Text|"
830 "Text Box|"
831 "Track|"
832 "Via|"
833 "Zone" );
834 }
835 else if( m_viaTypeRegex.Matches( last ) )
836 {
837 tokens = wxT( "Through|"
838 "Blind|"
839 "Buried|"
840 "Micro" );
841 }
842 else if( m_padTypeRegex.Matches( last ) )
843 {
844 tokens = wxT( "Through-hole|"
845 "SMD|"
846 "Edge connector|"
847 "NPTH, mechanical" );
848 }
849 else if( m_pinTypeRegex.Matches( last ) )
850 {
851 tokens = wxT( "Input|"
852 "Output|"
853 "Bidirectional|"
854 "Tri-state|"
855 "Passive|"
856 "Free|"
857 "Unspecified|"
858 "Power input|"
859 "Power output|"
860 "Open collector|"
861 "Open emitter|"
862 "Unconnected" );
863 }
864 else if( m_fabPropRegex.Matches( last ) )
865 {
866 tokens = wxT( "None|"
867 "BGA pad|"
868 "Fiducial, global to board|"
869 "Fiducial, local to footprint|"
870 "Test point pad|"
871 "Heatsink pad|"
872 "Castellated pad" );
873 }
874 else if( m_shapeRegex.Matches( last ) )
875 {
876 tokens = wxT( "Segment|"
877 "Rectangle|"
878 "Arc|"
879 "Circle|"
880 "Polygon|"
881 "Bezier" );
882 }
883 else if( m_padShapeRegex.Matches( last ) )
884 {
885 tokens = wxT( "Circle|"
886 "Rectangle|"
887 "Oval|"
888 "Trapezoid|"
889 "Rounded rectangle|"
890 "Chamfered rectangle|"
891 "Custom" );
892 }
893 else if( m_padConnectionsRegex.Matches( last ) )
894 {
895 tokens = wxT( "Inherited|"
896 "None|"
897 "Solid|"
898 "Thermal reliefs|"
899 "Thermal reliefs for PTH" );
900 }
901 else if( m_zoneConnStyleRegex.Matches( last ) )
902 {
903 tokens = wxT( "Inherited|"
904 "None|"
905 "Solid|"
906 "Thermal reliefs" );
907 }
908 else if( m_lineStyleRegex.Matches( last ) )
909 {
910 tokens = wxT( "Default|"
911 "Solid|"
912 "Dashed|"
913 "Dotted|"
914 "Dash-Dot|"
915 "Dash-Dot-Dot" );
916 }
917 else if( m_hJustRegex.Matches( last ) )
918 {
919 tokens = wxT( "Left|"
920 "Center|"
921 "Right" );
922 }
923 else if( m_vJustRegex.Matches( last ) )
924 {
925 tokens = wxT( "Top|"
926 "Center|"
927 "Bottom" );
928 }
929 }
930 }
931
932 if( !tokens.IsEmpty() )
933 m_scintillaTricks->DoAutocomplete( partial, wxSplit( tokens, '|' ) );
934}
935
936
937void PANEL_SETUP_RULES::OnCompile( wxCommandEvent& event )
938{
939 m_errorsReport->Clear();
940
941 try
942 {
943 std::vector<std::shared_ptr<DRC_RULE>> dummyRules;
944
945 std::function<bool( wxString* )> resolver =
946 [&]( wxString* token ) -> bool
947 {
948 if( IsComponentClassSelector( *token ) )
949 return false;
950
951 return m_frame->GetBoard()->ResolveTextVar( token, 0 );
952 };
953
954 wxString rulesText = m_textEditor->GetText();
955 rulesText = m_frame->GetBoard()->ConvertCrossReferencesToKIIDs( rulesText );
956 rulesText = ExpandTextVars( rulesText, &resolver, RESOLVED );
957
958 DRC_RULES_PARSER parser( rulesText, _( "DRC rules" ) );
959
960 parser.Parse( dummyRules, m_errorsReport );
961 checkPlausibility( dummyRules );
962 }
963 catch( PARSE_ERROR& pe )
964 {
965 m_errorsReport->Report( wxString::Format( wxT( "%s <a href='%d:%d'>%s</a>%s" ),
966 _( "ERROR:" ),
967 pe.lineNumber,
968 pe.byteIndex,
969 pe.ParseProblem(),
970 wxEmptyString ),
972 }
973
974 m_errorsReport->Flush();
975}
976
977
978void PANEL_SETUP_RULES::checkPlausibility( const std::vector<std::shared_ptr<DRC_RULE>>& aRules )
979{
980 BOARD* board = m_frame->GetBoard();
981 LSET enabledLayers = board->GetEnabledLayers();
982
983 // Key by (condition, layerSource) so rules with different layer scopes are considered distinct
984 std::map<std::pair<wxString, wxString>, wxString> seenConditions;
985 std::regex netclassPattern( "NetClass\\s*[!=]=\\s*'\"?([^\"\\s]+)'\"?" );
986
987 for( const auto& rule : aRules )
988 {
989 wxString condition;
990
991 if( rule->m_Condition )
992 condition = rule->m_Condition->GetExpression();
993
994 condition.Trim( true ).Trim( false );
995
996 auto key = std::make_pair( condition, rule->m_LayerSource );
997
998 if( seenConditions.count( key ) )
999 {
1000 m_errorsReport->Report( wxString::Format( _( "Rules '%s' and '%s' share the same condition." ),
1001 rule->m_Name,
1002 seenConditions[key] ),
1004 }
1005 else
1006 {
1007 seenConditions[key] = rule->m_Name;
1008 }
1009
1010 std::string condUtf8 = condition.ToStdString();
1011 std::sregex_iterator it( condUtf8.begin(), condUtf8.end(), netclassPattern );
1012 std::sregex_iterator end;
1013
1014 for( ; it != end; ++it )
1015 {
1016 wxString ncName = wxString::FromUTF8( ( *it )[1].str() );
1017
1018 if( !board->GetDesignSettings().m_NetSettings->HasNetclass( ncName ) )
1019 {
1020 m_errorsReport->Report( wxString::Format( _( "Rule '%s' references undefined netclass '%s'." ),
1021 rule->m_Name,
1022 ncName ),
1024 }
1025 }
1026
1027 const bool isInner = rule->m_LayerSource.IsSameAs( wxT( "'inner'" ), false );
1028 const bool isOuter = rule->m_LayerSource.IsSameAs( wxT( "'outer'" ), false );
1029
1030 if( !rule->m_LayerSource.IsEmpty() && !isInner && !isOuter )
1031 {
1032 LSET invalid = rule->m_LayerCondition & ~enabledLayers;
1033
1034 if( invalid.any() )
1035 {
1036 wxString badLayers;
1037
1038 for( PCB_LAYER_ID layer : invalid.Seq() )
1039 {
1040 if( !badLayers.IsEmpty() )
1041 badLayers += ", ";
1042
1043 badLayers += board->GetLayerName( layer );
1044 }
1045
1046 m_errorsReport->Report( wxString::Format( _( "Rule '%s' references undefined layer(s): %s." ),
1047 rule->m_Name,
1048 badLayers ),
1050 }
1051 }
1052 }
1053}
1054
1055
1056void PANEL_SETUP_RULES::OnErrorLinkClicked( wxHtmlLinkEvent& event )
1057{
1058 wxString link = event.GetLinkInfo().GetHref();
1059 wxArrayString parts;
1060 long line = 0, offset = 0;
1061
1062 wxStringSplit( link, parts, ':' );
1063
1064 if( parts.size() > 1 )
1065 {
1066 parts[0].ToLong( &line );
1067 parts[1].ToLong( &offset );
1068 }
1069
1070 int pos = m_textEditor->PositionFromLine( line - 1 ) + ( offset - 1 );
1071
1072 m_textEditor->GotoPos( pos );
1073
1074 m_textEditor->SetFocus();
1075}
1076
1077
1079{
1080 if( !m_frame->GetBoard() )
1081 return true;
1082
1084
1085 if( m_frame->Prj().IsNullProject() )
1086 {
1087 m_textEditor->ClearAll();
1088 m_textEditor->AddText( _( "Design rules cannot be added without a project" ) );
1089 m_textEditor->Disable();
1090 }
1091
1092 return true;
1093}
1094
1095
1097{
1098 if( IsModified() )
1099 {
1100 m_document->SetText( m_textEditor->GetText() );
1101 m_originalText = m_textEditor->GetText();
1102 }
1103
1104 return true;
1105}
1106
1107
1108void PANEL_SETUP_RULES::OnSyntaxHelp( wxHyperlinkEvent& aEvent )
1109{
1110 if( m_helpWindow )
1111 {
1112 m_helpWindow->ShowModeless();
1113 return;
1114 }
1115 std::vector<wxString> msg;
1116 msg.clear();
1117
1118 wxString t =
1120 ;
1121 msg.emplace_back( t );
1122 t =
1124 ;
1125 msg.emplace_back( t );
1126 t =
1128 ;
1129 msg.emplace_back( t );
1130 t =
1132 ;
1133 msg.emplace_back( t );
1134 t =
1136 ;
1137 msg.emplace_back( t );
1138 t =
1140 ;
1141 msg.emplace_back( t );
1142 t =
1144 ;
1145 msg.emplace_back( t );
1146 t =
1148 ;
1149 msg.emplace_back( t );
1150 t =
1152 ;
1153 msg.emplace_back( t );
1154 t =
1156 ;
1157 msg.emplace_back( t );
1158
1159 wxString msg_txt = wxEmptyString;
1160
1161 for( wxString i : msg )
1162 msg_txt << wxGetTranslation( i );
1163
1164#ifdef __WXMAC__
1165 msg_txt.Replace( wxT( "Ctrl+" ), wxT( "Cmd+" ) );
1166#endif
1167 const wxString& msGg_txt = msg_txt;
1168
1169 m_helpWindow = new HTML_MESSAGE_BOX( nullptr, _( "Syntax Help" ) );
1170 m_helpWindow->SetDialogSizeInDU( 420, 320 );
1171
1172 wxString html_txt = wxEmptyString;
1173 ConvertMarkdown2Html( msGg_txt, html_txt );
1174
1175 html_txt.Replace( wxS( "<td" ), wxS( "<td valign=top" ) );
1176 m_helpWindow->AddHTML_Text( html_txt );
1177
1178 m_helpWindow->ShowModeless();
1179}
1180
1181
1183{
1184 wxString text = m_document->GetText();
1185
1186 if( text != m_textEditor->GetText() )
1187 {
1188 m_textEditor->SetText( text );
1189 m_textEditor->EmptyUndoBuffer();
1190
1191 wxCommandEvent dummy;
1192 OnCompile( dummy );
1193 }
1194
1195 m_originalText = m_textEditor->GetText();
1196}
const char * name
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:106
std::shared_ptr< NET_SETTINGS > m_NetSettings
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
std::set< wxString > GetNetClassAssignmentCandidates() const
Return the set of netname candidates for netclass assignment.
Definition board.cpp:2982
const wxString GetLayerName(PCB_LAYER_ID aLayer) const
Return the name of a aLayer.
Definition board.cpp:960
const LSET & GetEnabledLayers() const
A proxy function that calls the corresponding function in m_BoardSettings.
Definition board.cpp:1202
BOARD_DESIGN_SETTINGS & GetDesignSettings()
Definition board.cpp:1318
APPEARANCE m_Appearance
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 bool IsSymbol(int aTok)
Test a token to see if it is a symbol.
Definition dsnlexer.cpp:340
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
LSET is a set of PCB_LAYER_IDs.
Definition lset.h:37
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
bool HasNetclass(const wxString &netclassName) const
Determines if the given netclass exists.
void SetModified()
static PAGED_DIALOG * GetDialog(wxWindow *aWindow)
STD_BITMAP_BUTTON * m_compileButton
wxStyledTextCtrl * m_textEditor
PANEL_SETUP_RULES_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)
WX_HTML_REPORT_BOX * m_errorsReport
bool TransferDataToWindow() override
void OnErrorLinkClicked(wxHtmlLinkEvent &event) override
void checkPlausibility(const std::vector< std::shared_ptr< DRC_RULE > > &aRules)
void onScintillaCharAdded(wxStyledTextEvent &aEvent)
DRC_RULE_DOCUMENT * m_document
PCB_EDIT_FRAME * m_frame
void OnContextMenu(wxMouseEvent &event) override
HTML_MESSAGE_BOX * m_helpWindow
void OnCompile(wxCommandEvent &event) override
PANEL_SETUP_RULES(wxWindow *aParentWindow, PCB_EDIT_FRAME *aFrame, DRC_RULE_DOCUMENT *aDocument)
bool TransferDataFromWindow() override
void OnSyntaxHelp(wxHyperlinkEvent &aEvent) override
void onCharHook(wxKeyEvent &aEvent)
SCINTILLA_TRICKS * m_scintillaTricks
const wxArrayString GetSignatures() const
static PCBEXPR_BUILTIN_FUNCTIONS & Instance()
The main frame for Pcbnew.
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
Provide class metadata.
const std::vector< PROPERTY_BASE * > & GetProperties(TYPE_ID aType) const
Return all properties for a specific type.
static PROPERTY_MANAGER & Instance()
std::vector< CLASS_INFO > GetAllClasses()
Add cut/copy/paste, dark theme, autocomplete and brace highlighting to a wxStyleTextCtrl instance.
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
Definition common.cpp:60
@ RESOLVED
Definition common.h:97
std::string utf8(const wxString &aText)
bool IsComponentClassSelector(const wxString &aToken)
${Class:X} inside a DRC rule is a component-class selector consumed by testFootprintSelector(),...
Definition drc_rule.cpp:32
@ DSN_LEFT
Definition dsnlexer.h:63
@ DSN_RIGHT
Definition dsnlexer.h:62
@ DSN_EOF
Definition dsnlexer.h:65
#define _(s)
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
@ RPT_SEVERITY_WARNING
@ RPT_SEVERITY_ERROR
@ RPT_SEVERITY_INFO
@ RPT_SEVERITY_ACTION
std::vector< FAB_LAYER_COLOR > dummy
void wxStringSplit(const wxString &aText, wxArrayString &aStrings, wxChar aSplitter)
Split aString to a string list separated at aSplitter.
void ConvertMarkdown2Html(const wxString &aMarkdownInput, wxString &aHtmlOutput)
A filename or source description, a problem input line, a line number, a byte offset,...
int lineNumber
at which line number, 1 based index.
const wxString ParseProblem()
int byteIndex
at which byte offset within the line, 1 based index
VECTOR2I end
@ 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