KiCad PCB EDA Suite
cmp_tree_model.cpp
Go to the documentation of this file.
1 /*
2  * This program source code file is part of KiCad, a free EDA CAD application.
3  *
4  * Copyright (C) 2017 Chris Pavlina <pavlina.chris@gmail.com>
5  * Copyright (C) 2014 Henner Zeller <h.zeller@acm.org>
6  * Copyright (C) 2014-2018 KiCad Developers, see AUTHORS.txt for contributors.
7  *
8  * This program is free software: you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License as published by the
10  * Free Software Foundation, either version 3 of the License, or (at your
11  * option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but
14  * WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program. If not, see <http://www.gnu.org/licenses/>.
20  */
21 
22 #include <cmp_tree_model.h>
23 
24 #include <class_library.h>
25 #include <eda_pattern_match.h>
26 #include <make_unique.h>
27 #include <utility>
28 #include <pgm_base.h>
29 
30 
31 // Each node gets this lowest score initially, without any matches applied.
32 // Matches will then increase this score depending on match quality. This way,
33 // an empty search string will result in all components being displayed as they
34 // have the minimum score. However, in that case, we avoid expanding all the
35 // nodes asd the result is very unspecific.
36 static const unsigned kLowestDefaultScore = 1;
37 
38 
39 // Creates a score depending on the position of a string match. If the position
40 // is 0 (= prefix match), this returns the maximum score. This degrades until
41 // pos == max, which returns a score of 0; Evertyhing else beyond that is just
42 // 0. Only values >= 0 allowed for position and max.
43 //
44 // @param aPosition is the position a string has been found in a substring.
45 // @param aMaximum is the maximum score this function returns.
46 // @return position dependent score.
47 static int matchPosScore(int aPosition, int aMaximum)
48 {
49  return ( aPosition < aMaximum ) ? aMaximum - aPosition : 0;
50 }
51 
52 
54 {
55  for( auto& child: Children )
56  child->ResetScore();
57 
59 }
60 
61 
63 {
64  std::vector<CMP_TREE_NODE*> sort_buf;
65 
66  for( auto const& node: Children )
67  sort_buf.push_back( &*node );
68 
69  std::sort( sort_buf.begin(), sort_buf.end(),
70  []( CMP_TREE_NODE* a, CMP_TREE_NODE* b ) -> bool
71  { return a->MatchName > b->MatchName; } );
72 
73  for( int i = 0; i < (int) sort_buf.size(); ++i )
74  sort_buf[i]->IntrinsicRank = i;
75 }
76 
77 
79 {
80  std::sort( Children.begin(), Children.end(),
81  []( std::unique_ptr<CMP_TREE_NODE> const& a, std::unique_ptr<CMP_TREE_NODE> const& b )
82  { return Compare( *a, *b ) > 0; } );
83 
84  for( auto& node: Children )
85  {
86  node->SortNodes();
87  }
88 }
89 
90 
91 int CMP_TREE_NODE::Compare( CMP_TREE_NODE const& aNode1, CMP_TREE_NODE const& aNode2 )
92 {
93  if( aNode1.Type != aNode2.Type )
94  return 0;
95 
96  if( aNode1.Score != aNode2.Score )
97  return aNode1.Score - aNode2.Score;
98 
99  if( aNode1.Parent != aNode2.Parent )
100  return 0;
101 
102  return aNode1.IntrinsicRank - aNode2.IntrinsicRank;
103 }
104 
105 
107  : Parent( nullptr ),
108  Type( INVALID ),
109  IntrinsicRank( 0 ),
111  Unit( 0 ),
112  IsRoot( false )
113 {}
114 
115 
117 {
118  static void* locale = nullptr;
119  static wxString namePrefix;
120 
121  // Fetching translations can take a surprising amount of time when loading libraries,
122  // so only do it when necessary.
123  if( Pgm().GetLocale() != locale )
124  {
125  namePrefix = _( "Unit" );
126  locale = Pgm().GetLocale();
127  }
128 
129  Parent = aParent;
130  Type = UNIT;
131 
132  Unit = aUnit;
133  LibId = aParent->LibId;
134 
135  Name = namePrefix + " " + LIB_PART::SubReference( aUnit, false );
136  Desc = wxEmptyString;
137  MatchName = wxEmptyString;
138 
139  IntrinsicRank = -aUnit;
140 }
141 
142 
144 {
145  wxASSERT( aParent && aAlias );
146 
147  Type = LIBID;
148  Parent = aParent;
149  Update( aAlias );
150 }
151 
152 
154 {
155  CMP_TREE_NODE_UNIT* unit = new CMP_TREE_NODE_UNIT( this, aUnit );
156  Children.push_back( std::unique_ptr<CMP_TREE_NODE>( unit ) );
157  return *unit;
158 }
159 
160 
162 {
163  Name = aAlias->GetName();
164  Desc = aAlias->GetDescription();
165 
166  // Parent node is the library nickname so set the LIB_ID library nickname.
167  IsRoot = aAlias->IsRoot();
168 
169  // Pre-normalized strings for fast case-insensitive matching
170  // Search text spaces out keywords and description to penalize description
171  // matches - earlier matches are worth more.
172  MatchName = aAlias->GetName().Lower();
173  SearchText = (aAlias->GetKeyWords() + " " + Desc);
174 
175  // Extract default footprint text
176  LIB_PART* part = aAlias->GetPart();
177 
178  wxString footprint;
179 
180  if( part )
181  {
182  LibId = part->GetLibId();
184  footprint = part->GetFootprintField().GetText();
185  }
186 
187  // If a footprint is defined for the part,
188  // add it to the serach string
189  if( !footprint.IsEmpty() )
190  {
191  SearchText += " ";
192  SearchText += footprint;
193  }
194 
195  Children.clear();
196 
197  if( part && part->IsMulti() )
198  {
199  for( int u = 1; u <= part->GetUnitCount(); ++u )
200  AddUnit( u );
201  }
202 
203  SearchTextNormalized = false;
204 }
205 
206 
208 {
209  if( Score <= 0 )
210  return; // Leaf nodes without scores are out of the game.
211 
212  if( !SearchTextNormalized )
213  {
214  SearchText = SearchText.Lower();
215  SearchTextNormalized = true;
216  }
217 
218  // Keywords and description we only count if the match string is at
219  // least two characters long. That avoids spurious, low quality
220  // matches. Most abbreviations are at three characters long.
221  int found_pos = EDA_PATTERN_NOT_FOUND;
222  int matchers_fired = 0;
223 
224  if( aMatcher.GetPattern() == MatchName )
225  {
226  Score += 1000; // exact match. High score :)
227  }
228  else if( aMatcher.Find( MatchName, matchers_fired, found_pos ) )
229  {
230  // Substring match. The earlier in the string the better.
231  Score += matchPosScore( found_pos, 20 ) + 20;
232  }
233  else if( aMatcher.Find( Parent->MatchName, matchers_fired, found_pos ) )
234  {
235  Score += 19; // parent name matches. score += 19
236  }
237  else if( aMatcher.Find( SearchText, matchers_fired, found_pos ) )
238  {
239  // If we have a very short search term (like one or two letters),
240  // we don't want to accumulate scores if they just happen to be in
241  // keywords or description as almost any one or two-letter
242  // combination shows up in there.
243  if( aMatcher.GetPattern().length() >= 2 )
244  {
245  // For longer terms, we add scores 1..18 for positional match
246  // (higher in the front, where the keywords are).
247  Score += matchPosScore( found_pos, 17 ) + 1;
248  }
249  }
250  else
251  {
252  // No match. That's it for this item.
253  Score = 0;
254  }
255 
256  // More matchers = better match
257  Score += 2 * matchers_fired;
258 }
259 
260 
262  wxString const& aName, wxString const& aDesc )
263 {
264  Type = LIB;
265  Name = aName;
266  MatchName = aName.Lower();
267  Desc = aDesc;
268  Parent = aParent;
269  LibId.SetLibNickname( aName );
270 }
271 
272 
274 {
275  CMP_TREE_NODE_LIB_ID* alias = new CMP_TREE_NODE_LIB_ID( this, aAlias );
276  Children.push_back( std::unique_ptr<CMP_TREE_NODE>( alias ) );
277  return *alias;
278 }
279 
280 
282 {
283  Score = 0;
284 
285  for( auto& child: Children )
286  {
287  child->UpdateScore( aMatcher );
288  Score = std::max( Score, child->Score );
289  }
290 }
291 
292 
294 {
295  Type = ROOT;
296 }
297 
298 
299 CMP_TREE_NODE_LIB& CMP_TREE_NODE_ROOT::AddLib( wxString const& aName, wxString const& aDesc )
300 {
301  CMP_TREE_NODE_LIB* lib = new CMP_TREE_NODE_LIB( this, aName, aDesc );
302  Children.push_back( std::unique_ptr<CMP_TREE_NODE>( lib ) );
303  return *lib;
304 }
305 
306 
308 {
309  for( auto& child: Children )
310  child->UpdateScore( aMatcher );
311 }
312 
LIB_FIELD & GetFootprintField()
Return reference to the footprint field.
wxString Name
Actual name of the part.
wxString Desc
Description to be displayed.
CMP_TREE_NODE_LIB & AddLib(wxString const &aName, wxString const &aDesc)
Construct an empty library node, add it to the root, and return it.
wxString const & GetPattern() const
CMP_TREE_NODE_LIB_ID(CMP_TREE_NODE_LIB_ID const &_)=delete
The addresses of CMP_TREE_NODEs are used as unique IDs for the wxDataViewModel, so don&#39;t let them be ...
Part library alias object definition.
bool IsMulti() const
bool SearchTextNormalized
Support for lazy normalization.
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Update the score for this part.
const LIB_ID & GetLibId() const
enum TYPE Type
Node type.
CMP_TREE_NODE_LIB_ID & AddAlias(LIB_ALIAS *aAlias)
Construct a new alias node, add it to this library, and return it.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:65
void ResetScore()
Initialize score to kLowestDefaultScore, recursively.
void SortNodes()
Sort child nodes quickly and recursively (IntrinsicRanks must have been set).
bool IsRoot
Indicates if the symbol is a root symbol instead of an alias.
LIB_ID LibId
LIB_ID determined by the parent library nickname and alias name.
CMP_TREE_NODE_UNIT(CMP_TREE_NODE_UNIT const &_)=delete
The addresses of CMP_TREE_NODEs are used as unique IDs for the wxDataViewModel, so don&#39;t let them be ...
Abstract pattern-matching tool and implementations.
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Update the score for this part.
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Perform the actual search.
bool IsRoot() const
void AssignIntrinsicRanks()
Store intrinsic ranks on all children of this node.
VTBL_ENTRY wxLocale * GetLocale()
Definition: pgm_base.h:175
const wxString & GetText() const
Function GetText returns the string associated with the text object.
Definition: eda_text.h:128
wxString GetDescription() const
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
Define a library symbol object.
wxString MatchName
Normalized name for matching.
static const int EDA_PATTERN_NOT_FOUND
CMP_TREE_NODE_UNIT & AddUnit(int aUnit)
Add a new unit to the component and return it.
static int matchPosScore(int aPosition, int aMaximum)
Node type: library.
Model class in the component selector Model-View-Adapter (mediated MVC) architecture.
CMP_TREE_NODE_ROOT()
Construct the root node.
int SetLibItemName(const UTF8 &aLibItemName, bool aTestForRev=true)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition: lib_id.cpp:232
CMP_TREE_NODE * Parent
Parent node or null.
LIB_PART * GetPart() const
Get the shared LIB_PART.
int SetLibNickname(const UTF8 &aNickname)
Override the logical library name portion of the LIB_ID to aNickname.
Definition: lib_id.cpp:219
int GetUnitCount() const
wxString SearchText
Descriptive text to search.
see class PGM_BASE
Implementation of std::make_unique for pre C++14 compilation environments.
const wxString & GetName() const
#define max(a, b)
Definition: auxiliary.h:86
void Update(LIB_ALIAS *aAlias)
Update the node using data from a LIB_ALIAS object.
PTR_VECTOR Children
List of child nodes.
CMP_TREE_NODE_LIB(CMP_TREE_NODE_LIB const &_)=delete
The addresses of CMP_TREE_NODEs are used as unique IDs for the wxDataViewModel, so don&#39;t let them be ...
size_t i
Definition: json11.cpp:597
static wxString SubReference(int aUnit, bool aAddSeparator=true)
int IntrinsicRank
The rank of the item before any search terms are applied.
static const unsigned kLowestDefaultScore
static int Compare(CMP_TREE_NODE const &aNode1, CMP_TREE_NODE const &aNode2)
Compare two nodes.
int Unit
Actual unit, or zero.
Definition for part library class.
wxString GetKeyWords() const
Node type: unit of component.
int Score
The score of an item resulting from the search algorithm.
Node type: LIB_ID.