void SetupQueryEngine()
 {
     m_QueryEngine = new QueryEngine <SearcherItem>();
     m_QueryEngine.SetSearchDataCallback(GetSearchData, s => s.ToLowerInvariant(), StringComparison.OrdinalIgnoreCase);
     m_QueryEngine.SetSearchWordMatcher((searchWord, isExact, comparisonOption, searchData) =>
     {
         if (m_MatchIndicesBuffer == null)
         {
             m_MatchIndicesBuffer = new List <int>(searchData.Length);
         }
         else
         {
             m_MatchIndicesBuffer.Clear();
         }
         long score     = 0;
         var fuzzyMatch = FuzzySearch.FuzzyMatch(searchWord, searchData, ref score, m_MatchIndicesBuffer);
         if (m_CurrentItem != null)
         {
             m_CurrentItem.lastMatchedIndices = m_MatchIndicesBuffer;
             m_CurrentItem.lastMatchedString  = searchData;
             m_CurrentItem.lastSearchScore    = (long)(score * m_ScoreMultiplier);
         }
         return(fuzzyMatch);
     });
 }
Exemple #2
0
        public List <ScraperMaster> LevenIteration(List <ScraperMaster> games, string searchStr)
        {
            int levCount = 0;
            List <ScraperMaster> temp = new List <ScraperMaster>();

            while (levCount <= 10)
            {
                levCount++;
                double it = Convert.ToDouble(levCount) / 10;
                List <ScraperMaster> found = FuzzySearch.FSearch(StripSymbols(searchStr.ToLower()), SearchCollection, it);

                if (found.Count == 1)
                {
                    return(found);
                }
                if (found.Count > 1)
                {
                    // multiple entries returned
                    temp = new List <ScraperMaster>();
                    temp.AddRange(found);
                }
                if (found.Count == 0)
                {
                    return(temp);
                }
            }
            return(temp);
        }
        private static IEnumerable <SearchItem> FetchItems(SearchContext context, SearchProvider provider)
        {
            // Cache all available static APIs
            if (methods == null)
            {
                methods = FetchStaticAPIMethodInfo();
            }

            var lowerCasePattern = context.searchQuery.ToLowerInvariant().Replace(" ", "");
            var matches          = new List <int>();

            foreach (var m in methods)
            {
                if (!m.IsPublic && !context.options.HasFlag(SearchFlags.WantsMore))
                {
                    continue;
                }
                long score         = 0;
                var  fullName      = $"{m.DeclaringType.FullName}.{m.Name}";
                var  fullNameLower = fullName.ToLowerInvariant();
                if (FuzzySearch.FuzzyMatch(lowerCasePattern, fullNameLower, ref score, matches) && score > 300)
                {
                    var visibilityString = m.IsPublic ? string.Empty : "(Non Public)";
                    yield return(provider.CreateItem(context, m.Name, m.IsPublic ? ~(int)score - 999 : ~(int)score, m.Name, $"{fullName} {visibilityString}", null, m));
                }
                else
                {
                    yield return(null);
                }
            }
        }
Exemple #4
0
        public ActionResult Index(string sortOrder, string searchString)
        {
            // create new employeeContent object (DAL)
            EmployeeContent epc = new EmployeeContent();

            // Determine all employees(List) using the DAL function
            var           employeeList      = epc.getAllEmployees();
            List <string> firstLastNameList = new List <string>();

            // If the search string is not empty, the result set is reduced to the parameter to be searched in the "First name" and "Last name" columns.
            if (!String.IsNullOrEmpty(searchString))
            {
                ViewBag.SearchingFor = "Tabelle zeigt aktuell alle Treffer mit '" + searchString + "'";

                // Return a list containing the person names with the values we are looking for
                employeeList = employeeList.Where(s => s.LastName.ToLower().Contains(searchString.ToLower()) || s.FirstName.ToLower().Contains(searchString.ToLower())).ToList();

                // first idea of getting the similarities
                foreach (Employees content in employeeList)
                {
                    content.similarity = FuzzySearch.CalculateSimilarity(searchString.ToLower(), (content.FirstName.ToLower() + " " + content.LastName.ToLower()));
                }
            }

            // return the employeelist
            return(View(employeeList));
        }
Exemple #5
0
        public void DescendingStalenessSort()
        {
            var chatScores = new Dictionary <Chat, double>();

            chatScores.Add(Chat.Create("c1").Staleness(3.1), 1);
            chatScores.Add(Chat.Create("c2").Staleness(3), 1);
            chatScores.Add(Chat.Create("c3").Staleness(1.1), 1);
            chatScores.Add(Chat.Create("c4"), 0);
            chatScores.Add(Chat.Create("c5"), 10);

            var list = FuzzySearch.DescendingStalenessRandomizedSort(chatScores);

            for (int i = 1; i < list.Count; i++)
            {
                Assert.That(list[i].Value <= list[i - 1].Value, Is.True);
            }

            //list.ForEach((kvp) => Console.WriteLine(kvp.Key + " -> " + kvp.Value));

            var chats = (from kvp in list select kvp.Key).ToList();

            Assert.That(chats[0].text, Is.EqualTo("c5"));
            Assert.That(chats[1].text, Is.EqualTo("c3"));
            Assert.That(chats[2].text, Is.EqualTo("c2"));
            Assert.That(chats[3].text, Is.EqualTo("c1"));
            Assert.That(chats[4].text, Is.EqualTo("c4"));
        }
Exemple #6
0
 protected override void OnTextChanged(TextChangedEventArgs e)
 {
     base.OnTextChanged(e);
     if (!_fuzzyEnable)
     {
         return;
     }
     _keySelectedIndex = -1;
     if (Text.Length < MinTextLenght)
     {
         _listBoxFilter.ItemsSource = null;
         _popupFilter.IsOpen        = false;
         return;
     }
     FuzzySearch?.BeginInvoke(Text, o =>
     {
         Dispatcher.BeginInvoke(new Action(() =>
         {
             var result = FuzzySearch.EndInvoke(o);
             if (result.Item1 == Text)
             {
                 var source = result.Item2 as IEnumerable;
                 _listBoxFilter.ItemsSource = source;
                 _popupFilter.IsOpen        = source != null;
             }
         }));
     }, null);
 }
        private SearchItem MatchGOD(SearchContext context, SearchProvider provider, GOD god, int index, bool useFuzzySearch, string fuzzyMatchQuery, List <int> FuzzyMatches)
        {
            long score = -1;

            if (useFuzzySearch)
            {
                if (!FuzzySearch.FuzzyMatch(fuzzyMatchQuery, god.name, ref score, FuzzyMatches))
                {
                    return(null);
                }
            }
            else
            {
                if (!MatchSearchGroups(context, god.name, true))
                {
                    return(null);
                }
            }

            var item = provider.CreateItem(god.id, ~(int)score, null,
                                           null,
                                           //$"MatchGOD[{useFuzzySearch}]:{~(int)score} -> {String.Join(";", SceneSearchIndexer.SplitComponents(god.rawname))}",
                                           null, index);

            item.descriptionFormat = SearchItemDescriptionFormat.Ellipsis | SearchItemDescriptionFormat.RightToLeft;
            if (useFuzzySearch)
            {
                item.descriptionFormat |= SearchItemDescriptionFormat.FuzzyHighlight;
            }
            else
            {
                item.descriptionFormat |= SearchItemDescriptionFormat.Highlight;
            }
            return(item);
        }
Exemple #8
0
        private SearchItem MatchGOD(SearchContext context, SearchProvider provider, GOD god, int index, bool useFuzzySearch, string fuzzyMatchQuery, List <int> FuzzyMatches)
        {
            long score = -1;

            if (useFuzzySearch)
            {
                if (!FuzzySearch.FuzzyMatch(fuzzyMatchQuery, god.tokens, ref score, FuzzyMatches))
                {
                    return(null);
                }
            }
            else
            {
                if (!MatchSearchGroups(context, god.tokens, true))
                {
                    return(null);
                }
            }

            var item = provider.CreateItem(god.id, ~(int)score, null, null, null, index);

            item.descriptionFormat = SearchItemDescriptionFormat.Ellipsis | SearchItemDescriptionFormat.RightToLeft;
            if (useFuzzySearch)
            {
                item.descriptionFormat |= SearchItemDescriptionFormat.FuzzyHighlight;
            }
            else
            {
                item.descriptionFormat |= SearchItemDescriptionFormat.Highlight;
            }
            return(item);
        }
        public Utility.Match FuzzyMatch(String searchKey)
        {
            var s      = new FuzzySearch(searchKey, SearchContent);
            var result = s.FindBestMatch();

            UpdateFromFuzzy(result);
            return(result);
        }
        public HttpResponseMessage GetWithService(HttpRequestMessage request, string question = "*", string answer = "*", int serviceid = 0,
                                                  int procedureid = 0, int pagesize = 15, int pageindex = 1)
        {
            Expression <Func <tbFAQ, bool> > questionfilter, answerfilter, serviceidfilter, procedureidfilter = null;

            if (question != "*")
            {
                FuzzySearch _fuzz = new FuzzySearch(question);
                questionfilter = l => _fuzz.IsMatch(l.Question);
            }
            else
            {
                questionfilter = l => l.IsDeleted != true;
            }
            if (answer != "*")
            {
                FuzzySearch _fuzz = new FuzzySearch(answer);
                answerfilter = l => _fuzz.IsMatch(l.Answer);
                //answerfilter = l => l.ManagedbyId == managedbyid;
            }
            else
            {
                answerfilter = l => l.IsDeleted != true;
            }
            if (serviceid != 0)
            {
                serviceidfilter = l => l.ServiceId == serviceid;
            }
            else
            {
                serviceidfilter = l => l.IsDeleted != true;
            }
            if (procedureid != 0)
            {
                procedureidfilter = l => l.ProcedureId == procedureid;
            }
            else
            {
                procedureidfilter = l => l.IsDeleted != true;
            }
            var skipindex = pagesize * (pageindex - 1);
            var obj       = new FAQViewModel
            {
                FAQs = repo.GetWithoutTracking().Where(questionfilter).Where(answerfilter).Where(serviceidfilter).Where(procedureidfilter)
                       .OrderByDescending(a => a.Question).Skip(skipindex).Take(pagesize).ToList(),
                Procedure = procedureRepo.GetWithoutTracking().Where(a => a.ID == procedureid).FirstOrDefault(),
                Service   = serviceRepo.GetWithoutTracking().Where(a => a.ID == serviceid).FirstOrDefault()
            };

            HttpResponseMessage response = request.CreateResponse <FAQViewModel>(HttpStatusCode.OK, obj);

            return(response);
        }
 private static string FuzzyCaseSensitiveMatch <T>(
     IDictionary <string, T> data,
     string search
     )
 {
     return(FuzzySearch.Aggregate(
                null as string,
                (acc, cur) =>
                acc ?? data.Keys.FirstOrDefault(
                    k => k.FuzzyCaseSensitiveMatches(search, cur)
                    )
                ));
 }
Exemple #12
0
        private static SearchItem MatchItem(SearchContext context, SearchProvider provider, string id, string name, bool useFuzzySearch)
        {
            if (context.searchPhrase.Length > 2)
            {
                long score = 99;
                bool foundMatch = !useFuzzySearch
                    ? MatchSearchGroups(context, name, false)
                    : FuzzySearch.FuzzyMatch(context.searchPhrase, name, ref score, s_FuzzyMatches);
                if (foundMatch)
                    return AddResult(provider, id, (~(int)score) + 10000, useFuzzySearch);
            }

            return null;
        }
 public void Match(String searchKey)
 {
     if (SearchContent.Length > ClipViewModel.MaxSearchContentLength)
     {
         var index = SearchContent.IndexOf(searchKey);
         if (index >= 0)
         {
             UpdateRichtTitleFromSingle(index, searchKey.Length);
             SearchScore = FuzzySearch.CalculateMaxScore(searchKey.Length, new ScoreConfig());
         }
     }
     else
     {
         FuzzyMatch(searchKey);
     }
 }
Exemple #14
0
        private bool IsFuzzyMatch(string word, string searchTerm)
        {
            if (word.Length <= 2)
            {
                // For 1-letter and 2-letter words, we need an exact match (no spelling mistakes)
                return(false);
            }
            else
            {
                // For words of more than 3 letters, allow "length/3" spelling mistakes

                int numberOfSpellingMistakes  = FuzzySearch.GetDamerauLevenshteinDistance(word, searchTerm);
                int allowableSpellingMistakes = word.Length / 3;

                return(numberOfSpellingMistakes <= allowableSpellingMistakes);
            }
        }
        internal bool MatchFirstName(int sequence, string input, string requestToken, List <Patient> patList)
        {
            bool status = false;

            try
            {
                List <Patient> matchedSearches = new List <Patient>();
                matchedSearches = FuzzySearch.Search(input.ToLower(), patList, 0.29);
                if (matchedSearches.Count > 0)
                {
                    var insertPatientSearchLogQuery = QueryBuilder.InsertPatientSearchLog(requestToken, sequence, input, "1");
                    int queryStatus = dA.executeInsertSqlStatement(insertPatientSearchLogQuery);
                    if (queryStatus == 1)
                    {
                        var patientSearchLogID       = QueryBuilder.GetPatientSearchLogID(requestToken, sequence);
                        var patientSearchLogIDResult = dA.executeSqlStatement(patientSearchLogID).Tables[0].Rows[0]["PatientSearchLogID"].ToString();
                        //foreach (DataRow patient in queryResult.Tables[0].Rows)
                        foreach (var patient in matchedSearches)
                        {
                            try
                            {
                                //var insertPatientSearchLogDetailQuery = QueryBuilder.InsertPatientSearchLogDetail(patientSearchLogIDResult, patient["PAPATID"].ToString());
                                var insertPatientSearchLogDetailQuery = QueryBuilder.InsertPatientSearchLogDetail(patientSearchLogIDResult, patient.ID.ToString());
                                dA.executeInsertSqlStatement(insertPatientSearchLogDetailQuery);
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    WebApiApplication.getPatFirstName = matchedSearches;
                    status = true;
                }
                else
                {
                    var sqlQuery    = QueryBuilder.InsertPatientSearchLog(requestToken, sequence, input, "0");
                    int queryStatus = dA.executeInsertSqlStatement(sqlQuery);
                }
            }
            catch (Exception ex)
            {
            }
            return(status);
        }
        private ObservableCollection <string> ExecuteSearch(string searchText)
        {
            //string[] filters = searchText.Split(new[] { ' ' });
            //var q = from x in list
            //where filters.All(f => x.Contains(f))
            //select x;

            FuzzySearch _fuzz = new FuzzySearch(searchText);

            var q = from x in list
                    where _fuzz.IsMatch(x)
                    select x;


            //var q = from s in list where s.ToLower().Contains(searchText.ToLower()) select s;
            var results = new ObservableCollection <string>(q);

            return(results);
        }
Exemple #17
0
        private void EnableSearchMode()
        {
            if (!DrawInSearchMode)
            {
                _scrollbar.ToTop();
            }

            DrawInSearchMode = true;

            _searchModeTree.Clear();
            _searchModeTree.AddRange(EnumerateTree()
                                     .Where(node => node.Type != null)
                                     .Select(node =>
            {
                bool includeInSearch = FuzzySearch.CanBeIncluded(_searchString, node.FullTypeName, out int score);
                return(new { score, item = node, include = includeInSearch });
            })
                                     .Where(x => x.include)
                                     .OrderByDescending(x => x.score)
                                     .Select(x => x.item));
        }
Exemple #18
0
        /// <summary>
        /// Consente di individuare se il condomino è residente confrontando l'indirizzo della persona con quello del condominio
        /// </summary>
        /// <remarks>Per stabilire se gli indirizzi corrispondono viene usato un componente di terze parti <see cref="http://www.shuffletext.com/Default.aspx"/></remarks>
        /// <param name="soggetto">Condomino</param>
        /// <returns>Ritorna true se è residente altrimenti false</returns>
        public bool IsResidente(SoggettoCondominio soggetto)
        {
            if (soggetto != null && soggetto.IsResidente == null && soggetto.UnitaImmobiliare != null && soggetto.UnitaImmobiliare.GruppoStabileRiferimento != null && soggetto.Persona != null && soggetto.Persona.IndirizzoResidenza != null && !string.IsNullOrEmpty(soggetto.Persona.IndirizzoResidenza.Indirizzo))
            {
                try
                {
                    var condominio = soggetto.UnitaImmobiliare.GruppoStabileRiferimento.PalazzinaRiferimento.CondominioRiferimento;

                    if (condominio.Indirizzo != null)
                    {
                        var person = new SearchableDictionary<int>();
                        var fuzzy = new FuzzySearch<int>();
                        var query = new Query(QuerySearchOption.And, new NameSynonymThesaurusReader(), 0.75);
                        var scope = new IntellisenseScope<int>();

                        var persona = soggetto.Persona;

                        var indirizzoSoggetto = persona.IndirizzoResidenza.GetIndirizzoCompleto();
                        var indirizzoCondominio = condominio.Indirizzo.GetIndirizzoCompleto();

                        if (!string.IsNullOrEmpty(indirizzoSoggetto) && !string.IsNullOrEmpty(indirizzoCondominio))
                        {
                            person.Add(persona.ID, string.Format("{0}", indirizzoSoggetto));
                            fuzzy.Add(persona.ID, "Indirizzo", indirizzoSoggetto);

                            query.Clear();
                            query.CreateSearchTerm("Indirizzo", indirizzoCondominio, 0.20, true);

                            var fuzzyResult = fuzzy.Search(query, scope, 1);
                            return fuzzyResult.Count > 0 && fuzzyResult[0].Rank > 1;
                        }

                        return true;
                    }

                }
                catch (Exception ex)
                {
                    
                    _log.Warn("Errore inaspettato durante il set di residente - " + Library.Utility.GetMethodDescription(), ex);
                    return false;
                }
            }

            return false;
        }
        public SearchResultViewModel Search(string query, IEnumerable <Event> events, string sortBy = "relevant")
        {
            SearchResultViewModel foundEvent = new SearchResultViewModel();

            if (!String.IsNullOrEmpty(query))
            {
                foreach (Event evt in events)
                {
                    List <String> splittedEvent = new List <String>();
                    String        eventName     = evt.EventName;
                    for (var i = 0; i <= eventName.Length - query.Length; i++)
                    {
                        splittedEvent.Add(eventName.Substring(i, query.Length));
                    }

                    List <string> foundbyTitle = FuzzySearch.Search(query.ToLower(), splittedEvent, 0.50);

                    List <String> splittedArtist = new List <String>();

                    List <string> foundbyArtist = new List <string>();
                    if (evt.Artist != null)
                    {
                        String Artist = evt.Artist;
                        for (var i = 0; i <= Artist.Length - query.Length; i++)
                        {
                            splittedArtist.Add(Artist.Substring(i, query.Length));
                        }

                        foundbyArtist = FuzzySearch.Search(query.ToLower(), splittedArtist, 0.5);
                    }

                    if (foundbyTitle.Count > 0 || foundbyArtist.Count > 0)
                    {
                        ResultEvent Event = new ResultEvent(evt);
                        Event.EventName.Matches = Utils.ReduceRedundancy(foundbyTitle);
                        Event.Artist.Matches    = Utils.ReduceRedundancy(foundbyArtist);

                        foundEvent.Result.Add(Event);
                    }
                    else
                    {
                        if (Utils.ConvertVN(evt.EventName).ToLower().Contains(Utils.ConvertVN(query.ToLower())))
                        {
                            ResultEvent Event = new ResultEvent(evt);
                            Event.EventName.Matches = new List <string> {
                                query
                            };
                            Event.IsFuzz = false;
                            foundEvent.Result.Add(Event);
                        }
                    }
                }



                ResultEventComparer comparer = new ResultEventComparer();

                if (sortBy == "relevant")
                {
                    comparer.ComparisonMethod = ResultEventComparer.ComparisonType.Relevant;
                    foundEvent.Result.Sort(comparer);
                }
                else if (sortBy == "HoldDate")
                {
                    comparer.ComparisonMethod = ResultEventComparer.ComparisonType.HoldDate;
                    foundEvent.Result.Sort(comparer);
                }

                return(foundEvent);
            }
            return(null);
        }
Exemple #20
0
        public void DescendingLastRunAtSort()
        {
            var chatScores = new Dictionary <Chat, double>();

            chatScores.Add(Chat.Create("c1").LastRunAt(Util.EpochMs()), 1);
            chatScores.Add(Chat.Create("c2").LastRunAt(Util.EpochMs()), 2);
            chatScores.Add(Chat.Create("c3").LastRunAt(Util.EpochMs()), 3);
            chatScores.Add(Chat.Create("c4").LastRunAt(Util.EpochMs()), 4);
            chatScores.Add(Chat.Create("c5").LastRunAt(Util.EpochMs()), 5);

            var chats = FuzzySearch.DescendingScoreLastRunAtRandomizedSort(chatScores);

            //chats.ForEach((obj) => Console.WriteLine(obj.Key.text));

            for (int i = 0; i < 5; i++)
            {
                Assert.That(chats[i].Key.text, Is.EqualTo("c" + (5 - i)));
            }

            ////////////////////////////////////////////////////////////////////

            chatScores = new Dictionary <Chat, double>();
            chatScores.Add(Chat.Create("c1").LastRunAt(Util.EpochMs()), 1);
            chatScores.Add(Chat.Create("c2").LastRunAt(Util.EpochMs()), 2);
            chatScores.Add(Chat.Create("c3").LastRunAt(Util.EpochMs()), 3);
            chatScores.Add(Chat.Create("c4").LastRunAt(Util.EpochMs()), 5);
            chatScores.Add(Chat.Create("c5").LastRunAt(Util.EpochMs() - 1), 5);

            chats = FuzzySearch.DescendingScoreLastRunAtRandomizedSort(chatScores);
            //chats.ForEach((obj) => Console.WriteLine(obj.Key.text));

            for (int i = 0; i < 5; i++)
            {
                Assert.That(chats[i].Key.text, Is.EqualTo("c" + (5 - i)));
            }

            ////////////////////////////////////////////////////////////////////

            chatScores = new Dictionary <Chat, double>();
            chatScores.Add(Chat.Create("c1").LastRunAt(Util.EpochMs()), 1);
            chatScores.Add(Chat.Create("c2").LastRunAt(Util.EpochMs()), 2);
            chatScores.Add(Chat.Create("c3").LastRunAt(Util.EpochMs()), 3);
            chatScores.Add(Chat.Create("c4").LastRunAt(Util.EpochMs()), 5);
            chatScores.Add(Chat.Create("c5").LastRunAt(-1), 5);

            chats = FuzzySearch.DescendingScoreLastRunAtRandomizedSort(chatScores);
            //chats.ForEach((obj) => Console.WriteLine(obj.Key.text));

            for (int i = 0; i < 5; i++)
            {
                Assert.That(chats[i].Key.text, Is.EqualTo("c" + (5 - i)));
            }

            //////////////////////////////////////////////////////////////////////

            chatScores = new Dictionary <Chat, double>();
            chatScores.Add(Chat.Create("c1").LastRunAt(Util.EpochMs()), 1);
            chatScores.Add(Chat.Create("c2").LastRunAt(Util.EpochMs()), 2);
            chatScores.Add(Chat.Create("c3").LastRunAt(Util.EpochMs()), 3);
            chatScores.Add(Chat.Create("c4").LastRunAt(-1), 5);
            chatScores.Add(Chat.Create("c5").LastRunAt(-1), 5);

            for (int j = 0; j < 10; j++) // repeat a few times
            {
                chats = FuzzySearch.DescendingScoreLastRunAtRandomizedSort(chatScores);
                //chats.ForEach(obj => Console.Write(obj.Key.text+ ", "));Console.WriteLine();
                Assert.That(chats[0].Key.text, Is.EqualTo("c5").Or.EqualTo("c4"));
                Assert.That(chats[0].Key.text, Is.EqualTo("c4").Or.EqualTo("c5"));
                Assert.That(chats[2].Key.text, Is.EqualTo("c3"));
                Assert.That(chats[3].Key.text, Is.EqualTo("c2"));
                Assert.That(chats[4].Key.text, Is.EqualTo("c1"));
            }

            //////////////////////////////////////////////////////////////////////

            chatScores = new Dictionary <Chat, double>();

            chatScores.Add(Chat.Create("c1").LastRunAt(Util.EpochMs()), 1);
            chatScores.Add(Chat.Create("c2").LastRunAt(Util.EpochMs() - 1000), 1);
            chatScores.Add(Chat.Create("c3").LastRunAt(Util.EpochMs() - 2000), 1);
            chatScores.Add(Chat.Create("c4"), 0);
            chatScores.Add(Chat.Create("c5"), 10);

            chats = FuzzySearch.DescendingScoreLastRunAtRandomizedSort(chatScores);
            for (int i = 0; i < chats.Count; i++)
            {
                //Console.WriteLine(chats[i].Key + "(" + chats[i].Key.lastRunAt + ") -> " + chats[i].Value);
                if (i + 1 < chats.Count)
                {
                    Assert.That(chats[i + 1].Value <= chats[i].Value, Is.True);
                }
            }

            Assert.That(chats[0].Key.text, Is.EqualTo("c5"));
            Assert.That(chats[1].Key.text, Is.EqualTo("c3"));
            Assert.That(chats[2].Key.text, Is.EqualTo("c2"));
            Assert.That(chats[3].Key.text, Is.EqualTo("c1"));
            Assert.That(chats[4].Key.text, Is.EqualTo("c4"));
        }
Exemple #21
0
        public SceneProvider(string providerId, string filterId, string displayName)
            : base(providerId, displayName)
        {
            priority      = 50;
            this.filterId = filterId;

            isEnabledForContextualSearch = () =>
                                           Utils.IsFocusedWindowTypeName("SceneView") ||
                                           Utils.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => m_HierarchyChanged = true;

            onEnable = () =>
            {
                if (m_HierarchyChanged)
                {
                    m_GameObjects      = fetchGameObjects();
                    m_SceneQueryEngine = new SceneQueryEngine(m_GameObjects);
                    m_HierarchyChanged = false;
                }
            };

            onDisable = () =>
            {
                // Only track changes that occurs when Quick Search is not active.
                m_HierarchyChanged = false;
            };

            toObject = (item, type) => ObjectFromItem(item);

            fetchItems = (context, items, provider) => SearchItems(context, provider);

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                if (context.searchView == null || context.searchView.displayMode == DisplayMode.List)
                {
                    var transformPath = SearchUtils.GetTransformPath(go.transform);
                    var components    = go.GetComponents <Component>();
                    if (components.Length > 2 && components[1] && components[components.Length - 1])
                    {
                        item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length - 1].GetType().Name})";
                    }
                    else if (components.Length > 1 && components[1])
                    {
                        item.label = $"{transformPath} ({components[1].GetType().Name})";
                    }
                    else
                    {
                        item.label = $"{transformPath} ({item.id})";
                    }

                    long       score   = 1;
                    List <int> matches = new List <int>();
                    var        sq      = Utils.CleanString(context.searchQuery);
                    if (FuzzySearch.FuzzyMatch(sq, Utils.CleanString(item.label), ref score, matches))
                    {
                        item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                    }
                }
                else
                {
                    item.label = go.name;
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                var go = ObjectFromItem(item);
                return(item.description = SearchUtils.GetHierarchyPath(go));
            };

            fetchThumbnail = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(null);
                }

                return(item.thumbnail = Utils.GetThumbnailForGameObject(obj));
            };

            fetchPreview = (item, context, size, options) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(item.thumbnail);
                }

                var sr = obj.GetComponent <SpriteRenderer>();
                if (sr && sr.sprite && sr.sprite.texture)
                {
                    return(sr.sprite.texture);
                }

                #if PACKAGE_UGUI
                var uii = obj.GetComponent <UnityEngine.UI.Image>();
                if (uii && uii.mainTexture is Texture2D uiit)
                {
                    return(uiit);
                }
                #endif

                var preview = AssetPreview.GetAssetPreview(obj);
                if (preview)
                {
                    return(preview);
                }

                var assetPath = SearchUtils.GetHierarchyAssetPath(obj, true);
                if (String.IsNullOrEmpty(assetPath))
                {
                    return(item.thumbnail);
                }
                return(Utils.GetAssetPreviewFromPath(assetPath, size, options));
            };

            startDrag = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    Utils.StartDrag(obj, item.label);
                }
            };

            trackSelection = (item, context) => PingItem(item);

            fetchGameObjects       = SceneQueryEngine.FetchGameObjects;
            buildKeywordComponents = SceneQueryEngine.BuildKeywordComponents;
        }
Exemple #22
0
        /// <summary>
        /// Fuzzy string matching (not currently used)
        /// </summary>
        /// <param name="searchStr"></param>
        /// <param name="manualIterator"></param>
        private void StartFuzzySearch(string searchStr, int manualIterator)
        {
            // start iterator
            if (manualIterator > 0)
            {
            }
            else
            {
                LocalIterationCount++;
                manualIterator = LocalIterationCount;
            }

            // setup fuzzystring options based on iteration
            List <FuzzyStringComparisonOptions> fuzzOptions = new List <FuzzyStringComparisonOptions>();
            FuzzyStringComparisonTolerance      tolerance;

            switch (manualIterator)
            {
            /* Iterations to widen the selection */
            // first auto iteration - strong matching using substring, subsequence and overlap coefficient
            case 1:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Normal;
                break;

            // second iteration - same as the first but with normal matching
            case 2:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Normal;
                break;

            // 3rd auto iteration - same as the first but with weak matching
            case 3:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Weak;
                break;

            /* Iterations to narrow down selection */
            // first manual iteration
            case 100:
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseNormalizedLevenshteinDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubsequence);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaccardDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseHammingDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseJaroWinklerDistance);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseLongestCommonSubstring);
                //fuzzOptions.Add(FuzzyStringComparisonOptions.UseOverlapCoefficient);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseRatcliffObershelpSimilarity);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseSorensenDiceDistance);
                fuzzOptions.Add(FuzzyStringComparisonOptions.UseTanimotoCoefficient);
                tolerance = FuzzyStringComparisonTolerance.Strong;
                break;

            default:
                // end and return
                return;
            }

            // iterate through each gamesdb game in the list
            foreach (ScraperMaster g in SystemCollection)
            {
                bool result = searchStr.ApproximatelyEquals(g.GDBTitle, tolerance, fuzzOptions.ToArray());
                if (result == true)
                {
                    // match found - add to searchcollection
                    SearchCollection.Add(g);
                }
                else
                {
                    // match not found
                }
            }

            if (SearchCollection.Count == 1)
            {
                WorkingSearchCollection = SearchCollection;
                return;
            }

            // Check whether the actual game name contains the actual search
            //GDBPlatformGame gp = SystemCollection.Where(a => StripSymbols(a.GameTitle.ToLower()).Contains(searchStr)).FirstOrDefault();
            List <ScraperMaster> gp = SystemCollection.Where(a => AddTrailingWhitespace(a.GDBTitle.ToLower()).Contains(AddTrailingWhitespace(SearchString))).ToList();

            if (gp == null)
            {
                // nothing found - proceed to other searches
            }
            else
            {
                if (gp.Count > 1)
                {
                    // multiples found - wipe out search collection and create a new one
                    SearchCollection = new List <ScraperMaster>();
                    SearchCollection.AddRange(gp);
                }
                else
                {
                    // only 1 entry found - return
                    SearchCollection = new List <ScraperMaster>();
                    SearchCollection.AddRange(gp);
                    WorkingSearchCollection = new List <ScraperMaster>();
                    WorkingSearchCollection.AddRange(gp);
                    return;
                }
            }


            // we should now have a pretty wide SearchCollection - count how many matched words
            Dictionary <ScraperMaster, int> totals = new Dictionary <ScraperMaster, int>();

            foreach (ScraperMaster g in SearchCollection)
            {
                int matchingWords = 0;
                // get total substrings in search string
                string[] arr          = BuildArray(searchStr);
                int      searchLength = arr.Length;

                // get total substrings in result string
                string[] rArr         = BuildArray(g.GDBTitle);
                int      resultLength = rArr.Length;

                // find matching words
                foreach (string s in arr)
                {
                    int i = 0;
                    while (i < resultLength)
                    {
                        if (StripSymbols(s) == StripSymbols(rArr[i]))
                        {
                            matchingWords++;
                            break;
                        }
                        i++;
                    }
                }
                // add to dictionary with count
                totals.Add(g, matchingWords);
            }

            // order dictionary
            totals.OrderByDescending(a => a.Value);
            // get max value
            var maxValueRecord = totals.OrderByDescending(v => v.Value).FirstOrDefault();
            int maxValue       = maxValueRecord.Value;
            // select all records that have the max value
            List <ScraperMaster> matches = (from a in totals
                                            where a.Value == maxValue
                                            select a.Key).ToList();

            if (matches.Count == 1)
            {
                // single match found
                WorkingSearchCollection = new List <ScraperMaster>();
                WorkingSearchCollection.AddRange(matches);
                return;
            }

            // run levenshetein fuzzy search on SearchCollection - 10 iterations
            int levCount = 0;

            while (levCount <= 10)
            {
                levCount++;
                double it = Convert.ToDouble(levCount) / 10;
                List <ScraperMaster> found = FuzzySearch.FSearch(searchStr, SearchCollection, it);
                //WorkingSearchCollection = new List<GDBPlatformGame>();

                if (found.Count == 1)
                {
                    // one entry returned
                    WorkingSearchCollection = new List <ScraperMaster>();
                    WorkingSearchCollection.AddRange(found);
                    return;
                }
                if (found.Count > 1)
                {
                    // multiple entries returned
                }

                if (found.Count == 0)
                {
                }

                //WorkingSearchCollection.AddRange(found);
                //return;
            }

            //return;

            // check how many matches we have
            if (SearchCollection.Count == 1)
            {
                WorkingSearchCollection = new List <ScraperMaster>();
                WorkingSearchCollection.Add(SearchCollection.Single());
                return;
            }

            if (SearchCollection.Count > 1)
            {
                // add to working search collection
                WorkingSearchCollection.AddRange(SearchCollection.ToList());
                // clear SearchCollection
                //SearchCollection = new List<GDBPlatformGame>();

                // try the first word
                string[] arr     = BuildArray(searchStr);
                int      i       = 0;
                string   builder = "";
                while (i < arr.Length)
                {
                    if (i == 0)
                    {
                        builder += arr[i];
                    }
                    else
                    {
                        builder += " " + arr[i];
                    }
                    string b = StripSymbols(builder).ToLower();


                    var s = SystemCollection.Where(a => a.GDBTitle.ToLower().Contains(b)).ToList();
                    if (s.Count == 1)
                    {
                        // one entry returned - this is the one to keep
                        WorkingSearchCollection = new List <ScraperMaster>();
                        //SearchCollection = new List<GDBPlatformGame>();
                        WorkingSearchCollection.Add(s.Single());
                        return;
                    }
                    if (s.Count > 1)
                    {
                        // still multiple entries returned - single match not found - continue
                        WorkingSearchCollection = new List <ScraperMaster>();
                        WorkingSearchCollection.AddRange(s);
                        //SearchCollection = new List<GDBPlatformGame>();
                    }
                    if (s.Count == 0)
                    {
                        // no matches returned - this should never happen
                    }
                    i++;
                }

                // multiple matches found - run search again from the beginning but remove FIRST substring
                //StartFuzzySearch(searchStr, 100);
                return;

                /*
                 * string[] arr = BuildArray(searchStr);
                 * StartFuzzySearch(BuildSearchString(arr.Take(0).ToArray()), 1);
                 * // multiple matches found - run search again from the beginning but remove last substring
                 * StartFuzzySearch(BuildSearchString(arr.Take(arr.Count() - 1).ToArray()), 1);
                 */
            }
            if (SearchCollection.Count == 0)
            {
                // no matches found - run this method again with the next iterator (slightly weaker tolerance)
                StartFuzzySearch(searchStr, 0);
            }
        }
Exemple #23
0
        public static IEnumerable <FindResult> Search(SearchContext context, SearchProvider provider, FindOptions options)
        {
            var searchQuery = context.searchQuery;

            if (string.IsNullOrEmpty(searchQuery) || searchQuery.Length < 2)
            {
                yield break;
            }

            #if DEBUG_FIND_PROVIDER
            using (new DebugTimer($"Searching {s_FileCount} files with <i>{searchQuery}</i> ({options})"))
            #endif
            {
                var roots      = GetRoots(options);
                var results    = new ConcurrentBag <FindResult>();
                var searchTask = Task.Run(() =>
                {
                    Regex globRx   = null, rxm = null;
                    var validRx    = options.HasFlag(FindOptions.Regex) && ParseRx(searchQuery, out rxm);
                    var validGlob  = options.HasFlag(FindOptions.Glob) && ParseGlob(searchQuery, out globRx);
                    var validWords = options.HasFlag(FindOptions.Words);
                    var validFuzzy = options.HasFlag(FindOptions.Fuzzy);
                    Parallel.ForEach(roots, r =>
                    {
                        var isPackage = options.HasFlag(FindOptions.Packages) && r.StartsWith("Packages/", StringComparison.Ordinal);
                        if (!options.HasFlag(FindOptions.Packages) && isPackage)
                        {
                            return;
                        }

                        if (!s_RootFilePaths.TryGetValue(r, out var files))
                        {
                            files = new ConcurrentDictionary <string, byte>(Directory.EnumerateFiles(r, "*.meta", SearchOption.AllDirectories)
                                                                            .Select(p => p.Substring(0, p.Length - 5).Replace("\\", "/")).ToDictionary(p => p, p => (byte)0));
                            s_RootFilePaths.TryAdd(r, files);
                            #if DEBUG_FIND_PROVIDER
                            s_FileCount += files.Length;
                            #endif
                        }

                        Parallel.ForEach(files, kvp =>
                        {
                            try
                            {
                                var f           = kvp.Key;
                                long fuzzyScore = 0;
                                int score       = isPackage ? (int)FindOptions.Packages : 0;
                                if (validWords && SearchUtils.MatchSearchGroups(context, f, true))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Words));
                                }
                                else if (validRx && rxm.IsMatch(f))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Regex));
                                }
                                else if (validGlob && globRx.IsMatch(f))
                                {
                                    results.Add(new FindResult(f, score | (int)FindOptions.Glob));
                                }
                                else if (validFuzzy && FuzzySearch.FuzzyMatch(searchQuery, f, ref fuzzyScore))
                                {
                                    results.Add(new FindResult(f, ComputeFuzzyScore(score, fuzzyScore)));
                                }
                            }
                            catch
                            {
                                // ignore
                            }
                        });
                    });
                });

                while (results.Count > 0 || !searchTask.Wait(1) || results.Count > 0)
                {
                    if (results.TryTake(out var e))
                    {
                        yield return(e);
                    }
                }
            }
        }
Exemple #24
0
        public SceneProvider(string providerId, string filterId, string displayName)
            : base(providerId, displayName)
        {
            priority           = 50;
            this.filterId      = filterId;
            showDetails        = true;
            showDetailsOptions = ShowDetailsOptions.Inspector | ShowDetailsOptions.Actions | ShowDetailsOptions.Preview | ShowDetailsOptions.DefaultGroup;

            isEnabledForContextualSearch = () =>
                                           Utils.IsFocusedWindowTypeName("SceneView") ||
                                           Utils.IsFocusedWindowTypeName("SceneHierarchyWindow");

            SearchMonitor.sceneChanged         += InvalidateScene;
            SearchMonitor.documentsInvalidated += Refresh;

            SearchMonitor.objectChanged += OnObjectChanged;

            supportsSyncViewSearch = true;

            toObject = (item, type) => ObjectFromItem(item, type);
            toKey    = (item) => ToKey(item);

            fetchItems = (context, items, provider) => SearchItems(context, provider);

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                if (context == null || context.searchView == null || context.searchView.displayMode == DisplayMode.List)
                {
                    var transformPath = SearchUtils.GetTransformPath(go.transform);
                    if (item.options.HasAny(SearchItemOptions.Compacted))
                    {
                        item.label = transformPath;
                    }
                    else
                    {
                        var components = go.GetComponents <Component>();
                        if (components.Length > 2 && components[1] && components[components.Length - 1])
                        {
                            item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length - 1].GetType().Name})";
                        }
                        else if (components.Length > 1 && components[1])
                        {
                            item.label = $"{transformPath} ({components[1].GetType().Name})";
                        }
                        else
                        {
                            item.label = $"{transformPath} ({item.id})";
                        }
                    }

                    if (context != null)
                    {
                        long       score   = 1;
                        List <int> matches = new List <int>();
                        var        sq      = Utils.CleanString(context.searchQuery);
                        if (FuzzySearch.FuzzyMatch(sq, Utils.CleanString(item.label), ref score, matches))
                        {
                            item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                        }
                    }
                }
                else
                {
                    item.label = go.name;
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                var go = ObjectFromItem(item);
                return(item.description = SearchUtils.GetHierarchyPath(go));
            };

            fetchThumbnail = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(null);
                }

                return(item.thumbnail = Utils.GetThumbnailForGameObject(obj));
            };

            fetchPreview = (item, context, size, options) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(item.thumbnail);
                }
                return(Utils.GetSceneObjectPreview(obj, size, options, item.thumbnail));
            };

            startDrag = (item, context) =>
            {
                if (context.selection.Count > 1)
                {
                    Utils.StartDrag(context.selection.Select(i => ObjectFromItem(i)).ToArray(), item.GetLabel(context, true));
                }
                else
                {
                    Utils.StartDrag(new[] { ObjectFromItem(item) }, item.GetLabel(context, true));
                }
            };

            fetchPropositions = (context, options) =>
            {
                if (options.HasAny(SearchPropositionFlags.QueryBuilder))
                {
                    return(FetchQueryBuilderPropositions(context));
                }
                return(m_SceneQueryEngine == null ? new SearchProposition[0] : m_SceneQueryEngine.FindPropositions(context, options));
            };

            trackSelection = (item, context) => PingItem(item);

            fetchColumns = (context, items) => SceneSelectors.Enumerate(items);
        }
Exemple #25
0
        public SceneProvider(string providerId, string filterId, string displayName)
            : base(providerId, displayName)
        {
            priority = 50;
            this.filterId = filterId;
            this.showDetails = true;

            subCategories = new List<NameEntry>
            {
                new NameEntry("fuzzy", "fuzzy")
            };

            isEnabledForContextualSearch = () =>
                QuickSearch.IsFocusedWindowTypeName("SceneView") ||
                QuickSearch.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => m_HierarchyChanged = true;

            onEnable = () =>
            {
                if (m_HierarchyChanged)
                {
                    m_BuildIndexEnumerator = null;
                    m_HierarchyChanged = false;
                }
            };

            onDisable = () =>
            {
                // Only track changes that occurs when Quick Search is not active.
                m_HierarchyChanged = false;
            };

            fetchItems = (context, items, provider) => SearchItems(context, provider);

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                    return item.label;

                var go = ObjectFromItem(item);
                if (!go)
                    return item.id;

                var transformPath = GetTransformPath(go.transform);
                var components = go.GetComponents<Component>();
                if (components.Length > 2 && components[1] && components[components.Length-1])
                    item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length-1].GetType().Name})";
                else if (components.Length > 1 && components[1])
                    item.label = $"{transformPath} ({components[1].GetType().Name})";
                else
                    item.label = $"{transformPath} ({item.id})";

                long score = 1;
                List<int> matches = new List<int>();
                var sq = CleanString(context.searchQuery);
                if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches))
                    item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);

                return item.label;
            };

            fetchDescription = (item, context) =>
            {
                var go = ObjectFromItem(item);
                return (item.description = GetHierarchyPath(go));
            };

            fetchThumbnail = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                    return null;

                return (item.thumbnail = Utils.GetThumbnailForGameObject(obj));
            };

            fetchPreview = (item, context, size, options) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                    return item.thumbnail;

                var assetPath = GetHierarchyAssetPath(obj, true);
                if (String.IsNullOrEmpty(assetPath))
                    return item.thumbnail;
                return Utils.GetAssetPreviewFromPath(assetPath, size, options) ?? AssetPreview.GetAssetPreview(obj);
            };

            startDrag = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj != null)
                    Utils.StartDrag(obj, item.label);
            };

            fetchGameObjects = FetchGameObjects;
            buildKeywordComponents = o => null;

            trackSelection = (item, context) => PingItem(item);
        }
Exemple #26
0
        /// <summary>
        /// Draws the search toolbar.
        /// </summary>
        public void DrawSearchToolbar(GUIStyle toolbarStyle = null)
        {
            var config = this.Config;

            var searchFieldRect = GUILayoutUtility.GetRect(0, config.SearchToolbarHeight, GUILayoutOptions.ExpandWidth(true));

            if (Event.current.type == EventType.Repaint)
            {
                (toolbarStyle ?? SirenixGUIStyles.ToolbarBackground).Draw(searchFieldRect, GUIContent.none, 0);
            }

            searchFieldRect       = searchFieldRect.HorizontalPadding(5).AlignMiddle(16);
            searchFieldRect.xMin += 3;
            searchFieldRect.y    += 1;

            EditorGUI.BeginChangeCheck();
            config.SearchTerm = this.DrawSearchField(searchFieldRect, config.SearchTerm, config.AutoFocusSearchBar);
            var changed = EditorGUI.EndChangeCheck();

            if ((changed || this.updateSearchResults) && this.hasRepaintedCurrentSearchResult)
            {
                this.updateSearchResults = false;

                // We want fast visual search feedback. If the user is typing faster than the window can repaint,
                // then no results will be visible while he's typing. this.hasRepaintedCurrentSearchResult fixes that.

                this.hasRepaintedCurrentSearchResult = false;
                bool doSearch = !string.IsNullOrEmpty(config.SearchTerm);
                if (doSearch)
                {
                    if (!this.DrawInSearchMode)
                    {
                        config.ScrollPos = new Vector2();
                    }

                    this.DrawInSearchMode = true;

                    if (config.SearchFunction != null)
                    {
                        // Custom search
                        this.FlatMenuTree.Clear();
                        foreach (var item in this.EnumerateTree())
                        {
                            if (config.SearchFunction(item))
                            {
                                this.FlatMenuTree.Add(item);
                            }
                        }
                    }
                    else
                    {
                        // Fuzzy search with sorting.
                        this.FlatMenuTree.Clear();
                        this.FlatMenuTree.AddRange(
                            this.EnumerateTree()
                            .Where(x => x.Value != null)
                            .Select(x =>
                        {
                            int score;
                            bool include = FuzzySearch.Contains(this.Config.SearchTerm, x.SearchString, out score);
                            return(new { score = score, item = x, include = include });
                        })
                            .Where(x => x.include)
                            .OrderByDescending(x => x.score)
                            .Select(x => x.item));
                    }

                    this.root.UpdateFlatMenuItemNavigation();
                }
                else
                {
                    this.DrawInSearchMode = false;
                    // Ensure all selected elements are visible, and scroll to the last one.
                    this.FlatMenuTree.Clear();
                    var last = this.selection.LastOrDefault();
                    this.UpdateMenuTree();
                    this.Selection.SelectMany(x => x.GetParentMenuItemsRecursive(false)).ForEach(x => x.Toggled = true);
                    if (last != null)
                    {
                        this.ScrollToMenuItem(last);
                    }

                    this.root.UpdateFlatMenuItemNavigation();
                }
            }

            if (Event.current.type == EventType.Repaint)
            {
                this.hasRepaintedCurrentSearchResult = true;
            }
        }
Exemple #27
0
        public void RicercaPersone()
        {
            var info = new Gipasoft.Business.Sfera.Repository.UserInfo {Azienda = Login.Instance.CurrentLogin().Azienda};
            var soggetti = SferaServiceProxy.Instance.CurrentService().GetSoggettiCondominioByCondominio(119, info);

            var person = new SearchableDictionary<int>();
            var fuzzy = new FuzzySearch<int>();
            var query = new Query(QuerySearchOption.And, new NameSynonymThesaurusReader(), 0.75);
            var scope = new IntellisenseScope<int>();

            var dict = new Dictionary<int, PersonaDTO>();
            foreach (var soggetto in soggetti.Distinct())
            {
                var persona = SferaServiceProxy.Instance.CurrentService().GetPersonaByID(soggetto.IdPersona, info);
                if (!dict.ContainsKey(persona.ID))
                {
                    person.Add(persona.ID,
                               String.Format("{0} {1} {2}", persona.IndirizzoResidenza.Indirizzo,
                                             persona.IndirizzoResidenza.DescrizioneComune,
                                             persona.IndirizzoResidenza.Civico));
                    fuzzy.Add(persona.ID, "Via", persona.IndirizzoResidenza.Indirizzo);
                    fuzzy.Add(persona.ID, "Comune", persona.IndirizzoResidenza.DescrizioneComune);
                    fuzzy.Add(persona.ID, "Civico", persona.IndirizzoResidenza.Civico);

                    dict.Add(persona.ID, persona);
                }
            }

            query.Clear();

            var condominio = SferaServiceProxy.Instance.CurrentService().GetCondominioById(119, true, false, info);

            query.CreateSearchTerm("Via", condominio.Indirizzo.Indirizzo, 0.20, true);
            query.CreateSearchTerm("Comune", condominio.Indirizzo.DescrizioneComune);
            query.CreateSearchTerm("Civico", condominio.Indirizzo.Civico);

            var fuzzyResult = fuzzy.Search(query, scope, dict.Count);

            foreach (var searchResult in fuzzyResult)
            {
                var split = person[searchResult.Key].Split(new[] { ' ' });
                var via = split[0];
//                table.Rows.Add(new object[] { searchResult.Rank, searchResult.Key, split[0], split[1], split[2] });
            }
        }
        public List<AddressModel> Cleansing(string id)
        {
            var resT = new StoreProcedure();
            id = id.Replace("\r", string.Empty).Replace("\n", string.Empty).ToUpper();
            string[] res = new string[] { };
            string[] addressSearch = new string[] { };
            var postCode = string.Empty;
            var temporaryPostCode = string.Empty;
            var houseNumber = string.Empty;
            string street = string.Empty;
            string post = string.Empty;
            string numb = string.Empty;
            string flat = string.Empty;

            if (id.Contains(',') == true)
            {
                res = id.Split(',');
                addressSearch = id.Split(',');

                for (int i = 0; i < addressSearch.Count(); i++)
                {
                    res[i] = res[i].TrimStart().TrimEnd();
                    addressSearch[i] = addressSearch[i].TrimStart().TrimEnd();
                    if (res[i].ToUpper().Contains("FLAT"))
                    {
                        flat = res[i];
                    }
                }
            }
            else if (id.Contains(';') == true)
            {
                res = id.Split(';');
                addressSearch = id.Split(';');

                for (int i = 0; i < addressSearch.Count(); i++)
                {
                    res[i] = res[i].TrimStart().TrimEnd();
                    addressSearch[i] = addressSearch[i].TrimStart().TrimEnd();
                    if (res[i].ToUpper().Contains("FLAT"))
                    {
                        flat = res[i];
                    }
                }
            }
            else
            {
                res = id.Split(' ');
                addressSearch = id.Split(' ');
                //Слагам тука
            }
            for (int i = 0; i < addressSearch.Count(); i++)
            {
                try
                {
                    if (res[i].ToUpper().Contains("FLAT") && flat == "")
                    {
                        flat = res[i] + " " + res[i + 1];
                    }

                    if (res[i].Length > 2)
                    {
                        if (PostCodeType.postCodeType.Contains(res[i].Substring(0, 3)))
                        {
                            post = res[i];
                            if (res[i].Length < 5 && i <= addressSearch.Length - 1)
                            {
                                if (res[i + 1].Length == 3)
                                {
                                    string firstCharNext = res[i + 1].Substring(0, 1);
                                    int n;
                                    bool isNumeric = int.TryParse(firstCharNext, out n);
                                    string secondChar = res[i + 1].Substring(1, 1);
                                    int t;
                                    bool isChar = int.TryParse(secondChar, out t);
                                    if (isNumeric == true && isChar == false)
                                    {
                                        post = res[i] + " " + res[i + 1];
                                    }
                                }
                            }
                            else if (res[i].Length > 4)
                            {
                                var checkChar = res[i].Substring(res[i].Length - 3, 1);
                                if (checkChar != " ")
                                {
                                    res[i] = res[i].Insert(res[i].Length - 3, " ");
                                    Match postCo = Regex.Match(res[i], patern);
                                    if (postCo.Success)
                                        post = res[i];
                                }
                            }
                        }
                        else
                        {
                            int n;
                            bool isNumeric = int.TryParse(res[i], out n);
                            if (isNumeric)
                            {
                                numb = res[i];
                            }
                        }
                    }
                    else
                    {
                        int n;
                        bool isNumeric = int.TryParse(res[i], out n);
                        if (isNumeric)
                        {
                            numb = res[i];
                        }
                    }
                }
                catch
                {

                }
            }

            if (post.Length == 0)
            {
                for (int i = 0; i < addressSearch.Length - 1; i++)
                {
                    string tempPostCode = addressSearch[i] + addressSearch[i + 1];
                    if (tempPostCode.Length > 5)
                    {
                        tempPostCode = tempPostCode.Insert(tempPostCode.Length - 3, " ");
                        Match regPostCode = Regex.Match(tempPostCode, patern);
                        if (regPostCode.Success && PostCodeType.postCodeType.Contains(tempPostCode.Substring(0, 3)))
                        {
                            post = tempPostCode;
                            break;
                        }
                    }
                }

                for (int i = 0; i < addressSearch.Length; i++)
                {
                    string ifPostCodeOneWord = addressSearch[i].Replace(" ", "");
                    if (ifPostCodeOneWord.Length > 5)
                    {
                        ifPostCodeOneWord = ifPostCodeOneWord.Insert(ifPostCodeOneWord.Length - 3, " ");
                        Match regpostCode = Regex.Match(ifPostCodeOneWord, patern);
                        if (regpostCode.Success && PostCodeType.postCodeType.Contains(ifPostCodeOneWord.Insert(ifPostCodeOneWord.Length - 3, " ").Substring(0, 3)))
                        {
                            post = ifPostCodeOneWord;
                            break;
                        }
                    }
                }
            }

            if (post.Length >= 4 && numb.Length > 0)
            {

                var searchStreet = FoundStreet(addressSearch, post);

                if (searchStreet.Count() >= 1)
                {
                    foreach (var item in searchStreet)
                    {
                        if (item.postCode == "" || item.postCode == null)
                        {
                            street = item.street;
                            houseNumber = item.houseNumber;
                            postCode = post;

                            if (PostCodeType.postCodeType.Contains(postCode.Replace(" ", "").Insert(postCode.Length - 3, " ").Substring(0, 3)))
                                goto Address;
                        }
                        else
                        {
                            if (PostCodeType.postCodeType.Contains(item.postCode.Replace(" ", "").Insert(item.postCode.Length - 3, " ").Substring(0, 3)))
                                post = item.postCode;
                            numb = item.houseNumber;
                        }
                    }
                }

                if (flat.Length > 0)
                {

                    var resultPlusFlat = resT.FullDetailsPlusFlat(post, numb, flat);

                    if (resultPlusFlat.Count > 0)
                    {
                        return resultPlusFlat;
                    }
                }

                if (post.Replace(" ", "").Length >= 5)
                {
                    var result = resT.FullDetailsPlusStreet(post, numb);

                    return result;
                }
            }

            Match postCodeOnly = Regex.Match(post, patern);
            if (postCodeOnly.Success && PostCodeType.postCodeType.Contains(post.Substring(0, 3)))
            {
                var result = resT.FullDetails(post);

                return result;
            }
            // Махам от тука
            // }

            for (int i = 0; i < res.Count(); i++)
            {
                //Премахваме всякакви шантави знаци
                res[i] = Regex.Replace(res[i], "[^0-9A-Za-z]+", "");
                if (res[i].Count() == 6 || res[i].Count() == 7)
                {   //Слагам разделителя
                    res[i] = res[i].Insert(res[i].Count() - 3, " ");

                    //REGEX да проверя кое е пощенският код
                    Match match = Regex.Match(res[i], patern);
                    if (match.Success)
                    {   //втора проверка дали първият знак от втората част е цифра
                        var cha = res[i].Substring(res[i].Count() - 3, 1);
                        int n;
                        bool isNumeric = int.TryParse(cha, out n);
                        if (isNumeric)
                        {
                            postCode = res[i];
                        }
                    }
                }
            }

            //Проверяваме ако няма намерен пощенски код
            if (postCode.Count() == 0)
            {
                for (int i = 0; i < res.Count(); i++)
                {
                    try
                    {
                        if (PostCodeType.postCodeType.Contains(res[i].Substring(0, 3)))
                        {
                            res[i] = res[i].Replace(" ", "");

                            for (int j = 1; j < res[i].Count(); j++)
                            {
                                string cha = res[i].Substring(res[i].Count() - j, 1);
                                int n;
                                bool isNumeric = int.TryParse(cha, out n);
                                if (isNumeric)
                                {
                                    res[i] = res[i].Insert(res[i].Length - j, " ");
                                    break;
                                }

                            }
                            postCode = res[i];
                            break;
                        }
                    }
                    catch
                    {

                    }
                }
            }

            var foundStreet = FoundStreet(addressSearch, post);

            if (foundStreet.Count() == 0 && postCode != "" && postCode != null)
            {
                var streetNumber = StreetNumber(addressSearch, postCode);

                if (streetNumber.Length > 0)
                {
                    var result = resT.FullDetailsPlusStreet(postCode, streetNumber);

                    return result;

                }
            }

            foreach (var item in foundStreet)
            {
                street = item.street;
                houseNumber = item.houseNumber;
                if (item.postCode != null)
                {
                    postCode = item.postCode;
                    if (street == null)
                    {
                        //this has to be list, because of double house numbers like 42A, 42B etc..

                        var result = resT.FullDetailsPlusStreet(postCode, houseNumber);

                        return result;
                    }
                }
            }

            //Проверявам дали съм намерил пощенски код

            Address:

            //при намерен пощенски код
            if (postCode.Count() > 0 && postCode.Length > 5)
            {
                //Вземаме данните от базата, чрез процедурата GetFullDetails и ги прехвътлям в лист за да мога да ги обработя повеяе от веднъж при нужда
                var data = resT.FullDetailsFirstOrDefault(postCode);

                //ако улицата от базата съвпада с улицата от записа
                if (data.Street == street.ToUpper())
                {
                    var result = new List<AddressModel>();

                    result.Add(new AddressModel
                    {
                        AdministrativeCounty = data.AdministrativeCounty,
                        BuildingName = data.BuildingName,
                        BuildingNumber = houseNumber,
                        City = data.City.Replace("u0027", " "),
                        Flat = data.Flat,
                        Locality = data.Locality,
                        PostCode = data.PostCode,
                        Street = data.Street.Replace("u0027", " "),
                        TraditionalCounty = data.TraditionalCounty,
                        OrganisationName = data.OrganisationName.Replace("u0026", "&"),
                        IsValid = "Corrected"
                    });
                    return result;
                }

                //Ако улицата не съвпада с тази от записа в базата
                var streetFound = new List<string>();

                streetFound.Add(data.Street);

                //пускаме един Левенщаин за да видим дали не е само правописна грешка
                var foundWords = FuzzySearch.Search(street, streetFound, 0.8);

                //Ако е правописна грешка
                if (foundWords.Count > 0)
                {
                    var result = resT.FullDetailsPlusStreet(post, numb);

                    return result;

                }
                //Ако не е правописна грешка
                else
                {
                    var fuzzy = new FuzzySearch();

                    var resultPlusOne = fuzzy.MinusLetter(postCode + " ", houseNumber, street);

                    if (resultPlusOne.Count > 0)
                        return resultPlusOne;

                    //If there is white space in street
                    var resultNoWhiteSpace = fuzzy.MinusLetter(postCode + " ", houseNumber, street.Replace(" ", ""));

                    if (resultNoWhiteSpace.Count > 0)
                        return resultNoWhiteSpace;

                    //Вземаме всички улици за пощенските кодове без последната буква
                    var resultMinusOne = fuzzy.MinusLetter(postCode, houseNumber, street);

                    if (resultMinusOne.Count > 0)
                        return resultMinusOne;

                    //Ако няма съвпадение, вземаме всички улици без последните 2 букви
                    string postCodeMinusOne = postCode.Substring(0, postCode.Length - 1);

                    var resultMinusTwo = fuzzy.MinusLetter(postCodeMinusOne, houseNumber, street);

                    if (resultMinusTwo.Count > 0)
                        return resultMinusTwo;

                    //Само първата част на ПК
                    string postCodeMinusTwo = postCodeMinusOne.Substring(0, postCodeMinusOne.Length - 1);

                    var resultMinusThree = fuzzy.MinusLetter(postCodeMinusTwo, houseNumber, street);

                    if (resultMinusThree.Count > 0)
                        return resultMinusThree;

                    if (post.Length > 0 && numb.Length > 0)
                    {
                        var houseNumberPostCode = resT.FullDetailsPlusStreet(post, numb);

                        if (houseNumberPostCode.Count > 0)
                            return houseNumberPostCode;
                    }
                }
            }

            if (post.Length > 0 && street.Length > 0)
            {

                var result = resT.FullDetailsPartialStreet(post, street);

                return result;

            }

            var resultT = new List<AddressModel>();
            resultT.Add(new AddressModel()
            {
                Flat = id,
                PostCode = "No match",
                IsValid = "No match found"
            });
            return resultT;
        }
Exemple #29
0
        public SceneObjectsProvider(string providerId, string displayName = null)
            : base(providerId, displayName)
        {
            priority = 50;
            filterId = "h:";

            subCategories = new List <NameId>
            {
                new NameId("fuzzy", "fuzzy"),
                new NameId("limit", $"limit to {k_LimitMatches} matches")
            };

            isEnabledForContextualSearch = () =>
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneView") ||
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => componentsById.Clear();

            onEnable = () =>
            {
                //using (new DebugTimer("Building Scene Object Description"))
                {
                    var objects     = new GameObject[0];
                    var prefabStage = PrefabStageUtility.GetCurrentPrefabStage();
                    if (prefabStage != null)
                    {
                        objects = SceneModeUtility.GetObjects(new[] { prefabStage.prefabContentsRoot }, true);
                    }
                    else
                    {
                        var goRoots = new List <UnityEngine.Object>();
                        for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; ++i)
                        {
                            goRoots.AddRange(UnityEngine.SceneManagement.SceneManager.GetSceneAt(i).GetRootGameObjects());
                        }
                        objects = SceneModeUtility.GetObjects(goRoots.ToArray(), true);
                    }

                    //using (new DebugTimer($"Fetching {gods.Length} Scene Objects Components"))
                    {
                        gods = new GOD[objects.Length];
                        for (int i = 0; i < objects.Length; ++i)
                        {
                            gods[i].gameObject = objects[i];
                            var id = gods[i].gameObject.GetInstanceID();
                            if (!componentsById.TryGetValue(id, out gods[i].name))
                            {
                                if (gods.Length > k_LODDetail2)
                                {
                                    gods[i].name = CleanString(gods[i].gameObject.name);
                                }
                                else if (gods.Length > k_LODDetail1)
                                {
                                    gods[i].name = CleanString(GetTransformPath(gods[i].gameObject.transform));
                                }
                                else
                                {
                                    gods[i].name = BuildComponents(gods[i].gameObject);
                                }
                                componentsById[id] = gods[i].name;
                            }
                        }

                        indexer = new SceneSearchIndexer(SceneManager.GetActiveScene().name, gods);
                        indexer.Build();
                    }
                }
            };

            onDisable = () =>
            {
                indexer = null;
                gods    = new GOD[0];
            };

            fetchItems = (context, items, provider) =>
            {
                if (gods == null)
                {
                    return;
                }

                if (indexer != null && indexer.IsReady())
                {
                    var results = indexer.Search(context.searchQuery).Take(201);
                    items.AddRange(results.Select(r =>
                    {
                        if (r.index < 0 || r.index >= gods.Length)
                        {
                            return(provider.CreateItem("invalid"));
                        }

                        var gameObjectId   = gods[r.index].gameObject.GetInstanceID().ToString();
                        var gameObjectName = gods[r.index].gameObject.name;
                        var itemScore      = r.score - 1000;
                        if (gameObjectName.Equals(context.searchQuery, StringComparison.InvariantCultureIgnoreCase))
                        {
                            itemScore *= 2;
                        }
                        var item = provider.CreateItem(gameObjectId, itemScore, null, null, null, r.index);
                        item.descriptionFormat = SearchItemDescriptionFormat.Ellipsis |
                                                 SearchItemDescriptionFormat.RightToLeft |
                                                 SearchItemDescriptionFormat.Highlight;
                        return(item);
                    }));
                }

                SearchGODs(context, provider, items);
            };

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                var transformPath = GetTransformPath(go.transform);
                var components    = go.GetComponents <Component>();
                if (components.Length > 2 && components[1] && components[components.Length - 1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length-1].GetType().Name})";
                }
                else if (components.Length > 1 && components[1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name})";
                }
                else
                {
                    item.label = $"{transformPath} ({item.id})";
                }

                long       score   = 1;
                List <int> matches = new List <int>();
                var        sq      = CleanString(context.searchQuery);
                if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches))
                {
                    item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                #if QUICKSEARCH_DEBUG
                item.description = gods[(int)item.data].name + " * " + item.score;
                #else
                var go = ObjectFromItem(item);
                item.description = GetHierarchyPath(go);
                #endif
                return(item.description);
            };

            fetchThumbnail = (item, context) =>
            {
                if (item.thumbnail)
                {
                    return(item.thumbnail);
                }

                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    if (SearchSettings.fetchPreview)
                    {
                        var assetPath = GetHierarchyAssetPath(obj, true);
                        if (!String.IsNullOrEmpty(assetPath))
                        {
                            item.thumbnail = AssetPreview.GetAssetPreview(obj);
                            if (item.thumbnail)
                            {
                                return(item.thumbnail);
                            }
                            item.thumbnail = Utils.GetAssetThumbnailFromPath(assetPath, true);
                            if (item.thumbnail)
                            {
                                return(item.thumbnail);
                            }
                        }
                    }

                    item.thumbnail = PrefabUtility.GetIconForGameObject(obj);
                    if (item.thumbnail)
                    {
                        return(item.thumbnail);
                    }
                    item.thumbnail = EditorGUIUtility.ObjectContent(obj, obj.GetType()).image as Texture2D;
                }

                return(item.thumbnail);
            };

            startDrag = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new[] { obj };
                    DragAndDrop.StartDrag("Drag scene object");
                }
            };

            trackSelection = (item, context) => PingItem(item);
        }
Exemple #30
0
        public SceneProvider(string providerId, string filterId, string displayName)
            : base(providerId, displayName)
        {
            priority      = 50;
            this.filterId = filterId;

            subCategories = new List <NameId>
            {
                new NameId("fuzzy", "fuzzy"),
            };

            isEnabledForContextualSearch = () =>
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneView") ||
                                           QuickSearchTool.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => m_HierarchyChanged = true;

            onEnable = () =>
            {
                if (m_HierarchyChanged)
                {
                    componentsById.Clear();
                    indexer = null;
                    gods    = null;
                    m_GodBuilderEnumerator = null;
                    m_HierarchyChanged     = false;
                }
            };

            onDisable = () => {};

            fetchItems = (context, items, provider) => FetchItems(context, provider);

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                var transformPath = GetTransformPath(go.transform);
                var components    = go.GetComponents <Component>();
                if (components.Length > 2 && components[1] && components[components.Length - 1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length-1].GetType().Name})";
                }
                else if (components.Length > 1 && components[1])
                {
                    item.label = $"{transformPath} ({components[1].GetType().Name})";
                }
                else
                {
                    item.label = $"{transformPath} ({item.id})";
                }

                long       score   = 1;
                List <int> matches = new List <int>();
                var        sq      = CleanString(context.searchQuery);
                if (FuzzySearch.FuzzyMatch(sq, CleanString(item.label), ref score, matches))
                {
                    item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                #if QUICKSEARCH_DEBUG
                item.description = gods[(int)item.data].name + " * " + item.score;
                #else
                var go = ObjectFromItem(item);
                item.description = GetHierarchyPath(go);
                #endif
                return(item.description);
            };

            fetchThumbnail = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(null);
                }

                item.thumbnail = PrefabUtility.GetIconForGameObject(obj);
                if (item.thumbnail)
                {
                    return(item.thumbnail);
                }
                return(EditorGUIUtility.ObjectContent(obj, obj.GetType()).image as Texture2D);
            };

            fetchPreview = (item, context, size, options) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(item.thumbnail);
                }

                var assetPath = GetHierarchyAssetPath(obj, true);
                if (String.IsNullOrEmpty(assetPath))
                {
                    return(item.thumbnail);
                }
                return(AssetPreview.GetAssetPreview(obj) ?? Utils.GetAssetPreviewFromPath(assetPath));
            };

            startDrag = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj != null)
                {
                    DragAndDrop.PrepareStartDrag();
                    DragAndDrop.objectReferences = new[] { obj };
                    DragAndDrop.StartDrag("Drag scene object");
                }
            };

            fetchGameObjects       = FetchGameObjects;
            buildKeywordComponents = BuildKeywordComponents;

            trackSelection = (item, context) => PingItem(item);
        }
        public SceneProvider(string providerId, string filterId, string displayName)
            : base(providerId, displayName)
        {
            priority           = 50;
            this.filterId      = filterId;
            this.showDetails   = true;
            showDetailsOptions = ShowDetailsOptions.Inspector | ShowDetailsOptions.Actions;

            isEnabledForContextualSearch = () =>
                                           Utils.IsFocusedWindowTypeName("SceneView") ||
                                           Utils.IsFocusedWindowTypeName("SceneHierarchyWindow");

            EditorApplication.hierarchyChanged += () => m_HierarchyChanged = true;

            onEnable = () =>
            {
                if (m_HierarchyChanged)
                {
                    m_GameObjects      = fetchGameObjects();
                    m_SceneQueryEngine = new SceneQueryEngine(m_GameObjects);
                    m_HierarchyChanged = false;
                }
            };

            onDisable = () =>
            {
                // Only track changes that occurs when Quick Search is not active.
                m_HierarchyChanged = false;
            };

            toObject = (item, type) => ObjectFromItem(item);

            fetchItems = (context, items, provider) => SearchItems(context, provider);

            fetchLabel = (item, context) =>
            {
                if (item.label != null)
                {
                    return(item.label);
                }

                var go = ObjectFromItem(item);
                if (!go)
                {
                    return(item.id);
                }

                if (context.searchView == null || context.searchView.displayMode == DisplayMode.List)
                {
                    var transformPath = SearchUtils.GetTransformPath(go.transform);
                    var components    = go.GetComponents <Component>();
                    if (components.Length > 2 && components[1] && components[components.Length - 1])
                    {
                        item.label = $"{transformPath} ({components[1].GetType().Name}..{components[components.Length - 1].GetType().Name})";
                    }
                    else if (components.Length > 1 && components[1])
                    {
                        item.label = $"{transformPath} ({components[1].GetType().Name})";
                    }
                    else
                    {
                        item.label = $"{transformPath} ({item.id})";
                    }

                    long       score   = 1;
                    List <int> matches = new List <int>();
                    var        sq      = Utils.CleanString(context.searchQuery);
                    if (FuzzySearch.FuzzyMatch(sq, Utils.CleanString(item.label), ref score, matches))
                    {
                        item.label = RichTextFormatter.FormatSuggestionTitle(item.label, matches);
                    }
                }
                else
                {
                    item.label = go.name;
                }

                return(item.label);
            };

            fetchDescription = (item, context) =>
            {
                var go = ObjectFromItem(item);
                return(item.description = SearchUtils.GetHierarchyPath(go));
            };

            fetchThumbnail = (item, context) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(null);
                }

                return(item.thumbnail = Utils.GetThumbnailForGameObject(obj));
            };

            fetchPreview = (item, context, size, options) =>
            {
                var obj = ObjectFromItem(item);
                if (obj == null)
                {
                    return(item.thumbnail);
                }
                return(Utils.GetSceneObjectPreview(obj, size, options, item.thumbnail));
            };

            startDrag = (item, context) =>
            {
                Utils.StartDrag(context.selection.Select(i => ObjectFromItem(i)).ToArray(), item.GetLabel(context, true));
            };

            trackSelection = (item, context) => PingItem(item);

            fetchGameObjects       = SceneQueryEngine.FetchGameObjects;
            buildKeywordComponents = SceneQueryEngine.BuildKeywordComponents;
        }
Exemple #32
0
        private void SearchGODs(SearchContext context, SearchProvider provider, List <SearchItem> items)
        {
            int        addedCount = 0;
            List <int> matches    = new List <int>();
            var        sq         = CleanString(context.searchQuery);

            var limitSearch    = context.categories.Any(c => c.name.id == "limit" && c.isEnabled);
            var useFuzzySearch = gods.Length < k_LODDetail2 && context.categories.Any(c => c.name.id == "fuzzy" && c.isEnabled);

            long bestScore = 1;

            for (int i = 0, end = gods.Length; i != end; ++i)
            {
                var go = gods[i].gameObject;
                if (!go)
                {
                    continue;
                }

                long score = 1;
                if (useFuzzySearch)
                {
                    if (!FuzzySearch.FuzzyMatch(sq, gods[i].name, ref score, matches))
                    {
                        continue;
                    }

                    if (score > bestScore)
                    {
                        bestScore = score;
                    }
                    if (limitSearch && addedCount > (k_LimitMatches / 2))
                    {
                        useFuzzySearch = addedCount < ((k_LimitMatches * 7) / 8);
                    }
                }
                else
                {
                    if (!MatchSearchGroups(context, gods[i].name, true))
                    {
                        continue;
                    }
                    score = bestScore + 1;
                }

                var gameObjectId = go.GetInstanceID().ToString();
                var item         = provider.CreateItem(gameObjectId, ~(int)score, null, null, null, i);
                item.descriptionFormat = SearchItemDescriptionFormat.Ellipsis | SearchItemDescriptionFormat.RightToLeft;
                if (useFuzzySearch)
                {
                    item.descriptionFormat |= SearchItemDescriptionFormat.FuzzyHighlight;
                }
                else
                {
                    item.descriptionFormat |= SearchItemDescriptionFormat.Highlight;
                }
                items.Add(item);
                if (limitSearch && ++addedCount > k_LimitMatches)
                {
                    break;
                }
            }
        }