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 )
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, 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 ),
120  Score( kLowestDefaultScore ),
121  Normalized( false ),
122  Unit( 0 ),
123  IsRoot( false ),
124  VisLen( 0 )
125 {}
126 
127 
129 {
130  static void* locale = nullptr;
131  static wxString namePrefix;
132 
133  // Fetching translations can take a surprising amount of time when loading libraries,
134  // so only do it when necessary.
135  if( Pgm().GetLocale() != locale )
136  {
137  namePrefix = _( "Unit" );
138  locale = Pgm().GetLocale();
139  }
140 
141  Parent = aParent;
142  Type = UNIT;
143 
144  Unit = aUnit;
145  LibId = aParent->LibId;
146 
147  Name = namePrefix + " " + aItem->GetUnitReference( aUnit );
148  Desc = wxEmptyString;
149  MatchName = wxEmptyString;
150 
151  IntrinsicRank = -aUnit;
152 }
153 
154 
156 {
157  Type = LIBID;
158  Parent = aParent;
159 
160  LibId.SetLibNickname( aItem->GetLibNickname() );
161  LibId.SetLibItemName( aItem->GetName () );
162 
163  Name = aItem->GetName();
164  Desc = aItem->GetDescription();
165 
166  MatchName = aItem->GetName();
167  SearchText = aItem->GetSearchText();
168  Normalized = false;
169 
170  IsRoot = aItem->IsRoot();
171 
172  if( aItem->GetUnitCount() > 1 )
173  {
174  for( int u = 1; u <= aItem->GetUnitCount(); ++u )
175  AddUnit( aItem, u );
176  }
177 }
178 
179 
181 {
182  LIB_TREE_NODE_UNIT* unit = new LIB_TREE_NODE_UNIT( this, aItem, aUnit );
183  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( unit ) );
184  return *unit;
185 }
186 
187 
189 {
190  // Update is called when the names match, so just update the other fields.
191 
193 
194  Desc = aItem->GetDescription();
195 
196  SearchText = aItem->GetSearchText();
197  Normalized = false;
198 
199  IsRoot = aItem->IsRoot();
200  Children.clear();
201 
202  for( int u = 1; u <= aItem->GetUnitCount(); ++u )
203  AddUnit( aItem, u );
204 }
205 
206 
208 {
209  if( Score <= 0 )
210  return; // Leaf nodes without scores are out of the game.
211 
212  if( !Normalized )
213  {
214  MatchName = MatchName.Lower();
215  SearchText = SearchText.Lower();
216  Normalized = true;
217  }
218 
219  // Keywords and description we only count if the match string is at
220  // least two characters long. That avoids spurious, low quality
221  // matches. Most abbreviations are at three characters long.
222  int found_pos = EDA_PATTERN_NOT_FOUND;
223  int matchers_fired = 0;
224 
225  if( aMatcher.GetPattern() == MatchName )
226  {
227  Score += 1000; // exact match. High score :)
228  }
229  else if( aMatcher.Find( MatchName, matchers_fired, found_pos ) )
230  {
231  // Substring match. The earlier in the string the better.
232  Score += matchPosScore( found_pos, 20 ) + 20;
233  }
234  else if( aMatcher.Find( Parent->MatchName, matchers_fired, found_pos ) )
235  {
236  Score += 19; // parent name matches. score += 19
237  }
238  else if( aMatcher.Find( SearchText, matchers_fired, found_pos ) )
239  {
240  // If we have a very short search term (like one or two letters),
241  // we don't want to accumulate scores if they just happen to be in
242  // keywords or description as almost any one or two-letter
243  // combination shows up in there.
244  if( aMatcher.GetPattern().length() >= 2 )
245  {
246  // For longer terms, we add scores 1..18 for positional match
247  // (higher in the front, where the keywords are).
248  Score += matchPosScore( found_pos, 17 ) + 1;
249  }
250  }
251  else
252  {
253  // No match. That's it for this item.
254  Score = 0;
255  }
256 
257  // More matchers = better match
258  Score += 2 * matchers_fired;
259 }
260 
261 
262 LIB_TREE_NODE_LIB::LIB_TREE_NODE_LIB( LIB_TREE_NODE* aParent, wxString const& aName,
263  wxString const& aDesc )
264 {
265  Type = LIB;
266  Name = aName;
267  MatchName = aName.Lower();
268  Desc = aDesc;
269  Parent = aParent;
270  LibId.SetLibNickname( aName );
271 }
272 
273 
275 {
276  LIB_TREE_NODE_LIB_ID* item = new LIB_TREE_NODE_LIB_ID( this, aItem );
277  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( item ) );
278  return *item;
279 }
280 
281 
283 {
284  Score = 0;
285 
286  // We need to score leaf nodes, which are usually (but not always) children.
287 
288  if( Children.size() )
289  {
290  for( auto& child: Children )
291  {
292  child->UpdateScore( aMatcher );
293  Score = std::max( Score, child->Score );
294  }
295  }
296  else
297  {
298  // No children; we are a leaf.
299  int found_pos = EDA_PATTERN_NOT_FOUND;
300  int matchers_fired = 0;
301 
302  if( aMatcher.GetPattern() == MatchName )
303  {
304  Score += 1000; // exact match. High score :)
305  }
306  else if( aMatcher.Find( MatchName, matchers_fired, found_pos ) )
307  {
308  // Substring match. The earlier in the string the better.
309  Score += matchPosScore( found_pos, 20 ) + 20;
310  }
311 
312  // More matchers = better match
313  Score += 2 * matchers_fired;
314  }
315 }
316 
317 
319 {
320  Type = ROOT;
321 }
322 
323 
324 LIB_TREE_NODE_LIB& LIB_TREE_NODE_ROOT::AddLib( wxString const& aName, wxString const& aDesc )
325 {
326  LIB_TREE_NODE_LIB* lib = new LIB_TREE_NODE_LIB( this, aName, aDesc );
327  Children.push_back( std::unique_ptr<LIB_TREE_NODE>( lib ) );
328  return *lib;
329 }
330 
331 
333 {
334  for( auto& child: Children )
335  child->UpdateScore( aMatcher );
336 }
337 
void SortNodes()
Sort child nodes quickly and recursively (IntrinsicRanks must have been set).
int StrNumCmp(const wxString &aString1, const wxString &aString2, bool aIgnoreCase)
Compare two strings with alphanumerical content.
Definition: string.cpp:342
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.
wxString const & GetPattern() const
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:65
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 bool IsRoot() const
For items having aliases, IsRoot() indicates the principal item.
Definition: lib_tree_item.h:54
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:231
Node type: library.
bool Find(const wxString &aTerm, int &aMatchersTriggered, int &aPosition)
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition: lib_id.h:97
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
#define _(s)
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'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't let them be ...
virtual void UpdateScore(EDA_COMBINED_MATCHER &aMatcher) override
Update the score for this part.
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'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