| | | 1 | | // ----------------------------------------------------------------------- |
| | | 2 | | // <copyright file="FileExtensionFilter.cs" company="Stéphane ANDRE"> |
| | | 3 | | // Copyright (c) Stéphane ANDRE. All rights reserved. |
| | | 4 | | // </copyright> |
| | | 5 | | // ----------------------------------------------------------------------- |
| | | 6 | | |
| | | 7 | | using System; |
| | | 8 | | using System.Collections.Generic; |
| | | 9 | | using System.Linq; |
| | | 10 | | |
| | | 11 | | namespace MyNet.IO.FileExtensions; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Represents a file extension filter, which is a collection of file extension groups. Each group has a key and a list |
| | | 15 | | /// </summary> |
| | | 16 | | /// <param name="groups">The collection of file extension groups to be included in the filter.</param> |
| | | 17 | | public sealed class FileExtensionFilter(IEnumerable<FileExtensionGroup> groups) |
| | | 18 | | { |
| | | 19 | | /// <summary> |
| | | 20 | | /// Gets the collection of file extension groups included in the filter. Each group represents a category of files a |
| | | 21 | | /// </summary> |
| | 27 | 22 | | public IReadOnlyList<FileExtensionGroup> Groups { get; } = [.. groups]; |
| | | 23 | | |
| | | 24 | | /// <summary> |
| | | 25 | | /// Gets a combined list of all file extensions across all groups in the filter. This property flattens the list of |
| | | 26 | | /// </summary> |
| | 15 | 27 | | public IEnumerable<string> AllExtensions => Groups.SelectMany(g => g.Extensions) |
| | 15 | 28 | | .Select(e => e.Value) |
| | 15 | 29 | | .Distinct(); |
| | | 30 | | |
| | | 31 | | /// <summary> |
| | | 32 | | /// Generates a filter string that can be used in file dialogs to filter files based on their extensions. The filter |
| | | 33 | | /// </summary> |
| | | 34 | | /// <param name="localize">A function to localize the group names. If null, the group keys are used as-is.</param> |
| | | 35 | | /// <returns>A filter string that can be used in file dialogs.</returns> |
| | | 36 | | public string ToFilterString(Func<string, string>? localize = null) |
| | 6 | 37 | | => string.Join("|", |
| | 6 | 38 | | Groups.Select(g => |
| | 6 | 39 | | { |
| | 6 | 40 | | var name = localize?.Invoke(g.Key) ?? g.Key; |
| | 6 | 41 | | var exts = string.Join(";", g.Extensions.Select(e => $"*{e.Value}")); |
| | 6 | 42 | | return $"{name} ({exts})"; |
| | 6 | 43 | | })); |
| | | 44 | | } |
| | | 45 | | |