Exemple #1
0
		public SearchLocation(SearchTarget target, string baseDirectory, string filter, bool searchSubdirs, ISegment selection)
		{
			this.Target = target;
			this.BaseDirectory = baseDirectory;
			this.Filter = filter ?? "*.*";
			this.SearchSubdirs = searchSubdirs;
			this.Selection = selection;
		}
Exemple #2
0
        /// <summary>
        /// Does the search using MS Full text search
        /// </summary>
        /// <param name="searchString">Search string.</param>
        /// <param name="forumIDs">Forum Ids of forums to search into.</param>
        /// <param name="orderFirstElement">Order first element setting.</param>
        /// <param name="orderSecondElement">Order second element setting.</param>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userID">The userid of the calling user.</param>
        /// <param name="targetToSearch">The target to search.</param>
        /// <returns>
        /// TypedList filled with threads matching the query.
        /// </returns>
        public static SearchResultTypedList DoSearch(string searchString, List<int> forumIDs, SearchResultsOrderSetting orderFirstElement,
            SearchResultsOrderSetting orderSecondElement, List<int> forumsWithThreadsFromOthers, int userID, SearchTarget targetToSearch)
        {
            // the search utilizes full text search. It performs a CONTAINS upon the MessageText field of the Message entity.
            string searchTerms = PrepareSearchTerms(searchString);
            bool searchMessageText = (targetToSearch == SearchTarget.MessageText) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            bool searchSubject = (targetToSearch == SearchTarget.ThreadSubject) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            if(!(searchSubject || searchMessageText))
            {
                // no target specified, select message
                searchMessageText = true;
            }

            PredicateExpression searchTermFilter = new PredicateExpression();
            if(searchMessageText)
            {
                // Message contents filter
                searchTermFilter.Add(new FieldCompareSetPredicate(ThreadFields.ThreadID, MessageFields.ThreadID,
                                    SetOperator.In, new FieldFullTextSearchPredicate(MessageFields.MessageText, FullTextSearchOperator.Contains, searchTerms)));
            }
            if(searchSubject)
            {
                // Thread subject filter
                if(searchMessageText)
                {
                    searchTermFilter.AddWithOr(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
                else
                {
                    searchTermFilter.Add(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
            }
            IPredicateExpression mainFilter = searchTermFilter
                                                    .And(ForumFields.ForumID == forumIDs)
                                                    .And(ThreadGuiHelper.CreateThreadFilter(forumsWithThreadsFromOthers, userID));

            ISortExpression sorter = new SortExpression();
            // add first element
            sorter.Add(CreateSearchSortClause(orderFirstElement));
            if(orderSecondElement != orderFirstElement)
            {
                sorter.Add(CreateSearchSortClause(orderSecondElement));
            }

            SearchResultTypedList results = new SearchResultTypedList(false);

            try
            {
                // get the data from the db.
                results.Fill(500, sorter, false, mainFilter);
            }
            catch
            {
                // probably an error with the search words / user error. Swallow for now, which will result in an empty resultset.
            }

            return results;
        }
        public void Create_url_with_query_params()
        {
            var router = CreateRouter().AddRoute("search", null, typeof(SearchTarget));

            var target = new SearchTarget("two words");
            var url = router.CreateUrl(target);

            Assert.AreEqual("test://search?searchtext=two%20words", url);
        }
		public AStarPathFinder(SearchTarget searchTarget, GridPoint goalPos, GridPoint startPos, int limitCost = int.MaxValue) {
			this.searchTarget = searchTarget;
			this.startPos = startPos;
			this.goalPos = goalPos;
			this.limitCost = limitCost;
			this.path = null;
			sortedOpens.Clear();

			Calculate();
		}
		public ReachableMap(SearchTarget target) {
			this.reachableCount = 0;
			this.target = target;
			reachableMap = new int[target.SizeX,target.SizeY];

			reachableCount = 1;
			for (int x = 0; x < target.SizeX; x++) {
				for (int y = 0; y < target.SizeY; y++) {
					if (InitializeReachable(new GridPoint(x, y), reachableCount)) {
						Calculate(reachableCount);
						reachableCount++;
					}
				}
			}

		}
Exemple #6
0
        internal static IEnumerable <string> InternalEnumeratePaths(
            string path,
            string searchPattern,
            SearchTarget searchTarget,
            EnumerationOptions options)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }
            if (searchPattern == null)
            {
                throw new ArgumentNullException(nameof(searchPattern));
            }

            FileSystemEnumerableFactory.NormalizeInputs(ref path, ref searchPattern, options.MatchType);

            return(searchTarget switch
            {
                SearchTarget.Files => FileSystemEnumerableFactory.UserFiles(path, searchPattern, options),
                SearchTarget.Directories => FileSystemEnumerableFactory.UserDirectories(path, searchPattern, options),
                SearchTarget.Both => FileSystemEnumerableFactory.UserEntries(path, searchPattern, options),
                _ => throw new ArgumentOutOfRangeException(nameof(searchTarget)),
            });
Exemple #7
0
        public SearchHistory Searched(string keyword, SearchTarget target)
        {
            var searchHistory = _collection.FindOne(x => x.Keyword == keyword && x.Target == target);

            if (searchHistory == null)
            {
                searchHistory = new SearchHistory
                {
                    Keyword     = keyword,
                    Target      = target,
                    LastUpdated = DateTime.Now,
                    SearchCount = 1
                };
            }
            else
            {
                searchHistory.LastUpdated = DateTime.Now;
                searchHistory.SearchCount++;
            }

            _collection.Upsert(searchHistory);

            return(searchHistory);
        }
		void SetOptions()
		{
			Get<ComboBox>("find").Text = SearchOptions.FindPattern;
			Get<ComboBox>("find").Items.Clear();
			
			Get<ComboBox>("find").Text = SearchOptions.FindPattern;
			Get<ComboBox>("find").Items.Clear();
			foreach (string findPattern in SearchOptions.FindPatterns) {
				Get<ComboBox>("find").Items.Add(findPattern);
			}
			
			if (searchAndReplaceMode == SearchAndReplaceMode.Replace) {
				Get<ComboBox>("replace").Text = SearchOptions.ReplacePattern;
				Get<ComboBox>("replace").Items.Clear();
				foreach (string replacePattern in SearchOptions.ReplacePatterns) {
					Get<ComboBox>("replace").Items.Add(replacePattern);
				}
			}
			
			Get<ComboBox>("lookIn").Text = SearchOptions.LookIn;
			foreach (string lookInText in typeof(SearchTarget).GetFields().SelectMany(f => f.GetCustomAttributes(false).OfType<DescriptionAttribute>()).Select(da => da.Description)) {
				Get<ComboBox>("lookIn").Items.Add(StringParser.Parse(lookInText));
			}
			Get<ComboBox>("lookIn").Items.Add(SearchOptions.LookIn);
			Get<ComboBox>("lookIn").SelectedIndexChanged += new EventHandler(LookInSelectedIndexChanged);
			
			if (IsMultipleLineSelection(SearchManager.GetActiveTextEditor())) {
				SearchTarget = SearchTarget.CurrentSelection;
			} else {
				if (SearchOptions.SearchTarget == SearchTarget.CurrentSelection) {
					SearchOptions.SearchTarget = SearchTarget.CurrentDocument;
				}
				SearchTarget = SearchOptions.SearchTarget;
			}
			
			Get<ComboBox>("fileTypes").Text         = SearchOptions.LookInFiletypes;
			Get<CheckBox>("matchCase").Checked      = SearchOptions.MatchCase;
			Get<CheckBox>("matchWholeWord").Checked = SearchOptions.MatchWholeWord;
			Get<CheckBox>("includeSubFolder").Checked = SearchOptions.IncludeSubdirectories;
			
			Get<ComboBox>("use").Items.Clear();
			Get<ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.Standard}"));
			Get<ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.RegexSearch}"));
			Get<ComboBox>("use").Items.Add(StringParser.Parse("${res:Dialog.NewProject.SearchReplace.SearchStrategy.WildcardSearch}"));
			switch (SearchOptions.SearchMode) {
				case SearchMode.RegEx:
					Get<ComboBox>("use").SelectedIndex = 1;
					break;
				case SearchMode.Wildcard:
					Get<ComboBox>("use").SelectedIndex = 2;
					break;
				default:
					Get<ComboBox>("use").SelectedIndex = 0;
					break;
			}
		}
Exemple #9
0
 public SearchArg(int pageIndex, bool isLibrary)
 {
     PageIndex = pageIndex;
     Target    = isLibrary ? SearchTarget.Library : SearchTarget.Recent;
 }
Exemple #10
0
 public SearchArg(string query, int pageIndex)
 {
     Query     = query;
     PageIndex = pageIndex;
     Target    = SearchTarget.Query;
 }
Exemple #11
0
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            var search = SearchPattern.Parse(ref path, ref searchPattern);

            return(zip.Cast <ZipEntry>().Map(x => {
                if (searchTarget == SearchTarget.File && !x.IsFile)
                {
                    return null;
                }
                if (searchTarget == SearchTarget.Directory && !x.IsDirectory)
                {
                    return null;
                }
                UPath child = UPath.DirectorySeparator + x.Name;
                if (!child.FullName.StartsWith(path.FullName))
                {
                    return null;
                }
                if (searchOption == SearchOption.TopDirectoryOnly)
                {
                    child = child.RemovePrefix(path).GetFirstPart();
                }
                if (!search.Match(child))
                {
                    return null;
                }
                return child;
            }).Filter(x => x != null).Distinct());
        }
Exemple #12
0
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        public IEnumerable <UPath> EnumeratePaths(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            AssertNotDisposed();
            if (searchPattern is null)
            {
                throw new ArgumentNullException(nameof(searchPattern));
            }
            return(EnumeratePathsImpl(ValidatePath(path), searchPattern, searchOption, searchTarget));
        }
Exemple #13
0
 public abstract IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget);
Exemple #14
0
 public override IEnumerable <string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     return(Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern,
                                                                    (searchTarget & SearchTarget.Files) == SearchTarget.Files,
                                                                    (searchTarget & SearchTarget.Directories) == SearchTarget.Directories,
                                                                    searchOption));
 }
Exemple #15
0
 public override IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     // Fill in implementation
     return(new FileSystemInfo[0]);
 }
Exemple #16
0
 public abstract IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget);
Exemple #17
0
 public abstract IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget);
Exemple #18
0
        public override IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            switch (searchTarget)
            {
            case SearchTarget.Files:
                return(new FileSystemEnumerable <FileInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
                                                           new FileInfo(path, null)));

            case SearchTarget.Directories:
                return(new FileSystemEnumerable <DirectoryInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) =>
                                                                new DirectoryInfo(path, null)));

            default:
                return(new FileSystemEnumerable <FileSystemInfo>(fullPath, searchPattern, searchOption, searchTarget, (path, isDir) => isDir ?
                                                                 (FileSystemInfo) new DirectoryInfo(path, null) :
                                                                 (FileSystemInfo) new FileInfo(path, null)));
            }
        }
Exemple #19
0
        public override IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            IReadOnlyList <IStorageItem> storageFiles = SynchronousResultOf(EnumerateFileQuery(fullPath, searchPattern, searchOption, searchTarget));

            return(IterateFileSystemInfosFromStorageItems(storageFiles));
        }
Exemple #20
0
        /// <summary>
        /// Does the search using MS Full text search
        /// </summary>
        /// <param name="searchString">Search string.</param>
        /// <param name="forumIDs">Forum Ids of forums to search into.</param>
        /// <param name="orderFirstElement">Order first element setting.</param>
        /// <param name="orderSecondElement">Order second element setting.</param>
        /// <param name="forumsWithThreadsFromOthers">The forums with threads from others.</param>
        /// <param name="userID">The userid of the calling user.</param>
        /// <param name="targetToSearch">The target to search.</param>
        /// <returns>
        /// TypedList filled with threads matching the query.
        /// </returns>
        public static SearchResultTypedList DoSearch(string searchString, List <int> forumIDs, SearchResultsOrderSetting orderFirstElement,
                                                     SearchResultsOrderSetting orderSecondElement, List <int> forumsWithThreadsFromOthers, int userID, SearchTarget targetToSearch)
        {
            // the search utilizes full text search. It performs a CONTAINS upon the MessageText field of the Message entity.
            string searchTerms       = PrepareSearchTerms(searchString);
            bool   searchMessageText = (targetToSearch == SearchTarget.MessageText) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);
            bool   searchSubject     = (targetToSearch == SearchTarget.ThreadSubject) || (targetToSearch == SearchTarget.MessageTextAndThreadSubject);

            if (!(searchSubject || searchMessageText))
            {
                // no target specified, select message
                searchMessageText = true;
            }

            PredicateExpression searchTermFilter = new PredicateExpression();

            if (searchMessageText)
            {
                // Message contents filter
                searchTermFilter.Add(new FieldCompareSetPredicate(ThreadFields.ThreadID, MessageFields.ThreadID,
                                                                  SetOperator.In, new FieldFullTextSearchPredicate(MessageFields.MessageText, FullTextSearchOperator.Contains, searchTerms)));
            }
            if (searchSubject)
            {
                // Thread subject filter
                if (searchMessageText)
                {
                    searchTermFilter.AddWithOr(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
                else
                {
                    searchTermFilter.Add(new FieldFullTextSearchPredicate(ThreadFields.Subject, FullTextSearchOperator.Contains, searchTerms));
                }
            }
            IPredicateExpression mainFilter = searchTermFilter
                                              .And(ForumFields.ForumID == forumIDs)
                                              .And(ThreadGuiHelper.CreateThreadFilter(forumsWithThreadsFromOthers, userID));

            ISortExpression sorter = new SortExpression();

            // add first element
            sorter.Add(CreateSearchSortClause(orderFirstElement));
            if (orderSecondElement != orderFirstElement)
            {
                sorter.Add(CreateSearchSortClause(orderSecondElement));
            }

            SearchResultTypedList results = new SearchResultTypedList(false);

            try
            {
                // get the data from the db.
                results.Fill(500, sorter, false, mainFilter);
            }
            catch
            {
                // probably an error with the search words / user error. Swallow for now, which will result in an empty resultset.
            }

            return(results);
        }
Exemple #21
0
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Special case for Windows as we need to provide list for:
            // - the root folder / (which should just return the /drive folder)
            // - the drive folders /drive/c, drive/e...etc.
            var search = SearchPattern.Parse(ref path, ref searchPattern);

            if (IsOnWindows)
            {
                if (IsWithinSpecialDirectory(path))
                {
                    if (!SpecialDirectoryExists(path))
                    {
                        throw NewDirectoryNotFoundException(path);
                    }

                    var searchForDirectory = searchTarget == SearchTarget.Both || searchTarget == SearchTarget.Directory;

                    // Only sub folder "/drive/" on root folder /
                    if (path == UPath.Root)
                    {
                        if (searchForDirectory)
                        {
                            yield return(PathDrivePrefixOnWindows);

                            if (searchOption == SearchOption.AllDirectories)
                            {
                                foreach (var subPath in EnumeratePathsImpl(PathDrivePrefixOnWindows, searchPattern, searchOption, searchTarget))
                                {
                                    yield return(subPath);
                                }
                            }
                        }

                        yield break;
                    }

                    // When listing for /drive, return the list of drives available
                    if (path == PathDrivePrefixOnWindows)
                    {
                        var pathDrives = new List <UPath>();
                        foreach (var drive in DriveInfo.GetDrives())
                        {
                            if (drive.Name.Length < 2 || drive.Name[1] != ':')
                            {
                                continue;
                            }

                            var pathDrive = PathDrivePrefixOnWindows / char.ToLowerInvariant(drive.Name[0]).ToString();

                            if (search.Match(pathDrive))
                            {
                                pathDrives.Add(pathDrive);

                                if (searchForDirectory)
                                {
                                    yield return(pathDrive);
                                }
                            }
                        }

                        if (searchOption == SearchOption.AllDirectories)
                        {
                            foreach (var pathDrive in pathDrives)
                            {
                                foreach (var subPath in EnumeratePathsImpl(pathDrive, searchPattern, searchOption, searchTarget))
                                {
                                    yield return(subPath);
                                }
                            }
                        }

                        yield break;
                    }
                }
            }

            IEnumerable <string> results;

            switch (searchTarget)
            {
            case SearchTarget.File:
                results = Directory.EnumerateFiles(ConvertPathToInternal(path), searchPattern, searchOption);
                break;

            case SearchTarget.Directory:
                results = Directory.EnumerateDirectories(ConvertPathToInternal(path), searchPattern, searchOption);
                break;

            case SearchTarget.Both:
                results = Directory.EnumerateFileSystemEntries(ConvertPathToInternal(path), searchPattern, searchOption);
                break;

            default:
                yield break;
            }

            foreach (var subPath in results)
            {
                // Windows will truncate the search pattern's extension to three characters if the filesystem
                // has 8.3 paths enabled. This means searching for *.docx will list *.doc as well which is
                // not what we want. Check against the search pattern again to filter out those false results.
                if (!IsOnWindows || search.Match(Path.GetFileName(subPath)))
                {
                    yield return(ConvertPathFromInternal(subPath));
                }
            }
        }
Exemple #22
0
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            SearchPattern.Parse(ref path, ref searchPattern);

            var entries     = new SortedSet <UPath>();
            var fileSystems = new List <IFileSystem>();

            if (Fallback != null)
            {
                fileSystems.Add(Fallback);
            }

            // Query all filesystems just once
            fileSystems.AddRange(_fileSystems);

            for (var i = fileSystems.Count - 1; i >= 0; i--)
            {
                var fileSystem = fileSystems[i];

                if (!fileSystem.DirectoryExists(path))
                {
                    continue;
                }

                foreach (var item in fileSystem.EnumeratePaths(path, searchPattern, searchOption, searchTarget))
                {
                    if (entries.Contains(item))
                    {
                        continue;
                    }
                    entries.Add(item);
                }
            }

            // Return entries
            foreach (var entry in entries)
            {
                yield return(entry);
            }
        }
Exemple #23
0
 public abstract IEnumerable <string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget);
Exemple #24
0
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            var search = SearchPattern.Parse(ref path, ref searchPattern);

            var directoryToVisit = new List <UPath>();

            directoryToVisit.Add(path);

            var entries           = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);
            var sortedDirectories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);
            var fileSystems       = new List <IFileSystem>();

            if (NextFileSystem != null)
            {
                fileSystems.Add(NextFileSystem);
            }

            // Query all filesystems just once
            lock (_fileSystems)
            {
                fileSystems.AddRange(_fileSystems);
            }

            while (directoryToVisit.Count > 0)
            {
                var pathToVisit = directoryToVisit[0];
                directoryToVisit.RemoveAt(0);
                int dirIndex = 0;
                entries.Clear();
                sortedDirectories.Clear();

                for (var i = fileSystems.Count - 1; i >= 0; i--)
                {
                    var fileSystem = fileSystems[i];

                    if (fileSystem.DirectoryExists(pathToVisit))
                    {
                        foreach (var item in fileSystem.EnumeratePaths(pathToVisit, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
                        {
                            if (!entries.Contains(item))
                            {
                                var isFile      = fileSystem.FileExists(item);
                                var isDirectory = fileSystem.DirectoryExists(item);
                                var isMatching  = search.Match(item);

                                if (isMatching && ((isFile && searchTarget != SearchTarget.Directory) || (isDirectory && searchTarget != SearchTarget.File)))
                                {
                                    entries.Add(item);
                                }

                                if (searchOption == SearchOption.AllDirectories && isDirectory)
                                {
                                    sortedDirectories.Add(item);
                                }
                            }
                        }
                    }
                }

                // Enqueue directories and respect order
                foreach (var nextDir in sortedDirectories)
                {
                    directoryToVisit.Insert(dirIndex++, nextDir);
                }

                // Return entries
                foreach (var entry in entries)
                {
                    yield return(entry);
                }
            }
        }
Exemple #25
0
 /// <summary>
 /// Returns an enumerable collection of <see cref="FileSystemEntry"/> that match a search pattern in a specified path.
 /// </summary>
 /// <param name="fileSystem">The file system.</param>
 /// <param name="path">The path of the directory to look for files and directories.</param>
 /// <param name="searchPattern">The search string to match against the names of directories in path. This parameter can contain a combination
 /// of valid literal path and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions.</param>
 /// <param name="searchOption">One of the enumeration values that specifies whether the search operation should include only the current directory
 /// or should include all subdirectories.
 /// The default value is TopDirectoryOnly.</param>
 /// <param name="searchTarget">The search target either <see cref="SearchTarget.Both"/> or only <see cref="SearchTarget.Directory"/> or <see cref="SearchTarget.File"/>. Default is <see cref="SearchTarget.Both"/></param>
 /// <returns>An enumerable collection of <see cref="FileSystemEntry"/> that match a search pattern in a specified path.</returns>
 public static IEnumerable <FileSystemEntry> EnumerateFileSystemEntries(this IFileSystem fileSystem, UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget = SearchTarget.Both)
 {
     if (searchPattern is null)
     {
         throw new ArgumentNullException(nameof(searchPattern));
     }
     foreach (var subPath in fileSystem.EnumeratePaths(path, searchPattern, searchOption, searchTarget))
     {
         yield return(fileSystem.DirectoryExists(subPath) ? (FileSystemEntry) new DirectoryEntry(fileSystem, subPath) : new FileEntry(fileSystem, subPath));
     }
 }
Exemple #26
0
 public override IEnumerable<string> EnumeratePaths(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     return Win32FileSystemEnumerableFactory.CreateFileNameIterator(fullPath, fullPath, searchPattern,
         (searchTarget & SearchTarget.Files) == SearchTarget.Files,
         (searchTarget & SearchTarget.Directories) == SearchTarget.Directories,
         searchOption);
 }
Exemple #27
0
 /// <summary>
 /// Implementation for <see cref="EnumeratePaths"/>, <paramref name="path"/> is guaranteed to be absolute and validated through <see cref="ValidatePath"/>.
 /// Returns an enumerable collection of file names and/or directory names that match a search pattern in a specified path, and optionally searches subdirectories.
 /// </summary>
 /// <param name="path">The path to the directory to search.</param>
 /// <param name="searchPattern">The search string to match against file-system entries in path. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters (see Remarks), but doesn't support regular expressions.</param>
 /// <param name="searchOption">One of the enumeration values that specifies whether the search operation should include only the current directory or should include all subdirectories.</param>
 /// <param name="searchTarget">The search target either <see cref="SearchTarget.Both"/> or only <see cref="SearchTarget.Directory"/> or <see cref="SearchTarget.File"/>.</param>
 /// <returns>An enumerable collection of file-system paths in the directory specified by path and that match the specified search pattern, option and target.</returns>
 protected abstract IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget);
Exemple #28
0
 public override IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     switch (searchTarget)
     {
         case SearchTarget.Directories:
             return Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption);
         case SearchTarget.Files:
             return Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption);
         case SearchTarget.Both:
             return Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption);
         default:
             throw new ArgumentException("searchTarget", SR.ArgumentOutOfRange_Enum);
     }
 }
Exemple #29
0
 public SearchArg(int tagId, int pageIndex)
 {
     TagId     = tagId;
     PageIndex = pageIndex;
     Target    = SearchTarget.Tagged;
 }
 public override void OnNavigatingFrom(NavigatingFromEventArgs e, Dictionary<string, object> viewModelState, bool suspending)
 {
     _LastSelectedTarget = SelectedTarget.Value;
     _LastKeyword = SearchText.Value;
     base.OnNavigatingFrom(e, viewModelState, suspending);
 }
Exemple #31
0
 public SearchArg(int pageIndex)
 {
     PageIndex = pageIndex;
     Target    = SearchTarget.Recent;
 }
 public override Collections.Generic.IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     return Select(fullPath).EnumerateFileSystemInfos(fullPath, searchPattern, searchOption, searchTarget);
 }
Exemple #33
0
 public override Collections.Generic.IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     return(Select(fullPath).EnumerateFileSystemInfos(fullPath, searchPattern, searchOption, searchTarget));
 }
Exemple #34
0
        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Use the search pattern to normalize the path/search pattern
            var search          = SearchPattern.Parse(ref path, ref searchPattern);
            var originalSrcPath = path;

            // Internal method used to retrieve the list of root directories
            SortedSet <UPath> GetRootDirectories()
            {
                var directories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);

                lock (_mounts)
                {
                    foreach (var mountName in _mounts.Keys)
                    {
                        directories.Add(mountName);
                    }
                }

                if (NextFileSystem != null)
                {
                    foreach (var dir in NextFileSystem.EnumeratePaths(path, "*", SearchOption.TopDirectoryOnly, SearchTarget.Directory))
                    {
                        if (!directories.Contains(dir))
                        {
                            directories.Add(dir);
                        }
                    }
                }

                return(directories);
            }

            IEnumerable <UPath> EnumeratePathFromFileSystem(UPath subPath, bool failOnInvalidPath)
            {
                var fs = TryGetMountOrNext(ref subPath, out var mountPath);

                if (fs == null)
                {
                    if (failOnInvalidPath)
                    {
                        throw NewDirectoryNotFoundException(originalSrcPath);
                    }
                    yield break;
                }

                if (fs != NextFileSystem)
                {
                    // In the case of a mount, we need to return the full path
                    Debug.Assert(!mountPath.IsNull);

                    foreach (var entry in fs.EnumeratePaths(subPath, searchPattern, searchOption, searchTarget))
                    {
                        yield return(mountPath / entry.ToRelative());
                    }
                }
                else
                {
                    foreach (var entry in fs.EnumeratePaths(subPath, searchPattern, searchOption, searchTarget))
                    {
                        yield return(entry);
                    }
                }
            }

            // Special case for the root as we have to return the list of mount directories
            // and merge them with the underlying FileSystem
            if (path == UPath.Root)
            {
                var entries = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);

                // Return the list of dircetories
                var directories = GetRootDirectories();

                // Process the files first
                if (NextFileSystem != null && (searchTarget == SearchTarget.File || searchTarget == SearchTarget.Both))
                {
                    foreach (var file in NextFileSystem.EnumeratePaths(path, searchPattern, SearchOption.TopDirectoryOnly, SearchTarget.File))
                    {
                        entries.Add(file);
                    }
                }

                if (searchTarget != SearchTarget.File)
                {
                    foreach (var dir in directories)
                    {
                        if (search.Match(dir))
                        {
                            entries.Add(dir);
                        }
                    }
                }

                // Return all entries sorted
                foreach (var entry in entries)
                {
                    yield return(entry);
                }

                if (searchOption == SearchOption.AllDirectories)
                {
                    foreach (var dir in directories)
                    {
                        foreach (var entry in EnumeratePathFromFileSystem(dir, false))
                        {
                            yield return(entry);
                        }
                    }
                }
            }
            else
            {
                foreach (var entry in EnumeratePathFromFileSystem(path, true))
                {
                    yield return(entry);
                }
            }
        }
Exemple #35
0
 public override IEnumerable <string> EnumeratePaths(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
 {
     return(new FileSystemEnumerable <string>(path, searchPattern, searchOption, searchTarget, (p, _) => p));
 }
        /// <summary>
        ///     TODO
        /// </summary>
        /// <param name="word">検索する単語</param>
        /// <param name="sort">ソート順</param>
        /// <param name="searchTarget">検索対象</param>
        /// <param name="bookmarkMinNum">TODO</param>
        /// <param name="startDate">開始日時</param>
        /// <param name="endDate">終了日時</param>
        /// <param name="filter">フィルター (`for_ios` が有効)</param>
        /// <returns>
        ///     <see cref="IEnumerable{BookmarkRange}" />
        /// </returns>
        public async Task <IEnumerable <BookmarkRange> > NovelAsync(string word, SortOrder sort, SearchTarget searchTarget, string bookmarkMinNum = "",
                                                                    string startDate = "", string endDate = "", string filter = "")
        {
            Ensure.NotNullOrWhitespace(word, nameof(word));

            var parameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("word", word),
                new KeyValuePair <string, string>("sort", sort.ToParameter()),
                new KeyValuePair <string, string>("search_target", searchTarget.ToParameter())
            };

            if (!string.IsNullOrWhiteSpace(bookmarkMinNum))
            {
                parameters.Add(new KeyValuePair <string, string>("bookmark_min_num", bookmarkMinNum));
            }
            if (!string.IsNullOrWhiteSpace(startDate))
            {
                parameters.Add(new KeyValuePair <string, string>("start_date", startDate));
            }
            if (!string.IsNullOrWhiteSpace(endDate))
            {
                parameters.Add(new KeyValuePair <string, string>("end_date", endDate));
            }
            if (!string.IsNullOrWhiteSpace(filter))
            {
                parameters.Add(new KeyValuePair <string, string>("filter", filter));
            }

            var response = await PixivClient.GetAsync("https://app-api.pixiv.net/v1/search/bookmark-ranges/novel", parameters).Stay();

            return(response["bookmark_ranges"].ToObject <IEnumerable <BookmarkRange> >());
        }
Exemple #37
0
        /// <inheritdoc />
        protected override IEnumerable <UPath> EnumeratePathsImpl(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Use the search pattern to normalize the path/search pattern
            var search = SearchPattern.Parse(ref path, ref searchPattern);

            // Query all mounts just once
            List <KeyValuePair <UPath, IFileSystem> > mounts;

            lock (_mounts)
            {
                mounts = _mounts.ToList();
            }

            // Internal method used to retrieve the list of search locations
            List <SearchLocation> GetSearchLocations(UPath basePath)
            {
                var locations    = new List <SearchLocation>();
                var matchedMount = false;

                foreach (var kvp in mounts)
                {
                    // Check if path partially matches a mount name
                    var remainingPath = GetRemaining(basePath, kvp.Key);
                    if (!remainingPath.IsNull && remainingPath != UPath.Root)
                    {
                        locations.Add(new SearchLocation(this, basePath, remainingPath));
                        continue;
                    }

                    if (!matchedMount)
                    {
                        // Check if path fully matches a mount name
                        remainingPath = GetRemaining(kvp.Key, basePath);
                        if (!remainingPath.IsNull)
                        {
                            matchedMount = true; // don't check other mounts, we don't want to merge them together

                            if (kvp.Value.DirectoryExists(remainingPath))
                            {
                                locations.Add(new SearchLocation(kvp.Value, kvp.Key, remainingPath));
                            }
                        }
                    }
                }

                if (!matchedMount && NextFileSystem != null && NextFileSystem.DirectoryExists(basePath))
                {
                    locations.Add(new SearchLocation(NextFileSystem, null, basePath));
                }

                return(locations);
            }

            var directoryToVisit = new List <UPath>();

            directoryToVisit.Add(path);

            var entries           = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);
            var sortedDirectories = new SortedSet <UPath>(UPath.DefaultComparerIgnoreCase);

            var first = true;

            while (directoryToVisit.Count > 0)
            {
                var pathToVisit = directoryToVisit[0];
                directoryToVisit.RemoveAt(0);
                var dirIndex = 0;
                entries.Clear();
                sortedDirectories.Clear();

                var locations = GetSearchLocations(pathToVisit);

                // Only need to search within one filesystem, no need to sort or do other work
                if (locations.Count == 1 && locations[0].FileSystem != this && (!first || searchOption == SearchOption.AllDirectories))
                {
                    var last = locations[0];
                    foreach (var item in last.FileSystem.EnumeratePaths(last.Path, searchPattern, searchOption, searchTarget))
                    {
                        yield return(CombinePrefix(last.Prefix, item));
                    }
                }
                else
                {
                    for (var i = locations.Count - 1; i >= 0; i--)
                    {
                        var location   = locations[i];
                        var fileSystem = location.FileSystem;
                        var searchPath = location.Path;

                        if (fileSystem == this)
                        {
                            // List a single part of a mount name, queue it to be visited if needed
                            var mountPart = new UPath(searchPath.GetFirstDirectory(out _)).ToRelative();
                            var mountPath = location.Prefix / mountPart;

                            var isMatching = search.Match(mountPath);
                            if (isMatching && searchTarget != SearchTarget.File)
                            {
                                entries.Add(mountPath);
                            }

                            if (searchOption == SearchOption.AllDirectories)
                            {
                                sortedDirectories.Add(mountPath);
                            }
                        }
                        else
                        {
                            // List files in the mounted filesystems, merged and sorted into one list
                            foreach (var item in fileSystem.EnumeratePaths(searchPath, "*", SearchOption.TopDirectoryOnly, SearchTarget.Both))
                            {
                                var publicName = CombinePrefix(location.Prefix, item);
                                if (entries.Contains(publicName))
                                {
                                    continue;
                                }

                                var isFile      = fileSystem.FileExists(item);
                                var isDirectory = fileSystem.DirectoryExists(item);
                                var isMatching  = search.Match(publicName);

                                if (isMatching && ((isFile && searchTarget != SearchTarget.Directory) || (isDirectory && searchTarget != SearchTarget.File)))
                                {
                                    entries.Add(publicName);
                                }

                                if (searchOption == SearchOption.AllDirectories && isDirectory)
                                {
                                    sortedDirectories.Add(publicName);
                                }
                            }
                        }
                    }
                }

                if (first)
                {
                    if (locations.Count == 0 && path != UPath.Root)
                    {
                        throw NewDirectoryNotFoundException(path);
                    }

                    first = false;
                }

                // Enqueue directories and respect order
                foreach (var nextDir in sortedDirectories)
                {
                    directoryToVisit.Insert(dirIndex++, nextDir);
                }

                // Return entries
                foreach (var entry in entries)
                {
                    yield return(entry);
                }
            }
        }
        // ----------------------------------------------
        // Search API
        // ----------------------------------------------

        /// <inheritdoc />
        public IEnumerable <UPath> EnumeratePaths(UPath path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            foreach (var subPath in NextFileSystemSafe.EnumeratePaths(ConvertPathToDelegate(path), searchPattern, searchOption, searchTarget))
            {
                yield return(ConvertPathFromDelegate(subPath));
            }
        }
Exemple #39
0
        private async static Task <IReadOnlyList <IStorageItem> > EnumerateFileQuery(string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            // Get a StorageFolder for "path"
            string        fullPath = Path.GetFullPath(path);
            StorageFolder folder   = await StorageFolder.GetFolderFromPathAsync(fullPath).TranslateWinRTTask(fullPath, isDirectory: true);

            // Construct a query for the search.
            QueryOptions query = new QueryOptions();

            // Translate SearchOption into FolderDepth
            query.FolderDepth = searchOption == SearchOption.AllDirectories ? FolderDepth.Deep : FolderDepth.Shallow;

            // Construct an AQS filter
            string normalizedSearchPattern = PathHelpers.NormalizeSearchPattern(searchPattern);

            if (normalizedSearchPattern.Length == 0)
            {
                // An empty searchPattern will return no results and requires no AQS parsing.
                return(new IStorageItem[0]);
            }
            else
            {
                // Parse the query as an ItemPathDisplay filter.
                string searchPath = PathHelpers.GetFullSearchString(fullPath, normalizedSearchPattern);
                string aqs        = "System.ItemPathDisplay:~\"" + searchPath + "\"";
                query.ApplicationSearchFilter = aqs;

                // If the filtered path is deeper than the given user path, we need to get a new folder for it.
                // This occurs when someone does something like Enumerate("C:\first\second\", "C:\first\second\third\*").
                // When AllDirectories is set this isn't an issue, but for TopDirectoryOnly we have to do some special work
                // to make sure something is actually returned when the searchPattern is a subdirectory of the path.
                // To do this, we attempt to get a new StorageFolder for the subdirectory and return an empty enumerable
                // if we can't.
                string searchPatternDirName = Path.GetDirectoryName(normalizedSearchPattern);
                string userPath             = string.IsNullOrEmpty(searchPatternDirName) ? fullPath : Path.Combine(fullPath, searchPatternDirName);
                if (userPath != folder.Path)
                {
                    folder = await StorageFolder.GetFolderFromPathAsync(userPath).TranslateWinRTTask(userPath, isDirectory: true);
                }
            }

            // Execute our built query
            if (searchTarget == SearchTarget.Files)
            {
                StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(query);
                return(await queryResult.GetFilesAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else if (searchTarget == SearchTarget.Directories)
            {
                StorageFolderQueryResult queryResult = folder.CreateFolderQueryWithOptions(query);
                return(await queryResult.GetFoldersAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
            else
            {
                StorageItemQueryResult queryResult = folder.CreateItemQueryWithOptions(query);
                return(await queryResult.GetItemsAsync().TranslateWinRTTask(folder.Path, isDirectory: true));
            }
        }
Exemple #40
0
            public void Returns_expected_values(string id, string path, string searchPattern, SearchOption searchOption, SearchTarget searchTarget, string[] expected)
            {
                // ARRANGE
                _ = id;
                var sut           = new EmbeddedResourcesFileSystem(Assembly.GetExecutingAssembly());
                var expectedPaths = expected.Select(x => (UPath)x).ToHashSet();

                // ACT
                var actualPaths = sut.EnumeratePaths(path, searchPattern, searchOption, searchTarget);

                // ASSERT
                Assert.True(expectedPaths.SetEquals(actualPaths));
            }
Exemple #41
0
        public override IEnumerable <FileSystemInfo> EnumerateFileSystemInfos(string fullPath, string searchPattern, SearchOption searchOption, SearchTarget searchTarget)
        {
            switch (searchTarget)
            {
            case SearchTarget.Directories:
                return(Win32FileSystemEnumerableFactory.CreateDirectoryInfoIterator(fullPath, fullPath, searchPattern, searchOption));

            case SearchTarget.Files:
                return(Win32FileSystemEnumerableFactory.CreateFileInfoIterator(fullPath, fullPath, searchPattern, searchOption));

            case SearchTarget.Both:
                return(Win32FileSystemEnumerableFactory.CreateFileSystemInfoIterator(fullPath, fullPath, searchPattern, searchOption));

            default:
                throw new ArgumentException(SR.ArgumentOutOfRange_Enum, "searchTarget");
            }
        }
 public async Task<Tuple<string, string>> ConnectToSearch(HttpClient client, Uri plusBaseUrl, string keyword, SearchTarget target, SearchRange range, string searchTicket, string atVal)
 {
     keyword = keyword.Replace("\\", "\\\\");
     keyword = keyword.Replace("\"", "\\\"");
     var query = searchTicket == null
         ? new Dictionary<string, string>()
             {
                 { "at", atVal },
                 { "srchrp", string.Format("[[\"{0}\",{1},2,[{2}]]]", keyword, (int)target, (int)range) }
             }
         : new Dictionary<string, string>()
             {
                 { "at", atVal },
                 { "srchrp", string.Format("[[\"{0}\",{1},2,[{2}]],null,[\"{3}\"]]", keyword, (int)target, (int)range, searchTicket) }
             };
     var jsonTxt = ApiAccessorUtility.ConvertIntoValidJson(
         await PostStringAsync(client, new Uri(plusBaseUrl, "_/s/query?rt=j"), query));
     var json = JToken.Parse(jsonTxt);
     searchTicket = (string)json[0][1][1][1][2];
     return Tuple.Create(jsonTxt, searchTicket);
 }