KiCad PCB EDA Suite
lib_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 <lib_tree_model.h>
23 
24 #include <eda_pattern_match.h>
25 #include <lib_tree_item.h>
26 #include <make_unique.h>
27 #include <utility>
28 #include <pgm_base.h>
29 #include <kicad_string.h>
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<LIB_TREE_NODE*> sort_buf;
65 
66  if( presorted )
67  {
68  int max = Children.size() - 1;
69 
70  for( int i = 0; i <= max; ++i )
71  Children[i]->IntrinsicRank = max - i;
72  }
73  else
74  {
75  for( auto const& node: Children )
76  sort_buf.push_back( &*node );
77 
78  std::sort( sort_buf.begin(), sort_buf.end(),
79  []( LIB_TREE_NODE* a, LIB_TREE_NODE* b ) -> bool
80  { return StrNumCmp( a->Name, b->Name, INT_MAX, true ) > 0; } );
81 
82  for( int i = 0; i < (int) sort_buf.size(); ++i )
83  sort_buf[i]->IntrinsicRank = i;
84  }
85 }
86 
87 
89 {
90  std::sort( Children.begin(), Children.end(),
91  []( std::unique_ptr<LIB_TREE_NODE> const& a, std::unique_ptr<LIB_TREE_NODE> const& b )
92  { return Compare( *a, *b ) > 0; } );
93 
94  for( auto& node: Children )
95  {
96  node->SortNodes();
97  }
98 }
99 
100 
101 int LIB_TREE_NODE::Compare( LIB_TREE_NODE const& aNode1, LIB_TREE_NODE const& aNode2 )
102 {
103  if( aNode1.Type != aNode2.Type )
104  return 0;
105 
106  if( aNode1.Score != aNode2.Score )
107  return aNode1.Score - aNode2.Score;
108 
109  if( aNode1.Parent != aNode2.Parent )
110  return 0;
111 
112  return aNode1.IntrinsicRank - aNode2.IntrinsicRank;
113 }
114 
115 
117  : Parent( nullptr ),
118  Type( INVALID ),
119  IntrinsicRank( 0 ),
121  Normalized( false ),
122  Unit( 0 ),
123  IsRoot( false )
124 {}
125 
126 
128 {
129  static void* locale = nullptr;
130  static wxString namePrefix;
131 
132  // Fetching translations can take a surprising amount of time when loading libraries,
133  // so only do it when necessary.
134  if( Pgm().GetLocale() != locale )
135  {
136  namePrefix = _( "Unit" );
137  locale = Pgm().GetLocale();
138  }
139 
140  Parent = aParent;
141  Type = UNIT;
142 
143  Unit = aUnit;
144  LibId = aParent->LibId;
145 
146  Name = namePrefix + " " + aItem->GetUnitReference( aUnit );
147  Desc = wxEmptyString;
148  MatchName = wxEmptyString;
149 
150  IntrinsicRank = -aUnit;
151 }
152 
153 
155 {
156  Type = LIBID;
157  Parent = aParent;
158 
159  LibId.SetLibNickname( aItem->GetLibNickname() );
160  LibId.SetLibItemName( aItem->GetName () );
161 
162  Name = aItem->GetName();
163  Desc = aItem->GetDescription();
164 
165  MatchName = aItem->GetName();
166  SearchText = aItem->GetSearchText();
167  Normalized = false;
168 
169  IsRoot = aItem->IsRoot();
170 
171  if( aItem->GetUnitCount() > 1 )
172  {
173  for( int u = 1; u <= aItem->GetUnitCount(); ++u )
174  AddUnit( aItem, u );
175  }
176 }
177 
178 
180 {
181  LIB_TREE_NODE_UNIT* unit = new LIB_TREE_NODE_UNIT( this, aItem, aUnit );
182  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( unit ) );
183  return *unit;
184 }
185 
186 
188 {
189  // Update is called when the names match, so just update the other fields.
190 
192 
193  Desc = aItem->GetDescription();
194 
195  SearchText = aItem->GetSearchText();
196  Normalized = false;
197 
198  IsRoot = aItem->IsRoot();
199  Children.clear();
200 
201  for( int u = 1; u <= aItem->GetUnitCount(); ++u )
202  AddUnit( aItem, u );
203 }
204 
205 
207 {
208  if( Score <= 0 )
209  return; // Leaf nodes without scores are out of the game.
210 
211  if( !Normalized )
212  {
213  MatchName = MatchName.Lower();
214  SearchText = SearchText.Lower();
215  Normalized = 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 
261 LIB_TREE_NODE_LIB::LIB_TREE_NODE_LIB( LIB_TREE_NODE* aParent, wxString const& aName,
262  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  LIB_TREE_NODE_LIB_ID* item = new LIB_TREE_NODE_LIB_ID( this, aItem );
276  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( item ) );
277  return *item;
278 }
279 
280 
282 {
283  Score = 0;
284 
285  // We need to score leaf nodes, which are usually (but not always) children.
286 
287  if( Children.size() )
288  {
289  for( auto& child: Children )
290  {
291  child->UpdateScore( aMatcher );
292  Score = std::max( Score, child->Score );
293  }
294  }
295  else
296  {
297  // No children; we are a leaf.
298  int found_pos = EDA_PATTERN_NOT_FOUND;
299  int matchers_fired = 0;
300 
301  if( aMatcher.GetPattern() == MatchName )
302  {
303  Score += 1000; // exact match. High score :)
304  }
305  else if( aMatcher.Find( MatchName, matchers_fired, found_pos ) )
306  {
307  // Substring match. The earlier in the string the better.
308  Score += matchPosScore( found_pos, 20 ) + 20;
309  }
310 
311  // More matchers = better match
312  Score += 2 * matchers_fired;
313  }
314 }
315 
316 
318 {
319  Type = ROOT;
320 }
321 
322 
323 LIB_TREE_NODE_LIB& LIB_TREE_NODE_ROOT::AddLib( wxString const& aName, wxString const& aDesc )
324 {
325  LIB_TREE_NODE_LIB* lib = new LIB_TREE_NODE_LIB( this, aName, aDesc );
326  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( lib ) );
327  return *lib;
328 }
329 
330 
332 {
333  for( auto& child: Children )
334  child->UpdateScore( aMatcher );
335 }
336 
wxString const & GetPattern() const
void SortNodes()
Sort child nodes quickly and recursively (IntrinsicRanks must have been set).
PTR_VECTOR Children
List of child nodes.
enum TYPE Type
Node type.
static int matchPosScore(int aPosition, int aMaximum)
static int Compare(LIB_TREE_NODE const &aNode1, LIB_TREE_NODE const &aNode2)
Compare two nodes.
A mix-in to provide polymorphism between items stored in libraries (symbols, aliases and footprints)...
Definition: lib_tree_item.h:39
bool Normalized
Support for lazy normalization.
Node type: LIB_ID.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Perform the actual search.
LIB_TREE_NODE * Parent
Parent node or null.
int Score
The score of an item resulting from the search algorithm.
Abstract pattern-matching tool and implementations.
virtual wxString GetSearchText()
Definition: lib_tree_item.h:49
LIB_TREE_NODE_LIB_ID & AddItem(LIB_TREE_ITEM *aItem)
Construct a new alias node, add it to this library, and return it.
wxString MatchName
Normalized name for matching.
VTBL_ENTRY wxLocale * GetLocale()
Definition: pgm_base.h:217
Node type: library.
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
LIB_ID LibId
LIB_ID determined by the parent library nickname and alias name.
LIB_TREE_NODE_UNIT & AddUnit(LIB_TREE_ITEM *aItem, int aUnit)
Add a new unit to the component and return it.
virtual const wxString & GetDescription()=0
void ResetScore()
Initialize score to kLowestDefaultScore, recursively.
static const int EDA_PATTERN_NOT_FOUND
Model class in the component selector Model-View-Adapter (mediated MVC) architecture.
static const unsigned kLowestDefaultScore
Node type: unit of component.
wxString Desc
Description to be displayed.
int SetLibItemName(const UTF8 &aLibItemName, bool aTestForRev=true)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition: lib_id.cpp:206
LIB_TREE_NODE_LIB & AddLib(wxString const &aName, wxString const &aDesc)
Construct an empty library node, add it to the root, and return it.
wxString SearchText
Descriptive text to search.
int SetLibNickname(const UTF8 &aNickname)
Override the logical library name portion of the LIB_ID to aNickname.
Definition: lib_id.cpp:193
virtual int GetUnitCount()
For items with units, return the number of units.
Definition: lib_tree_item.h:59
virtual const wxString & GetName() const =0
wxString Name
Actual name of the part.
bool IsRoot
Indicates if the symbol is a root symbol instead of an alias.
void AssignIntrinsicRanks(bool presorted=false)
Store intrinsic ranks on all children of this node.
see class PGM_BASE
virtual LIB_ID GetLibId() const =0
LIB_TREE_NODE_LIB_ID(LIB_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 ...
Implementation of std::make_unique for pre C++14 compilation environments.
virtual wxString GetLibNickname() const =0
#define max(a, b)
Definition: auxiliary.h:86
int Unit
Actual unit, or zero.
size_t i
Definition: json11.cpp:597
LIB_TREE_NODE_ROOT()
Construct the root node.
int IntrinsicRank
The rank of the item before any search terms are applied.
void Update(LIB_TREE_ITEM *aItem)
Update the node using data from a LIB_ALIAS object.
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Update the score for this part.
LIB_TREE_NODE_LIB(LIB_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 ...
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Update the score for this part.
int StrNumCmp(const wxString &aString1, const wxString &aString2, int aLength, bool aIgnoreCase)
Function StrNumCmp is a routine compatible with qsort() to sort by alphabetical order.
Definition: string.cpp:315
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition: lib_id.h:97
virtual bool IsRoot() const
For items having aliases, IsRoot() indicates the principal item.
Definition: lib_tree_item.h:54
LIB_TREE_NODE_UNIT(LIB_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 ...
virtual wxString GetUnitReference(int aUnit)
For items with units, return an identifier for unit x.
Definition: lib_tree_item.h:64