Пример #1
0
        private void InitializeReport(string path)
        {
            if (!File.Exists(path))
            {
                Debug.LogWarning(L10n.Tr($"Search report <a>{path}</a> is no longer valid."));
                Close();
                return;
            }

            m_ReportPath = path;

            m_Report = SearchReport.LoadFromFile(path);
            m_ReportName = Path.GetFileNameWithoutExtension(path);
            var searchServiceProvider = SearchService.GetDefaultProvider();
            m_Items = m_Report.CreateSearchItems(searchServiceProvider).ToList();
            titleContent = new GUIContent($"{m_ReportName} ({m_Items.Count})", m_ReportPath);

            m_FocusSearchField = true;

            // ITableView
            m_TableConfig = new SearchTable(m_ReportName, m_Report.columns);
            for (int i = 0; i < m_TableConfig.columns.Length; ++i)
                InitializeColumn(m_TableConfig.columns[i]);

            m_QueryEngine = new QueryEngine<int>(k_QueryEngineOptions);
            foreach (var column in m_Report.columns)
            {
                var filterName = column.content.text.Replace(" ", "");
                m_QueryEngine.AddFilter(filterName, i => AddFilter(i, column.selector));
                if (filterName != filterName.ToLowerInvariant())
                    m_QueryEngine.AddFilter(filterName.ToLowerInvariant(), i => AddFilter(i, column.selector));

                SearchValue.SetupEngine(m_QueryEngine);
            }
            m_QueryEngine.SetSearchDataCallback(i => m_Items[i].GetFields().Select(f => (f.value ?? "").ToString()), StringComparison.OrdinalIgnoreCase);

            UpdatePropertyTable();
        }
Пример #2
0
        public override void BeginSearch(ISearchContext context, string query)
        {
            if (!searchSessions.ContainsKey(context.guid))
            {
                return;
            }
            base.BeginSearch(context, query);

            var searchSession = searchSessions[context.guid];

            if (searchSession.context.searchText == query)
            {
                return;
            }

            searchSession.context.searchText = query;
            if (context.requiredTypeNames != null && context.requiredTypeNames.Any())
            {
                searchSession.context.filterType = Utils.GetTypeFromName(context.requiredTypeNames.First());
            }
            else
            {
                searchSession.context.filterType = typeof(GameObject);
            }

            if (!m_SearchItemsBySession.ContainsKey(context.guid))
            {
                m_SearchItemsBySession.Add(context.guid, new HashSet <int>());
            }
            var searchItemsSet = m_SearchItemsBySession[context.guid];

            searchItemsSet.Clear();

            foreach (var id in SearchService.GetItems(searchSession.context, SearchFlags.Synchronous).Select(item => Convert.ToInt32(item.id)))
            {
                searchItemsSet.Add(id);
            }
        }
Пример #3
0
        static SearchContext CreateContextFromAttribute(SearchContextAttribute attribute)
        {
            var providers = attribute.providerIds.Select(id => SearchService.GetProvider(id))
                            .Concat(attribute.instantiableProviders.Select(type => SearchService.GetProvider(type))).Where(p => p != null);

            if (!providers.Any())
            {
                providers = SearchService.GetObjectProviders();
            }

            var searchText  = attribute.query;
            var searchQuery = GetSearchQueryFromFromAttribute(attribute);

            if (searchQuery != null)
            {
                searchText = searchQuery.text;
                providers  = QuickSearch.GetMergedProviders(providers, searchQuery.providerIds);
            }

            var context = SearchService.CreateContext(providers, searchText);

            return(context);
        }
Пример #4
0
        SearchTable LoadDefaultTableConfig(bool reset, string id = null, SearchTable defaultConfig = null)
        {
            if (!reset)
            {
                var sessionSearchTableData = SessionState.GetString(GetDefaultGroupId(id), null);
                if (!string.IsNullOrEmpty(sessionSearchTableData))
                {
                    return(SearchTable.Import(sessionSearchTableData));
                }
            }

            if (searchView is QuickSearch qs)
            {
                var providers = qs.context.GetProviders();
                var provider  = providers.Count == 1 ? providers.FirstOrDefault() : SearchService.GetProvider(qs.currentGroup);
                if (provider?.tableConfig != null)
                {
                    return(provider.tableConfig(context));
                }
            }

            return(defaultConfig ?? SearchTable.CreateDefault());
        }
Пример #5
0
        public static bool TryParse(StringView text, out QueryMarker marker)
        {
            marker = none;
            if (!IsQueryMarker(text))
            {
                return(false);
            }

            var innerText = text.Substring(k_StartToken.Length, text.Length - k_StartToken.Length - k_EndToken.Length);

            var indexOfColon = innerText.IndexOf(':');

            if (indexOfColon < 0)
            {
                return(false);
            }

            var controlType     = innerText.Substring(0, indexOfColon).Trim().ToString();
            var args            = new List <StringView>();
            var level           = 0;
            var currentArgStart = indexOfColon + 1;

            for (var i = currentArgStart; i < innerText.Length; ++i)
            {
                if (ParserUtils.IsOpener(innerText[i]))
                {
                    ++level;
                }
                if (ParserUtils.IsCloser(innerText[i]))
                {
                    --level;
                }
                if (innerText[i] != ',' || level != 0)
                {
                    continue;
                }
                if (i + 1 == innerText.Length)
                {
                    return(false);
                }

                args.Add(innerText.Substring(currentArgStart, i - currentArgStart).Trim());
                currentArgStart = i + 1;
            }

            if (currentArgStart == innerText.Length)
            {
                return(false); // No arguments
            }
            // Extract the final argument, since there is no comma after the last argument
            args.Add(innerText.Substring(currentArgStart, innerText.Length - currentArgStart).Trim());

            var queryMarkerArguments = new List <QueryMarkerArgument>();

            using (var context = SearchService.CreateContext(""))
            {
                foreach (var arg in args)
                {
                    var parserArgs = new SearchExpressionParserArgs(arg, context, SearchExpressionParserFlags.ImplicitLiterals);
                    SearchExpression expression = null;
                    try
                    {
                        expression = SearchExpression.Parse(parserArgs);
                    }
                    catch (SearchExpressionParseException)
                    { }

                    if (expression == null || !expression.types.HasAny(SearchExpressionType.Literal))
                    {
                        queryMarkerArguments.Add(new QueryMarkerArgument {
                            rawText = arg, expression = expression, value = expression == null ? arg.ToString() : null
                        });
                        continue;
                    }
                    var results             = expression.Execute(context);
                    var resolvedValue       = results.FirstOrDefault(item => item != null);
                    var resolvedValueObject = resolvedValue?.value;
                    queryMarkerArguments.Add(new QueryMarkerArgument {
                        rawText = arg, expression = expression, value = resolvedValueObject
                    });
                }
            }

            marker = new QueryMarker {
                type = controlType, text = text, args = queryMarkerArguments.ToArray()
            };
            return(true);
        }
Пример #6
0
 internal override SearchContext CreateQueryContext(ISearchQuery query)
 {
     return(SearchService.CreateContext(context?.GetProviders(), query.searchText, context?.options ?? SearchFlags.Default));
 }
Пример #7
0
        private void SetupContext()
        {
            m_Results?.Dispose();
            m_ResultView?.Dispose();
            if (m_SearchContext != null)
            {
                m_SearchContext.Dispose();
                m_SearchContext.asyncItemReceived -= OnAsyncItemsReceived;
            }

            var providerIds = m_EnabledProviderIds.Count != 0 ? m_EnabledProviderIds : SearchService.GetActiveProviders().Select(p => p.id);

            m_SearchContext = SearchService.CreateContext(providerIds, m_TextProperty.stringValue, SearchSettings.GetContextOptions());
            m_SearchContext.asyncItemReceived += OnAsyncItemsReceived;
            m_Results    = new SortedSearchList(m_SearchContext);
            m_ResultView = new SearchResultView(m_Results);

            RefreshResults();
        }
Пример #8
0
        public void ObjectIconDropDown(Rect position, SerializedProperty iconProperty)
        {
            const float kDropDownArrowMargin = 2;
            const float kDropDownArrowWidth  = 12;
            const float kDropDownArrowHeight = 12;

            if (s_IconTextureInactive == null)
            {
                s_IconTextureInactive = (Material)EditorGUIUtility.LoadRequired("Inspectors/InactiveGUI.mat");
            }

            if (s_IconButtonStyle == null)
            {
                s_IconButtonStyle = new GUIStyle("IconButton")
                {
                    fixedWidth = 0, fixedHeight = 0
                }
            }
            ;

            void SelectIcon(UnityEngine.Object obj, bool isCanceled)
            {
                if (!isCanceled)
                {
                    iconProperty.objectReferenceValue = obj;
                    iconProperty.serializedObject.ApplyModifiedProperties();
                    SearchService.RefreshWindows();
                }
            }

            if (EditorGUI.DropdownButton(position, GUIContent.none, FocusType.Passive, s_IconButtonStyle))
            {
                SearchUtils.ShowIconPicker(SelectIcon);
                GUIUtility.ExitGUI();
            }

            if (Event.current.type == EventType.Repaint)
            {
                var contentPosition = position;

                contentPosition.xMin += kDropDownArrowMargin;
                contentPosition.xMax -= kDropDownArrowMargin + kDropDownArrowWidth / 2;
                contentPosition.yMin += kDropDownArrowMargin;
                contentPosition.yMax -= kDropDownArrowMargin + kDropDownArrowWidth / 2;

                Rect arrowRect = new Rect(
                    contentPosition.x + contentPosition.width - kDropDownArrowWidth / 2,
                    contentPosition.y + contentPosition.height - kDropDownArrowHeight / 2,
                    kDropDownArrowWidth, kDropDownArrowHeight);
                Texture2D icon = null;

                if (!iconProperty.hasMultipleDifferentValues)
                {
                    icon = iconProperty.objectReferenceValue as Texture2D ?? AssetPreview.GetMiniThumbnail(targets[0]);
                }
                if (icon == null)
                {
                    icon = Icons.favorite;
                }

                Vector2 iconSize = contentPosition.size;

                if (icon)
                {
                    iconSize.x = Mathf.Min(icon.width, iconSize.x);
                    iconSize.y = Mathf.Min(icon.height, iconSize.y);
                }
                Rect iconRect = new Rect(
                    contentPosition.x + contentPosition.width / 2 - iconSize.x / 2,
                    contentPosition.y + contentPosition.height / 2 - iconSize.y / 2,
                    iconSize.x, iconSize.y);

                GUI.DrawTexture(iconRect, icon, ScaleMode.ScaleToFit);
                if (s_IconDropDown == null)
                {
                    s_IconDropDown = EditorGUIUtility.IconContent("Icon Dropdown");
                }
                GUIStyle.none.Draw(arrowRect, s_IconDropDown, false, false, false, false);
            }
        }

        void AddProvider(ReorderableList list)
        {
            var menu = new GenericMenu();
            var disabledProviders = GetDisabledProviders().ToList();

            for (var i = 0; i < disabledProviders.Count; ++i)
            {
                var provider = disabledProviders[i];
                menu.AddItem(new GUIContent(provider.name), false, AddProvider, provider);
                if (!provider.isExplicitProvider && i + 1 < disabledProviders.Count && disabledProviders[i + 1].isExplicitProvider)
                {
                    menu.AddSeparator(string.Empty);
                }
            }
            menu.ShowAsContext();
        }

        void AddProvider(object providerObj)
        {
            if (providerObj is SearchProvider provider && !m_EnabledProviderIds.Contains(provider.id))
            {
                m_EnabledProviderIds.Add(provider.id);
                UpdateEnabledProviders();
            }
        }

        void RemoveProvider(ReorderableList list)
        {
            var index = list.index;

            if (index != -1 && index < m_EnabledProviderIds.Count)
            {
                var toRemove = SearchService.GetProvider(m_EnabledProviderIds[index]);
                if (toRemove == null)
                {
                    return;
                }
                m_EnabledProviderIds.Remove(toRemove.id);
                UpdateEnabledProviders();

                if (index >= list.count)
                {
                    list.index = list.count - 1;
                }
            }
        }

        void UpdateEnabledProviders()
        {
            m_ProvidersProperty.arraySize = m_EnabledProviderIds.Count;
            for (var i = 0; i < m_EnabledProviderIds.Count; ++i)
            {
                m_ProvidersProperty.GetArrayElementAtIndex(i).stringValue = m_EnabledProviderIds[i];
            }
            serializedObject.ApplyModifiedProperties();
            SetupContext();
        }

        void DrawProviderElement(Rect rect, int index, bool selected, bool focused)
        {
            if (index >= 0 && index < m_EnabledProviderIds.Count)
            {
                GUI.Label(rect, SearchService.GetProvider(m_EnabledProviderIds[index])?.name ?? "<unknown>");
            }
        }

        void CheckContext()
        {
            if (m_SearchContext.searchText != m_TextProperty.stringValue)
            {
                SetupContext();
            }
        }
    }
Пример #9
0
 private void RefreshResults()
 {
     SetItems(SearchService.GetItems(m_SearchContext));
 }
Пример #10
0
        internal static SearchExpression Parse(string text, SearchExpressionParserFlags options = SearchExpressionParserFlags.Default)
        {
            var searchContext = SearchService.CreateContext(text);

            return(Parse(searchContext, options));
        }
Пример #11
0
        public QueryHelperWidget(bool blockMode, ISearchView view = null)
        {
            m_BlockMode = blockMode;
            drawBorder  = true;

            m_Areas = new QueryBuilder("")
            {
                drawBackground = false,
            };
            m_Areas.AddBlock(new QueryAreaBlock(m_Areas, k_All, ""));

            var builtinSearches = SearchTemplateAttribute.GetAllQueries();
            var allProviders    = view != null && view.context != null?view.context.GetProviders() : SearchService.GetActiveProviders();

            var generalProviders  = allProviders.Where(p => !p.isExplicitProvider);
            var explicitProviders = allProviders.Where(p => p.isExplicitProvider);
            var providers         = generalProviders.Concat(explicitProviders);

            if (blockMode)
            {
                m_ActiveSearchProviders = providers.Where(p => p.id != "expression" && (p.fetchPropositions != null || builtinSearches.Any(sq => sq.searchText.StartsWith(p.filterId) || sq.GetProviderIds().Any(pid => p.id == pid)))).ToArray();
            }
            else
            {
                m_ActiveSearchProviders = providers.ToArray();
            }

            foreach (var p in m_ActiveSearchProviders)
            {
                m_Areas.AddBlock(new QueryAreaBlock(m_Areas, p));
            }
            m_Areas.@readonly = true;
            foreach (var b in m_Areas.blocks)
            {
                b.tooltip = $"Double click to search in: {b.value}";
            }

            if (string.IsNullOrEmpty(m_CurrentAreaFilterId))
            {
                m_CurrentAreaFilterId = SearchSettings.helperWidgetCurrentArea;
            }
            m_Searches = new QueryHelperSearchGroup(m_BlockMode, L10n.Tr("Searches"));

            ChangeCurrentAreaFilter(m_CurrentAreaFilterId);

            PopulateSearches(builtinSearches);
            RefreshSearches();
            BindSearchView(view);
        }
Пример #12
0
        public static string ReplaceText(string searchText, string replacement, int cursorPos, out int insertTokenPos)
        {
            var replaceFrom = cursorPos - 1;

            while (replaceFrom >= 0 && !SearchPropositionOptions.IsDelimiter(searchText[replaceFrom]))
            {
                replaceFrom--;
            }
            if (replaceFrom == -1)
            {
                replaceFrom = 0;
            }
            else
            {
                replaceFrom++;
            }

            var activeProviders = SearchService.GetActiveProviders();

            foreach (var provider in activeProviders)
            {
                if (replaceFrom + provider.filterId.Length > searchText.Length || provider.filterId.Length == 1)
                {
                    continue;
                }

                var stringViewTest = new StringView(searchText, replaceFrom, replaceFrom + provider.filterId.Length);
                if (stringViewTest == provider.filterId)
                {
                    replaceFrom += provider.filterId.Length;
                    break;
                }
            }

            var replaceTo = IndexOfDelimiter(searchText, cursorPos);

            if (replaceTo == -1)
            {
                replaceTo = searchText.Length;
            }

            if (searchText.Substring(replaceFrom, replaceTo - replaceFrom).StartsWith(replacement, StringComparison.OrdinalIgnoreCase))
            {
                insertTokenPos = cursorPos;
                return(searchText);
            }

            var sb = new StringBuilder(searchText);

            sb.Remove(replaceFrom, replaceTo - replaceFrom);
            sb.Insert(replaceFrom, replacement);

            var insertion = sb.ToString();

            insertTokenPos = insertion.LastIndexOf('\t');
            if (insertTokenPos != -1)
            {
                insertion = insertion.Remove(insertTokenPos, 1);
            }
            return(insertion);
        }
Пример #13
0
 public static ISearchView ShowWindow(string searchQuery)
 {
     return(ShowWindow(searchQuery, SearchService.GetActiveProviders()));
 }
Пример #14
0
        public static ISearchView ShowWindow(string searchQuery, IEnumerable <SearchProvider> providers)
        {
            var context = SearchService.CreateContext(providers, searchQuery);

            return(SearchService.ShowWindow(context, topic: "Expression", saveFilters: false));
        }