From 577c1dd3322cf4adeffb37f18fb39f489ad57407 Mon Sep 17 00:00:00 2001
From: Jeff Young <jeff@rokeby.ie>
Date: Mon, 13 Jan 2025 16:22:05 +0000
Subject: [PATCH] Also limit the number of search terms (as well as their
 length)

Fixes https://gitlab.com/kicad/code/kicad/-/issues/19464
---
 common/eda_pattern_match.cpp      |  4 ++--
 common/lib_tree_model_adapter.cpp | 14 +++++++++-----
 2 files changed, 11 insertions(+), 7 deletions(-)

diff --git a/common/eda_pattern_match.cpp b/common/eda_pattern_match.cpp
index 8914ef1937..b83033a202 100644
--- a/common/eda_pattern_match.cpp
+++ b/common/eda_pattern_match.cpp
@@ -488,8 +488,8 @@ int EDA_COMBINED_MATCHER::ScoreTerms( std::vector<SEARCH_TERM>& aWeightedTerms )
 
             // Don't cause KiCad to hang if someone accidentally pastes the PCB or schematic
             // into the search box.
-            if( term.Text.Length() > 5000 )
-                term.Text = term.Text.Left( 5000 );
+            if( term.Text.Length() > 1000 )
+                term.Text = term.Text.Left( 1000 );
 
             term.Normalized = true;
         }
diff --git a/common/lib_tree_model_adapter.cpp b/common/lib_tree_model_adapter.cpp
index 9cab31e59f..687d298231 100644
--- a/common/lib_tree_model_adapter.cpp
+++ b/common/lib_tree_model_adapter.cpp
@@ -285,17 +285,21 @@ void LIB_TREE_MODEL_ADAPTER::UpdateSearchString( const wxString& aSearch, bool a
 
         m_tree.ResetScore();
 
-        wxStringTokenizer tokenizer( aSearch );
-        bool              firstTerm = true;
+        // Don't cause KiCad to hang if someone accidentally pastes the PCB or schematic into
+        // the search box.
+        constexpr int MAX_TERMS = 100;
 
-        while( tokenizer.HasMoreTokens() )
+        wxStringTokenizer tokenizer( aSearch );
+        int               termCount = 0;
+
+        while( tokenizer.HasMoreTokens() && termCount < MAX_TERMS )
         {
             // First search for the full token, in case it appears in a search string
             wxString             term = tokenizer.GetNextToken().Lower();
             EDA_COMBINED_MATCHER termMatcher( term, CTX_LIBITEM );
 
             m_tree.UpdateScore( &termMatcher, wxEmptyString, m_filter );
-            firstTerm = false;
+            termCount++;
 
             if( term.Contains( ":" ) )
             {
@@ -308,7 +312,7 @@ void LIB_TREE_MODEL_ADAPTER::UpdateSearchString( const wxString& aSearch, bool a
             }
         }
 
-        if( firstTerm )
+        if( termCount == 0 )
         {
             // No terms processed; just run the filter
             m_tree.UpdateScore( nullptr, wxEmptyString, m_filter );