KiCad PCB EDA Suite
Loading...
Searching...
No Matches
drc_rule_document.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
20#include "drc_rule_document.h"
21
22#include <board.h>
23#include <drc/drc_rule_parser.h>
24#include <kiplatform/io.h>
25#include <string_utils.h>
26#include <algorithm>
27#include <wx/convauto.h>
28#include <wx/ffile.h>
29#include <wx/filename.h>
30
31#include "drc_re_rule_loader.h"
33#include "drc_re_rule_saver.h"
36
37
39 m_board( aBoard ),
40 m_hasRawText( false ),
41 m_textCurrent( false ),
42 m_modified( false ),
43 m_nextId( 1 ),
44 m_nextGroupId( 1 )
45{
46}
47
48
50{
51 load( m_board->GetDesignRulesPath() );
52 m_modified = false;
53}
54
55
56void DRC_RULE_DOCUMENT::LoadFrom( const wxString& aPath )
57{
58 if( !wxFileName::FileExists( aPath ) )
59 return;
60
61 if( load( aPath ) )
62 m_modified = true;
63}
64
65
66bool DRC_RULE_DOCUMENT::load( const wxString& aPath )
67{
68 bool exists = wxFileName::FileExists( aPath );
69 wxString text;
70
71 if( exists )
72 {
73 wxFFile file( aPath, wxS( "rb" ) );
74
75 // wxConvAuto falls back to Latin-1, so a file that is not UTF-8 still reads
76 if( !file.IsOpened() || !file.ReadAll( &text, wxConvAuto() ) || ( file.Length() > 0 && text.IsEmpty() ) )
77 return false;
78
79 text.Replace( wxS( "\r\n" ), wxS( "\n" ) );
80 }
81
82 m_entries.clear();
84 m_rawText.clear();
85 m_hasRawText = false;
86 m_textCurrent = false;
87
88 if( !exists )
89 return true;
90
91 // A rules file written outside KiCad can carry typographic quotes that the parser rejects.
93
95 m_textCurrent = true;
97 return true;
98}
99
100
101bool DRC_RULE_DOCUMENT::parseInto( const wxString& aText )
102{
103 DRC_RULE_LOADER loader;
104 bool parsed = false;
105
106 std::vector<DRC_RE_LOADED_PANEL_ENTRY> entries = loader.LoadFromString( aText, &parsed );
107
108 if( !parsed )
109 return false;
110
111 m_entries = std::move( entries );
112 m_trivia = loader.GetFileTrivia();
114
115 return true;
116}
117
118
120{
122 {
123 m_nextGroupId = std::max( m_nextGroupId, entry.ruleGroupId + 1 );
124
125 if( !entry.constraintData )
126 continue;
127
128 entry.constraintData->SetId( m_nextId++ );
129
130 wxString layerSource = entry.layerSource;
131
132 // An edited panel writes the canonical name, and siblings of a split rule must match it
133 if( m_board && entry.layerCondition.count() == 1 )
134 {
135 PCB_LAYER_ID layer = entry.layerCondition.Seq().front();
136
137 if( layerSource == m_board->GetLayerName( layer ) )
138 layerSource = LSET::Name( layer );
139 }
140
141 entry.constraintData->SetLayerSource( layerSource );
142
143 if( !entry.layerSource.IsEmpty() )
144 entry.constraintData->SetLayers( entry.layerCondition.Seq() );
145
146 entry.constraintData->SetSeverity( entry.severity );
147 }
148}
149
150
151bool DRC_RULE_DOCUMENT::Save( wxString* aError )
152{
153 wxString text = GetText();
154 std::string utf8 = std::string( text.mb_str( wxConvUTF8 ) );
155
156 if( !KIPLATFORM::IO::AtomicWriteFile( m_board->GetDesignRulesPath(), utf8.data(), utf8.size(), aError ) )
157 return false;
158
159 m_modified = false;
160 return true;
161}
162
163
165{
166 if( m_textCurrent )
167 return m_rawText;
168
169 DRC_RULE_SAVER saver;
171}
172
173
174void DRC_RULE_DOCUMENT::SetText( const wxString& aText )
175{
176 if( aText == GetText() )
177 return;
178
179 m_rawText = aText;
180 m_textCurrent = true;
181 m_hasRawText = !parseInto( aText );
182 m_modified = true;
183}
184
185
186std::set<DRC_CONSTRAINT_T> DRC_RULE_DOCUMENT::ConstraintsOf( const DRC_RE_LOADED_PANEL_ENTRY& aEntry )
187{
188 std::set<DRC_CONSTRAINT_T> result;
189
190 if( !aEntry.constraintData )
191 return result;
192
193 // The condition cannot change which constraints are set, and leaving it out keeps the parse from failing on it
195 ctx.ruleName = wxS( "rule" );
197
198 wxString ruleText = aEntry.constraintData->GenerateRule( ctx );
199 std::vector<std::shared_ptr<DRC_RULE>> rules;
200
201 try
202 {
203 DRC_RULES_PARSER parser( wxS( "(version 2)\n" ) + ruleText, wxS( "Rule Document" ) );
204 parser.Parse( rules, nullptr );
205 }
206 catch( const IO_ERROR& )
207 {
208 return result;
209 }
210
211 for( const std::shared_ptr<DRC_RULE>& rule : rules )
212 {
213 for( const DRC_CONSTRAINT& constraint : rule->m_Constraints )
214 result.insert( constraint.m_Type );
215 }
216
217 return result;
218}
219
220
222{
223 // A rule no graphical panel could take apart is kept as text. It still belongs on the
224 // page of every constraint it sets.
225 static DRC_PANEL_MATCHER matcher;
226 std::vector<int> result;
227
228 // The entries are a previous parse, so they no longer describe the text
229 if( m_hasRawText )
230 return result;
231
232 for( size_t i = 0; i < m_entries.size(); ++i )
233 {
234 const DRC_RE_LOADED_PANEL_ENTRY& entry = m_entries[i];
235
236 if( !entry.constraintData )
237 continue;
238
239 if( entry.panelType == aType )
240 {
241 result.push_back( (int) i );
242 }
243 else if( entry.panelType == CUSTOM_RULE && aType != CUSTOM_RULE )
244 {
245 for( DRC_CONSTRAINT_T constraint : ConstraintsOf( entry ) )
246 {
247 if( matcher.GetHomePanel( constraint ) == aType )
248 {
249 result.push_back( (int) i );
250 break;
251 }
252 }
253 }
254 }
255
256 return result;
257}
258
259
260std::vector<int> DRC_RULE_DOCUMENT::IndicesSetting( DRC_CONSTRAINT_T aConstraint ) const
261{
262 std::vector<int> result;
263
264 if( m_hasRawText )
265 return result;
266
267 for( size_t i = 0; i < m_entries.size(); ++i )
268 {
269 if( ConstraintsOf( m_entries[i] ).count( aConstraint ) )
270 result.push_back( (int) i );
271 }
272
273 return result;
274}
275
276
278{
279 // Regenerating from stale entries would replace the text the user is still fixing
280 if( m_hasRawText )
281 return -1;
282
283 m_entries.push_back( aEntry );
284
285 if( m_entries.back().ruleGroupId <= 0 )
286 m_entries.back().ruleGroupId = m_nextGroupId++;
287
288 touch();
289
290 return (int) m_entries.size() - 1;
291}
292
293
295{
296 if( m_hasRawText || aIndex < 0 || aIndex >= (int) m_entries.size() )
297 return;
298
299 m_entries[aIndex] = aEdited;
300 m_entries[aIndex].wasEdited = true;
301
302 const DRC_RE_LOADED_PANEL_ENTRY& edited = m_entries[aIndex];
303
304 for( size_t i = 0; i < m_entries.size(); ++i )
305 {
307
308 if( (int) i == aIndex || sibling.ruleGroupId <= 0 || sibling.ruleGroupId != edited.ruleGroupId )
309 continue;
310
311 sibling.ruleName = edited.ruleName;
312 sibling.condition = edited.condition;
313 sibling.layerCondition = edited.layerCondition;
314 sibling.layerSource = edited.layerSource;
315 sibling.severity = edited.severity;
316 sibling.wasEdited = true;
317
318 if( sibling.constraintData )
319 {
320 sibling.constraintData->SetRuleName( edited.ruleName );
321 sibling.constraintData->SetRuleCondition( edited.condition );
322 sibling.constraintData->SetLayers( edited.layerCondition.Seq() );
323 sibling.constraintData->SetLayerSource( edited.layerSource );
324 sibling.constraintData->SetSeverity( edited.severity );
325
326 if( edited.constraintData )
328
329 sibling.constraintData->SetGeneratedRule( wxEmptyString );
330 }
331 }
332
333 touch();
334}
335
336
338{
339 if( m_hasRawText || aIndex < 0 || aIndex >= (int) m_entries.size() )
340 return;
341
342 m_entries.erase( m_entries.begin() + aIndex );
343 touch();
344}
345
346
348{
349 if( m_hasRawText || aIndex < 0 || aIndex >= (int) m_entries.size() || !m_entries[aIndex].constraintData )
350 return -1;
351
353
354 // Drop a trailing number so copying a copy counts on instead of stacking suffixes.
355 wxString baseName = source.ruleName;
356 int lastSpace = baseName.Find( ' ', true );
357
358 if( lastSpace != wxNOT_FOUND )
359 {
360 long number;
361
362 if( baseName.Mid( lastSpace + 1 ).ToLong( &number ) )
363 baseName = baseName.Left( lastSpace );
364 }
365
366 wxString name = UniqueRuleName( baseName );
368 std::shared_ptr<DRC_RE_BASE_CONSTRAINT_DATA> data =
370
371 data->CopyFrom( *source.constraintData );
372 data->SetRuleName( name );
373 data->SetIsNew( false );
374
375 // The copy is written from its own fields, so drop the text the original was read from.
376 data->SetGeneratedRule( wxEmptyString );
377
378 DRC_RE_LOADED_PANEL_ENTRY copy( source.panelType, data, name, source.condition, source.severity,
379 source.layerCondition );
380
381 copy.layerSource = source.layerSource;
382 copy.wasEdited = true;
383 copy.ruleGroupId = m_nextGroupId++;
384
385 m_entries.insert( m_entries.begin() + aIndex + 1, copy );
386 touch();
387
388 return aIndex + 1;
389}
390
391
392bool DRC_RULE_DOCUMENT::Move( int aIndex, int aDelta, DRC_RULE_EDITOR_CONSTRAINT_NAME aType )
393{
394 if( m_hasRawText || aDelta == 0 )
395 return false;
396
397 std::vector<int> order = IndicesFor( aType );
398 auto it = std::find( order.begin(), order.end(), aIndex );
399
400 if( it == order.end() )
401 return false;
402
403 int position = (int) ( it - order.begin() ) + ( aDelta > 0 ? 1 : -1 );
404
405 if( position < 0 || position >= (int) order.size() )
406 return false;
407
408 int movedGroup = m_entries[aIndex].ruleGroupId;
409 int otherGroup = m_entries[order[position]].ruleGroupId;
410
411 if( movedGroup <= 0 || otherGroup <= 0 || movedGroup == otherGroup )
412 {
413 std::swap( m_entries[aIndex], m_entries[order[position]] );
414 touch();
415 return true;
416 }
417
418 // The saver writes a rule where its first entry sits, so whole rules swap to keep the file in step
419 std::vector<int> groups;
420
421 for( const DRC_RE_LOADED_PANEL_ENTRY& entry : m_entries )
422 {
423 if( std::find( groups.begin(), groups.end(), entry.ruleGroupId ) == groups.end() )
424 groups.push_back( entry.ruleGroupId );
425 }
426
427 std::iter_swap( std::find( groups.begin(), groups.end(), movedGroup ),
428 std::find( groups.begin(), groups.end(), otherGroup ) );
429
430 std::vector<DRC_RE_LOADED_PANEL_ENTRY> reordered;
431 reordered.reserve( m_entries.size() );
432
433 for( int group : groups )
434 {
436 {
437 if( entry.ruleGroupId == group )
438 reordered.push_back( std::move( entry ) );
439 }
440 }
441
442 m_entries = std::move( reordered );
443 touch();
444 return true;
445}
446
447
449 int aExceptIndex ) const
450{
451 if( aExceptIndex >= 0 && aExceptIndex < (int) m_entries.size() )
452 aType = m_entries[aExceptIndex].panelType;
453
454 for( size_t i = 0; i < m_entries.size(); ++i )
455 {
456 if( (int) i == aExceptIndex )
457 continue;
458
459 if( m_entries[i].panelType == aType && m_entries[i].ruleName == aName )
460 return false;
461 }
462
463 return true;
464}
465
466
467wxString DRC_RULE_DOCUMENT::UniqueRuleName( const wxString& aBase ) const
468{
469 auto exists = [this]( const wxString& aName )
470 {
471 for( const DRC_RE_LOADED_PANEL_ENTRY& entry : m_entries )
472 {
473 if( entry.ruleName == aName )
474 return true;
475 }
476
477 return false;
478 };
479
480 int n = 1;
481 wxString name = wxString::Format( wxS( "%s %d" ), aBase, n );
482
483 while( exists( name ) )
484 name = wxString::Format( wxS( "%s %d" ), aBase, ++n );
485
486 return name;
487}
488
489
491{
492 m_modified = true;
493 m_textCurrent = false;
494}
495
496
497size_t DRC_RULE_DOCUMENT::FindConstraintClause( const wxString& aText, const wxString& aCode )
498{
499 const wxString keyword = wxS( "(constraint" );
500 size_t pos = aText.find( keyword );
501
502 auto isSpace = []( wxUniChar aChar )
503 {
504 return aChar == ' ' || aChar == '\t' || aChar == '\n' || aChar == '\r';
505 };
506
507 while( pos != wxString::npos )
508 {
509 size_t code = pos + keyword.length();
510
511 while( code < aText.length() && isSpace( aText[code] ) )
512 code++;
513
514 size_t end = code + aCode.length();
515
516 if( code > pos + keyword.length() && aText.compare( code, aCode.length(), aCode ) == 0
517 && ( end >= aText.length() || isSpace( aText[end] ) || aText[end] == ')' ) )
518 {
519 return pos;
520 }
521
522 pos = aText.find( keyword, pos + keyword.length() );
523 }
524
525 return wxString::npos;
526}
const char * name
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
DRC_CONSTRAINT_T m_Type
Definition drc_rule.h:205
Maps DRC rule constraints to appropriate editor panels.
DRC_RULE_EDITOR_CONSTRAINT_NAME GetHomePanel(DRC_CONSTRAINT_T aConstraintType)
The panel whose page lists a text rule that sets this constraint, or CUSTOM_RULE when no panel edits ...
void SetLayers(std::vector< PCB_LAYER_ID > aLayers)
void SetGeneratedRule(const wxString &aRule)
void SetLayerSource(const wxString &aSource)
void SetRuleCondition(const wxString &aRuleCondition)
virtual wxString GenerateRule(const RULE_GENERATION_CONTEXT &aContext)
void Parse(std::vector< std::shared_ptr< DRC_RULE > > &aRules, REPORTER *aReporter)
std::vector< int > IndicesSetting(DRC_CONSTRAINT_T aConstraint) const
Every rule that sets aConstraint, whichever page edits it.
void SetText(const wxString &aText)
Take the text of the Custom Rules page.
bool Save(wxString *aError)
Write the board's rules file.
static size_t FindConstraintClause(const wxString &aText, const wxString &aCode)
Position of the constraint clause for aCode in rule text, or npos.
void UpdateEntry(int aIndex, const DRC_RE_LOADED_PANEL_ENTRY &aEdited)
Write an edited rule back.
std::vector< int > IndicesFor(DRC_RULE_EDITOR_CONSTRAINT_NAME aType) const
void Load()
Read the board's own rules file.
static std::set< DRC_CONSTRAINT_T > ConstraintsOf(const DRC_RE_LOADED_PANEL_ENTRY &aEntry)
The DRC constraints a rule sets, read back through the rules parser.
bool parseInto(const wxString &aText)
wxString UniqueRuleName(const wxString &aBase) const
void Remove(int aIndex)
std::vector< DRC_RE_LOADED_PANEL_ENTRY > m_entries
int Add(const DRC_RE_LOADED_PANEL_ENTRY &aEntry)
DRC_RULE_DOCUMENT(BOARD *aBoard)
void LoadFrom(const wxString &aPath)
Replace the rules with those of another board's file, as an import.
bool IsRuleNameUnique(const wxString &aName, DRC_RULE_EDITOR_CONSTRAINT_NAME aType, int aExceptIndex) const
DRC_RE_FILE_TRIVIA m_trivia
bool load(const wxString &aPath)
Returns false when the file could not be read, leaving the document as it was.
wxString GetText() const
The rules as text, for the Custom Rules page.
int Duplicate(int aIndex)
bool Move(int aIndex, int aDelta, DRC_RULE_EDITOR_CONSTRAINT_NAME aType)
Move a rule one step among the rules listed for aType.
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...
Loads DRC rules from .kicad_dru files and converts them to panel entries.
const DRC_RE_FILE_TRIVIA & GetFileTrivia() const
std::vector< DRC_RE_LOADED_PANEL_ENTRY > LoadFromString(const wxString &aRulesText, bool *aParsed=nullptr)
Load rules from a text string.
Saves DRC panel entries back to .kicad_dru files.
wxString GenerateRulesText(const std::vector< DRC_RE_LOADED_PANEL_ENTRY > &aEntries, const BOARD *aBoard=nullptr, const DRC_RE_FILE_TRIVIA &aTrivia={})
Generate rule text from panel entries.
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
LSEQ Seq(const LSEQ &aSequence) const
Return an LSEQ from the union of this LSET and a desired sequence.
Definition lset.cpp:309
static wxString Name(PCB_LAYER_ID aLayerId)
Return the fixed name association with aLayerId.
Definition lset.cpp:184
wxString GetComment()
Get the comment associated with the rule.
void SetRuleName(wxString aRuleName)
Set the name of the rule.
void SetComment(wxString aComment)
Set the comment for the rule.
std::string utf8(const wxString &aText)
DRC_RULE_EDITOR_CONSTRAINT_NAME
static bool isSpace(char cc)
Test for whitespace.
Definition dsnlexer.cpp:461
std::string source
PCB_LAYER_ID
A quick note on layer IDs:
Definition layer_ids.h:56
bool AtomicWriteFile(const wxString &aTargetPath, const void *aData, size_t aSize, wxString *aError=nullptr)
Writes aData to aTargetPath via a sibling temp file, fsyncs the data and directory,...
bool ConvertSmartQuotesAndDashes(wxString *aString)
Convert curly quotes and em/en dashes to straight quotes and dashes.
The text of a rules file that lies outside every rule, kept so a save can reproduce it.
Represents a rule loaded from a .kicad_dru file and mapped to a panel.
wxString ruleName
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
VECTOR2I end
wxString result
Test unit parsing edge cases and error handling.