├── Blazor.Maui.PhotoSlideshow ├── Components │ ├── Layout │ │ ├── MainLayout.razor.css │ │ └── MainLayout.razor │ ├── Pages │ │ ├── Home.razor.css │ │ ├── NotFound.razor │ │ ├── Home.razor │ │ └── Home.razor.cs │ ├── Routes.razor │ └── _Imports.razor ├── Resources │ ├── Fonts │ │ └── OpenSans-Regular.ttf │ ├── AppIcon │ │ ├── appicon.svg │ │ └── appiconfg.svg │ ├── Raw │ │ └── AboutAssets.txt │ ├── Splash │ │ └── splash.svg │ └── Images │ │ └── dotnet_bot.svg ├── Properties │ └── launchSettings.json ├── MainPage.xaml.cs ├── Platforms │ ├── Android │ │ ├── Resources │ │ │ └── values │ │ │ │ └── colors.xml │ │ ├── AndroidManifest.xml │ │ ├── MainApplication.cs │ │ └── MainActivity.cs │ ├── iOS │ │ ├── AppDelegate.cs │ │ ├── Program.cs │ │ ├── Info.plist │ │ └── Resources │ │ │ └── PrivacyInfo.xcprivacy │ ├── MacCatalyst │ │ ├── AppDelegate.cs │ │ ├── Program.cs │ │ ├── Entitlements.plist │ │ └── Info.plist │ └── Windows │ │ ├── App.xaml │ │ ├── App.xaml.cs │ │ ├── app.manifest │ │ └── Package.appxmanifest ├── Models │ └── ImageItem.cs ├── App.xaml ├── MainPage.xaml ├── App.xaml.cs ├── wwwroot │ ├── index.html │ └── app.css ├── MauiProgram.cs ├── Blazor.Maui.PhotoSlideshow.csproj └── Services │ ├── ImageConverterService.cs │ ├── ThumbnailService.cs │ ├── ImageCacheService.cs │ └── SlideshowService.cs ├── README.md ├── BenchmarkSuite1 ├── Services │ ├── ThumbnailService.cs │ └── ImageConverterService.cs ├── Program.cs ├── BenchmarkSuite1.csproj └── ImageProcessingBenchmarks.cs ├── Blazor-Maui-PhotoSlideshow.sln └── .gitignore /Blazor.Maui.PhotoSlideshow/Components/Layout/MainLayout.razor.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Layout/MainLayout.razor: -------------------------------------------------------------------------------- 1 | @inherits LayoutComponentBase 2 | 3 | @Body 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fully vibe-coded :/ 2 | 3 | https://github.com/user-attachments/assets/3a92dbe8-7e84-4d37-ae1f-75e784e794b4 4 | 5 | -------------------------------------------------------------------------------- /BenchmarkSuite1/Services/ThumbnailService.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tossnet/Blazor-Maui-PhotoSlideshow/main/BenchmarkSuite1/Services/ThumbnailService.cs -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Pages/Home.razor.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tossnet/Blazor-Maui-PhotoSlideshow/main/Blazor.Maui.PhotoSlideshow/Components/Pages/Home.razor.css -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Pages/NotFound.razor: -------------------------------------------------------------------------------- 1 | @page "/not-found" 2 | @layout MainLayout 3 | 4 |

Not Found

5 |

Sorry, the content you are looking for does not exist.

6 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/Fonts/OpenSans-Regular.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tossnet/Blazor-Maui-PhotoSlideshow/main/Blazor.Maui.PhotoSlideshow/Resources/Fonts/OpenSans-Regular.ttf -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "profiles": { 3 | "Windows Machine": { 4 | "commandName": "Project", 5 | "nativeDebugging": false 6 | } 7 | } 8 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/MainPage.xaml.cs: -------------------------------------------------------------------------------- 1 | namespace Blazor.Maui.PhotoSlideshow; 2 | 3 | public partial class MainPage : ContentPage 4 | { 5 | public MainPage() 6 | { 7 | InitializeComponent(); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/AppIcon/appicon.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Android/Resources/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #512BD4 4 | #2B0B98 5 | #2B0B98 6 | -------------------------------------------------------------------------------- /BenchmarkSuite1/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | namespace BenchmarkSuite1 4 | { 5 | internal class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | var _ = BenchmarkRunner.Run(typeof(Program).Assembly); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/iOS/AppDelegate.cs: -------------------------------------------------------------------------------- 1 | using Foundation; 2 | 3 | namespace Blazor.Maui.PhotoSlideshow 4 | { 5 | [Register("AppDelegate")] 6 | public class AppDelegate : MauiUIApplicationDelegate 7 | { 8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/MacCatalyst/AppDelegate.cs: -------------------------------------------------------------------------------- 1 | using Foundation; 2 | 3 | namespace Blazor.Maui.PhotoSlideshow 4 | { 5 | [Register("AppDelegate")] 6 | public class AppDelegate : MauiUIApplicationDelegate 7 | { 8 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Routes.razor: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Windows/App.xaml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/_Imports.razor: -------------------------------------------------------------------------------- 1 | @using System.Net.Http 2 | @using System.Net.Http.Json 3 | @using Microsoft.AspNetCore.Components.Forms 4 | @using Microsoft.AspNetCore.Components.Routing 5 | @using Microsoft.AspNetCore.Components.Web 6 | @using Microsoft.AspNetCore.Components.Web.Virtualization 7 | @using Microsoft.JSInterop 8 | @using Blazor.Maui.PhotoSlideshow 9 | @using Blazor.Maui.PhotoSlideshow.Components 10 | @using Blazor.Maui.PhotoSlideshow.Components.Layout 11 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Android/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Android/MainApplication.cs: -------------------------------------------------------------------------------- 1 | using Android.App; 2 | using Android.Runtime; 3 | 4 | namespace Blazor.Maui.PhotoSlideshow 5 | { 6 | [Application] 7 | public class MainApplication : MauiApplication 8 | { 9 | public MainApplication(IntPtr handle, JniHandleOwnership ownership) 10 | : base(handle, ownership) 11 | { 12 | } 13 | 14 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Android/MainActivity.cs: -------------------------------------------------------------------------------- 1 | using Android.App; 2 | using Android.Content.PM; 3 | using Android.OS; 4 | 5 | namespace Blazor.Maui.PhotoSlideshow 6 | { 7 | [Activity(Theme = "@style/Maui.SplashTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize | ConfigChanges.Density)] 8 | public class MainActivity : MauiAppCompatActivity 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /BenchmarkSuite1/BenchmarkSuite1.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net10.0 5 | Exe 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/MacCatalyst/Program.cs: -------------------------------------------------------------------------------- 1 | using ObjCRuntime; 2 | using UIKit; 3 | 4 | namespace Blazor.Maui.PhotoSlideshow 5 | { 6 | public class Program 7 | { 8 | // This is the main entry point of the application. 9 | static void Main(string[] args) 10 | { 11 | // if you want to use a different Application Delegate class from "AppDelegate" 12 | // you can specify it here. 13 | UIApplication.Main(args, null, typeof(AppDelegate)); 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/iOS/Program.cs: -------------------------------------------------------------------------------- 1 | using ObjCRuntime; 2 | using UIKit; 3 | 4 | namespace Blazor.Maui.PhotoSlideshow 5 | { 6 | public class Program 7 | { 8 | // This is the main entry point of the application. 9 | static void Main(string[] args) 10 | { 11 | // if you want to use a different Application Delegate class from "AppDelegate" 12 | // you can specify it here. 13 | UIApplication.Main(args, null, typeof(AppDelegate)); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Models/ImageItem.cs: -------------------------------------------------------------------------------- 1 | namespace Blazor.Maui.PhotoSlideshow.Models; 2 | 3 | public class ImageItem 4 | { 5 | public string NetworkPath { get; set; } = string.Empty; 6 | public string? CachedPath { get; set; } // Chemin de la MINIATURE (pour mosaïque) 7 | public string? FullscreenPath { get; set; } // Chemin de l'image COMPLÈTE (pour plein écran) 8 | public double X { get; set; } 9 | public double Y { get; set; } 10 | public double Scale { get; set; } = 1.0; 11 | public double Rotation { get; set; } 12 | public double Opacity { get; set; } = 1.0; 13 | public bool IsFullScreen { get; set; } 14 | } 15 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/App.xaml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/MainPage.xaml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/App.xaml.cs: -------------------------------------------------------------------------------- 1 | namespace Blazor.Maui.PhotoSlideshow 2 | { 3 | public partial class App : Application 4 | { 5 | public App() 6 | { 7 | InitializeComponent(); 8 | MainPage = new MainPage(); 9 | } 10 | 11 | protected override Window CreateWindow(IActivationState? activationState) 12 | { 13 | var window = base.CreateWindow(activationState); 14 | 15 | #if WINDOWS 16 | window.Width = 1920; 17 | window.Height = 1080; 18 | window.MinimumWidth = 800; 19 | window.MinimumHeight = 600; 20 | #endif 21 | 22 | return window; 23 | return new Window(new MainPage()) { Title = "PhotoSlideshow" }; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/MacCatalyst/Entitlements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | com.apple.security.app-sandbox 8 | 9 | 10 | com.apple.security.network.client 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/Raw/AboutAssets.txt: -------------------------------------------------------------------------------- 1 | Any raw assets you want to be deployed with your application can be placed in 2 | this directory (and child directories). Deployment of the asset to your application 3 | is automatically handled by the following `MauiAsset` Build Action within your `.csproj`. 4 | 5 | 6 | 7 | These files will be deployed with your package and will be accessible using Essentials: 8 | 9 | async Task LoadMauiAsset() 10 | { 11 | using var stream = await FileSystem.OpenAppPackageFileAsync("AboutAssets.txt"); 12 | using var reader = new StreamReader(stream); 13 | 14 | var contents = reader.ReadToEnd(); 15 | } 16 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/wwwroot/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | PhotoSlideshow 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 |
Loading...
18 | 19 |
20 | An unhandled error has occurred. 21 | Reload 22 | 🗙 23 |
24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Windows/App.xaml.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.UI.Xaml; 2 | 3 | // To learn more about WinUI, the WinUI project structure, 4 | // and more about our project templates, see: http://aka.ms/winui-project-info. 5 | 6 | namespace Blazor.Maui.PhotoSlideshow.WinUI 7 | { 8 | /// 9 | /// Provides application-specific behavior to supplement the default Application class. 10 | /// 11 | public partial class App : MauiWinUIApplication 12 | { 13 | /// 14 | /// Initializes the singleton application object. This is the first line of authored code 15 | /// executed, and as such is the logical equivalent of main() or WinMain(). 16 | /// 17 | public App() 18 | { 19 | this.InitializeComponent(); 20 | } 21 | 22 | protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Windows/app.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | true/PM 12 | PerMonitorV2, PerMonitor 13 | 14 | true 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/MauiProgram.cs: -------------------------------------------------------------------------------- 1 | using Blazor.Maui.PhotoSlideshow.Services; 2 | using Microsoft.Extensions.Logging; 3 | 4 | namespace Blazor.Maui.PhotoSlideshow 5 | { 6 | public static class MauiProgram 7 | { 8 | public static MauiApp CreateMauiApp() 9 | { 10 | var builder = MauiApp.CreateBuilder(); 11 | builder 12 | .UseMauiApp() 13 | .ConfigureFonts(fonts => 14 | { 15 | fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular"); 16 | }); 17 | 18 | builder.Services.AddMauiBlazorWebView(); 19 | 20 | builder.Services.AddSingleton(); 21 | builder.Services.AddSingleton(); 22 | builder.Services.AddSingleton(); 23 | builder.Services.AddSingleton(); 24 | 25 | #if DEBUG 26 | builder.Services.AddBlazorWebViewDeveloperTools(); 27 | builder.Logging.AddDebug(); 28 | #endif 29 | 30 | return builder.Build(); 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/iOS/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | LSRequiresIPhoneOS 6 | 7 | UIDeviceFamily 8 | 9 | 1 10 | 2 11 | 12 | UIRequiredDeviceCapabilities 13 | 14 | arm64 15 | 16 | UISupportedInterfaceOrientations 17 | 18 | UIInterfaceOrientationPortrait 19 | UIInterfaceOrientationLandscapeLeft 20 | UIInterfaceOrientationLandscapeRight 21 | 22 | UISupportedInterfaceOrientations~ipad 23 | 24 | UIInterfaceOrientationPortrait 25 | UIInterfaceOrientationPortraitUpsideDown 26 | UIInterfaceOrientationLandscapeLeft 27 | UIInterfaceOrientationLandscapeRight 28 | 29 | XSAppIconAssets 30 | Assets.xcassets/appicon.appiconset 31 | 32 | 33 | -------------------------------------------------------------------------------- /Blazor-Maui-PhotoSlideshow.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 18 4 | VisualStudioVersion = 18.3.11206.111 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Blazor.Maui.PhotoSlideshow", "Blazor.Maui.PhotoSlideshow\Blazor.Maui.PhotoSlideshow.csproj", "{1B557B03-5B7B-4BD1-96B7-395BC34C5085}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BenchmarkSuite1", "BenchmarkSuite1\BenchmarkSuite1.csproj", "{A20861A9-411E-6150-BF5C-69E8196E5D22}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Debug|Any CPU.Deploy.0 = Debug|Any CPU 19 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Release|Any CPU.ActiveCfg = Release|Any CPU 20 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Release|Any CPU.Build.0 = Release|Any CPU 21 | {1B557B03-5B7B-4BD1-96B7-395BC34C5085}.Release|Any CPU.Deploy.0 = Release|Any CPU 22 | {A20861A9-411E-6150-BF5C-69E8196E5D22}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {A20861A9-411E-6150-BF5C-69E8196E5D22}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {A20861A9-411E-6150-BF5C-69E8196E5D22}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {A20861A9-411E-6150-BF5C-69E8196E5D22}.Release|Any CPU.Build.0 = Release|Any CPU 26 | EndGlobalSection 27 | GlobalSection(SolutionProperties) = preSolution 28 | HideSolutionNode = FALSE 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/Splash/splash.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/AppIcon/appiconfg.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/MacCatalyst/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | UIDeviceFamily 15 | 16 | 2 17 | 18 | UIRequiredDeviceCapabilities 19 | 20 | arm64 21 | 22 | UISupportedInterfaceOrientations 23 | 24 | UIInterfaceOrientationPortrait 25 | UIInterfaceOrientationLandscapeLeft 26 | UIInterfaceOrientationLandscapeRight 27 | 28 | UISupportedInterfaceOrientations~ipad 29 | 30 | UIInterfaceOrientationPortrait 31 | UIInterfaceOrientationPortraitUpsideDown 32 | UIInterfaceOrientationLandscapeLeft 33 | UIInterfaceOrientationLandscapeRight 34 | 35 | XSAppIconAssets 36 | Assets.xcassets/appicon.appiconset 37 | 38 | 39 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/Windows/Package.appxmanifest: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | $placeholder$ 15 | User Name 16 | $placeholder$.png 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Platforms/iOS/Resources/PrivacyInfo.xcprivacy: -------------------------------------------------------------------------------- 1 | 2 | 10 | 11 | 12 | 13 | NSPrivacyAccessedAPITypes 14 | 15 | 16 | NSPrivacyAccessedAPIType 17 | NSPrivacyAccessedAPICategoryFileTimestamp 18 | NSPrivacyAccessedAPITypeReasons 19 | 20 | C617.1 21 | 22 | 23 | 24 | NSPrivacyAccessedAPIType 25 | NSPrivacyAccessedAPICategorySystemBootTime 26 | NSPrivacyAccessedAPITypeReasons 27 | 28 | 35F9.1 29 | 30 | 31 | 32 | NSPrivacyAccessedAPIType 33 | NSPrivacyAccessedAPICategoryDiskSpace 34 | NSPrivacyAccessedAPITypeReasons 35 | 36 | E174.1 37 | 38 | 39 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /BenchmarkSuite1/Services/ImageConverterService.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | using System.Collections.Concurrent; 5 | 6 | namespace BenchmarkSuite1.Services; 7 | 8 | public class ImageConverterService 9 | { 10 | private readonly ConcurrentDictionary _base64Cache = new(); 11 | private readonly ConcurrentDictionary> _pendingConversions = new(); 12 | 13 | public async Task ConvertToBase64Async(string imagePath) 14 | { 15 | if (string.IsNullOrEmpty(imagePath)) 16 | return string.Empty; 17 | 18 | if (_base64Cache.TryGetValue(imagePath, out var cached)) 19 | return cached; 20 | 21 | if (_pendingConversions.TryGetValue(imagePath, out var pendingTask)) 22 | return await pendingTask; 23 | 24 | var conversionTask = Task.Run(async () => 25 | { 26 | try 27 | { 28 | if (!File.Exists(imagePath)) 29 | return string.Empty; 30 | 31 | var bytes = await File.ReadAllBytesAsync(imagePath); 32 | var base64 = Convert.ToBase64String(bytes); 33 | var ext = Path.GetExtension(imagePath).ToLower(); 34 | 35 | var mimeType = ext switch 36 | { 37 | ".jpg" or ".jpeg" => "image/jpeg", 38 | ".png" => "image/png", 39 | ".gif" => "image/gif", 40 | ".bmp" => "image/bmp", 41 | _ => "image/jpeg" 42 | }; 43 | 44 | var result = $"data:{mimeType};base64,{base64}"; 45 | _base64Cache.TryAdd(imagePath, result); 46 | 47 | return result; 48 | } 49 | catch (Exception ex) 50 | { 51 | Console.WriteLine($"Erreur conversion image {Path.GetFileName(imagePath)}: {ex.Message}"); 52 | return string.Empty; 53 | } 54 | finally 55 | { 56 | _pendingConversions.TryRemove(imagePath, out _); 57 | } 58 | }); 59 | 60 | _pendingConversions.TryAdd(imagePath, conversionTask); 61 | return await conversionTask; 62 | } 63 | 64 | public void ClearCache() 65 | { 66 | _base64Cache.Clear(); 67 | _pendingConversions.Clear(); 68 | } 69 | 70 | public Task PreloadImageAsync(string imagePath) 71 | { 72 | return ConvertToBase64Async(imagePath); 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Pages/Home.razor: -------------------------------------------------------------------------------- 1 | @page "/" 2 | 3 | 4 |
5 | @if (_currentImages.Any()) 6 | { 7 |
8 | @foreach (var image in _currentImages) 9 | { 10 | @if (!string.IsNullOrEmpty(image.CachedPath) && !image.IsFullScreen) 11 | { 12 |
14 | @* mosaïque *@ 15 | Photo 16 |
17 | } 18 | } 19 |
20 | 21 | @* Image plein écran en dehors de la grille *@ 22 | @foreach (var image in _currentImages.Where(img => img.IsFullScreen)) 23 | { 24 | @if (!string.IsNullOrEmpty(image.FullscreenPath)) 25 | { 26 |
27 | @if (_fullscreenImageBase64 != null) 28 | { 29 | 30 | } 31 | else 32 | { 33 |
Chargement de l'image...
34 | } 35 |
36 | } 37 | } 38 | } 39 | else 40 | { 41 |
42 |

Scan du réseau en cours...

43 |

L'affichage démarrera dès les premières images trouvées

44 |
45 | } 46 |
47 | 48 |
49 | 50 | 51 | 52 |
53 | @if (!SlideshowService.IsLoadingComplete) 54 | { 55 |

Chargement: @SlideshowService.LoadedImages / @SlideshowService.TotalImages

56 | @if (SlideshowService.TotalImages > 0) 57 | { 58 | 59 | } 60 | } 61 | else 62 | { 63 |

✓ @SlideshowService.TotalImages images chargées

64 | } 65 | @* NOUVEAU: Afficher les stats du cache *@ 66 |

Cache: @_cacheStats.count images (@_cacheStats.pending en cours)

67 |
68 |
69 | 70 | @if (_showSettings) 71 | { 72 |
73 |

Configuration

74 |
75 | 76 | 77 |
78 |
79 | 80 | 81 |
82 |
83 | } 84 | 85 | -------------------------------------------------------------------------------- /BenchmarkSuite1/ImageProcessingBenchmarks.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Threading.Tasks; 4 | using BenchmarkDotNet.Attributes; 5 | using BenchmarkDotNet.Diagnosers; 6 | using BenchmarkSuite1.Services; 7 | using SkiaSharp; 8 | 9 | namespace BenchmarkSuite1; 10 | 11 | [MemoryDiagnoser] 12 | public class ImageProcessingBenchmarks 13 | { 14 | private ThumbnailService _thumbnailService = null!; 15 | private ImageConverterService _imageConverter = null!; 16 | private string _testImagePath = null!; 17 | private string _testThumbnailPath = null!; 18 | private string _existingThumbnail = null!; 19 | 20 | [GlobalSetup] 21 | public async Task Setup() 22 | { 23 | _thumbnailService = new ThumbnailService(); 24 | _imageConverter = new ImageConverterService(); 25 | 26 | var tempDir = Path.Combine(Path.GetTempPath(), "PhotoSlideshowBenchmarks"); 27 | Directory.CreateDirectory(tempDir); 28 | 29 | _testImagePath = Path.Combine(tempDir, "test_image.jpg"); 30 | _testThumbnailPath = Path.Combine(tempDir, "test_thumbnail.jpg"); 31 | 32 | if (!File.Exists(_testImagePath)) 33 | { 34 | using var bitmap = new SKBitmap(4000, 3000); 35 | using var canvas = new SKCanvas(bitmap); 36 | canvas.Clear(SKColors.Blue); 37 | 38 | using var paint = new SKPaint 39 | { 40 | Color = SKColors.White, 41 | TextSize = 100, 42 | IsAntialias = true 43 | }; 44 | canvas.DrawText("Benchmark Image", 100, 200, paint); 45 | 46 | using var image = SKImage.FromBitmap(bitmap); 47 | using var data = image.Encode(SKEncodedImageFormat.Jpeg, 90); 48 | await File.WriteAllBytesAsync(_testImagePath, data.ToArray()); 49 | } 50 | 51 | _existingThumbnail = await _thumbnailService.CreateThumbnailAsync(_testImagePath, _testThumbnailPath) ?? string.Empty; 52 | } 53 | 54 | [Benchmark] 55 | public async Task ThumbnailCreation() 56 | { 57 | var outputPath = Path.Combine(Path.GetTempPath(), $"thumb_{Guid.NewGuid()}.jpg"); 58 | var result = await _thumbnailService.CreateThumbnailAsync(_testImagePath, outputPath); 59 | 60 | if (File.Exists(outputPath)) 61 | File.Delete(outputPath); 62 | 63 | return result; 64 | } 65 | 66 | [Benchmark] 67 | public async Task Base64Conversion() 68 | { 69 | _imageConverter.ClearCache(); 70 | return await _imageConverter.ConvertToBase64Async(_existingThumbnail); 71 | } 72 | 73 | [Benchmark] 74 | public async Task Base64ConversionWithCache() 75 | { 76 | await _imageConverter.ConvertToBase64Async(_existingThumbnail); 77 | return await _imageConverter.ConvertToBase64Async(_existingThumbnail); 78 | } 79 | 80 | [GlobalCleanup] 81 | public void Cleanup() 82 | { 83 | _imageConverter.ClearCache(); 84 | 85 | var tempDir = Path.Combine(Path.GetTempPath(), "PhotoSlideshowBenchmarks"); 86 | if (Directory.Exists(tempDir)) 87 | { 88 | try 89 | { 90 | Directory.Delete(tempDir, true); 91 | } 92 | catch 93 | { 94 | // Ignore cleanup errors 95 | } 96 | } 97 | } 98 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/wwwroot/app.css: -------------------------------------------------------------------------------- 1 | body { 2 | margin: 0; 3 | padding: 0; 4 | font-family: Roboto, Helvetica, Arial, sans-serif; 5 | } 6 | 7 | h1:focus { 8 | outline: none; 9 | } 10 | 11 | .valid.modified:not([type=checkbox]) { 12 | outline: 1px solid #26b050; 13 | } 14 | 15 | .invalid { 16 | outline: 1px solid #e50000; 17 | } 18 | 19 | .validation-message { 20 | color: #e50000; 21 | } 22 | 23 | #blazor-error-ui { 24 | color-scheme: light only; 25 | background: lightyellow; 26 | bottom: 0; 27 | box-shadow: 0 -1px 2px rgba(0, 0, 0, 0.2); 28 | box-sizing: border-box; 29 | display: none; 30 | left: 0; 31 | padding: 0.6rem 1.25rem 0.7rem 1.25rem; 32 | position: fixed; 33 | width: 100%; 34 | z-index: 1000; 35 | } 36 | 37 | #blazor-error-ui .dismiss { 38 | cursor: pointer; 39 | position: absolute; 40 | right: 0.75rem; 41 | top: 0.5rem; 42 | } 43 | 44 | .blazor-error-boundary { 45 | background: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNTYiIGhlaWdodD0iNDkiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIG92ZXJmbG93PSJoaWRkZW4iPjxkZWZzPjxjbGlwUGF0aCBpZD0iY2xpcDAiPjxyZWN0IHg9IjIzNSIgeT0iNTEiIHdpZHRoPSI1NiIgaGVpZ2h0PSI0OSIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMCkiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMzUgLTUxKSI+PHBhdGggZD0iTTI2My41MDYgNTFDMjY0LjcxNyA1MSAyNjUuODEzIDUxLjQ4MzcgMjY2LjYwNiA1Mi4yNjU4TDI2Ny4wNTIgNTIuNzk4NyAyNjcuNTM5IDUzLjYyODMgMjkwLjE4NSA5Mi4xODMxIDI5MC41NDUgOTIuNzk1IDI5MC42NTYgOTIuOTk2QzI5MC44NzcgOTMuNTEzIDI5MSA5NC4wODE1IDI5MSA5NC42NzgyIDI5MSA5Ny4wNjUxIDI4OS4wMzggOTkgMjg2LjYxNyA5OUwyNDAuMzgzIDk5QzIzNy45NjMgOTkgMjM2IDk3LjA2NTEgMjM2IDk0LjY3ODIgMjM2IDk0LjM3OTkgMjM2LjAzMSA5NC4wODg2IDIzNi4wODkgOTMuODA3MkwyMzYuMzM4IDkzLjAxNjIgMjM2Ljg1OCA5Mi4xMzE0IDI1OS40NzMgNTMuNjI5NCAyNTkuOTYxIDUyLjc5ODUgMjYwLjQwNyA1Mi4yNjU4QzI2MS4yIDUxLjQ4MzcgMjYyLjI5NiA1MSAyNjMuNTA2IDUxWk0yNjMuNTg2IDY2LjAxODNDMjYwLjczNyA2Ni4wMTgzIDI1OS4zMTMgNjcuMTI0NSAyNTkuMzEzIDY5LjMzNyAyNTkuMzEzIDY5LjYxMDIgMjU5LjMzMiA2OS44NjA4IDI1OS4zNzEgNzAuMDg4N0wyNjEuNzk1IDg0LjAxNjEgMjY1LjM4IDg0LjAxNjEgMjY3LjgyMSA2OS43NDc1QzI2Ny44NiA2OS43MzA5IDI2Ny44NzkgNjkuNTg3NyAyNjcuODc5IDY5LjMxNzkgMjY3Ljg3OSA2Ny4xMTgyIDI2Ni40NDggNjYuMDE4MyAyNjMuNTg2IDY2LjAxODNaTTI2My41NzYgODYuMDU0N0MyNjEuMDQ5IDg2LjA1NDcgMjU5Ljc4NiA4Ny4zMDA1IDI1OS43ODYgODkuNzkyMSAyNTkuNzg2IDkyLjI4MzcgMjYxLjA0OSA5My41Mjk1IDI2My41NzYgOTMuNTI5NSAyNjYuMTE2IDkzLjUyOTUgMjY3LjM4NyA5Mi4yODM3IDI2Ny4zODcgODkuNzkyMSAyNjcuMzg3IDg3LjMwMDUgMjY2LjExNiA4Ni4wNTQ3IDI2My41NzYgODYuMDU0N1oiIGZpbGw9IiNGRkU1MDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPjwvZz48L3N2Zz4=) no-repeat 1rem/1.8rem, #b32121; 46 | padding: 1rem 1rem 1rem 3.7rem; 47 | color: white; 48 | } 49 | 50 | .blazor-error-boundary::after { 51 | content: "An error has occurred." 52 | } 53 | 54 | .darker-border-checkbox.form-check-input { 55 | border-color: #929292; 56 | } 57 | 58 | .form-floating > .form-control-plaintext::placeholder, .form-floating > .form-control::placeholder { 59 | color: var(--bs-secondary-color); 60 | text-align: end; 61 | } 62 | 63 | .form-floating > .form-control-plaintext:focus::placeholder, .form-floating > .form-control:focus::placeholder { 64 | text-align: start; 65 | } 66 | 67 | .status-bar-safe-area { 68 | display: none; 69 | } 70 | 71 | @supports (-webkit-touch-callout: none) { 72 | .status-bar-safe-area { 73 | display: flex; 74 | position: sticky; 75 | top: 0; 76 | height: env(safe-area-inset-top); 77 | background-color: #f7f7f7; 78 | width: 100%; 79 | z-index: 1; 80 | } 81 | 82 | .flex-column, .navbar-brand { 83 | padding-left: env(safe-area-inset-left); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Blazor.Maui.PhotoSlideshow.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net10.0-android;net10.0-ios;net10.0-maccatalyst 5 | $(TargetFrameworks);net10.0-windows10.0.19041.0 6 | 7 | 12 | 13 | 14 | Exe 15 | Blazor.Maui.PhotoSlideshow 16 | true 17 | true 18 | enable 19 | false 20 | enable 21 | 22 | 23 | Blazor.Maui.PhotoSlideshow 24 | 25 | 26 | com.companyname.blazor.maui.photoslideshow 27 | 28 | 29 | 1.0 30 | 1 31 | 32 | 33 | None 34 | 35 | 15.0 36 | 15.0 37 | 24.0 38 | 10.0.17763.0 39 | 10.0.17763.0 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Services/ImageConverterService.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Concurrent; 2 | 3 | namespace Blazor.Maui.PhotoSlideshow.Services; 4 | 5 | public class ImageConverterService 6 | { 7 | private readonly ConcurrentDictionary _base64Cache = new(); 8 | private readonly ConcurrentDictionary> _pendingConversions = new(); 9 | 10 | // OPTIMISÉ: Limite de cache pour éviter l'explosion mémoire 11 | private const int MAX_CACHE_SIZE = 200; // Limite à 200 images en cache 12 | private readonly Queue _cacheKeys = new(); 13 | private readonly object _cacheLock = new(); 14 | 15 | /// 16 | /// Convertit de manière ASYNCHRONE pour éviter de bloquer le thread UI 17 | /// OPTIMISÉ: Avec limite de cache pour éviter OOM 18 | /// 19 | public async Task ConvertToBase64Async(string imagePath) 20 | { 21 | if (string.IsNullOrEmpty(imagePath)) 22 | return string.Empty; 23 | 24 | // Retourner du cache si disponible 25 | if (_base64Cache.TryGetValue(imagePath, out var cached)) 26 | return cached; 27 | 28 | // Si une conversion est déjà en cours, attendre le résultat 29 | if (_pendingConversions.TryGetValue(imagePath, out var pendingTask)) 30 | return await pendingTask; 31 | 32 | // Créer une nouvelle tâche de conversion 33 | var conversionTask = Task.Run(async () => 34 | { 35 | try 36 | { 37 | if (!File.Exists(imagePath)) 38 | return string.Empty; 39 | 40 | // Lecture asynchrone pour ne pas bloquer 41 | var bytes = await File.ReadAllBytesAsync(imagePath); 42 | var base64 = Convert.ToBase64String(bytes); 43 | var ext = Path.GetExtension(imagePath).ToLower(); 44 | 45 | var mimeType = ext switch 46 | { 47 | ".jpg" or ".jpeg" => "image/jpeg", 48 | ".png" => "image/png", 49 | ".gif" => "image/gif", 50 | ".bmp" => "image/bmp", 51 | _ => "image/jpeg" 52 | }; 53 | 54 | var result = $"data:{mimeType};base64,{base64}"; 55 | 56 | // OPTIMISÉ: Mettre en cache avec limite LRU (Least Recently Used) 57 | AddToCache(imagePath, result); 58 | 59 | return result; 60 | } 61 | catch (Exception ex) 62 | { 63 | Console.WriteLine($"Erreur conversion image {Path.GetFileName(imagePath)}: {ex.Message}"); 64 | return string.Empty; 65 | } 66 | finally 67 | { 68 | // Nettoyer la tâche en attente 69 | _pendingConversions.TryRemove(imagePath, out _); 70 | } 71 | }); 72 | 73 | // Enregistrer la tâche en cours 74 | _pendingConversions.TryAdd(imagePath, conversionTask); 75 | 76 | return await conversionTask; 77 | } 78 | 79 | /// 80 | /// OPTIMISÉ: Ajoute au cache avec politique LRU pour éviter l'explosion mémoire 81 | /// 82 | private void AddToCache(string key, string value) 83 | { 84 | lock (_cacheLock) 85 | { 86 | // Si le cache est plein, supprimer le plus ancien 87 | if (_base64Cache.Count >= MAX_CACHE_SIZE && !_base64Cache.ContainsKey(key)) 88 | { 89 | if (_cacheKeys.TryDequeue(out var oldestKey)) 90 | { 91 | _base64Cache.TryRemove(oldestKey, out _); 92 | Console.WriteLine($"Cache LRU: Suppression de {Path.GetFileName(oldestKey)}"); 93 | } 94 | } 95 | 96 | // Ajouter la nouvelle entrée 97 | if (_base64Cache.TryAdd(key, value)) 98 | { 99 | _cacheKeys.Enqueue(key); 100 | } 101 | } 102 | } 103 | 104 | public void ClearCache() 105 | { 106 | lock (_cacheLock) 107 | { 108 | _base64Cache.Clear(); 109 | _pendingConversions.Clear(); 110 | _cacheKeys.Clear(); 111 | 112 | // Forcer la collecte garbage pour libérer la mémoire 113 | GC.Collect(); 114 | GC.WaitForPendingFinalizers(); 115 | GC.Collect(); 116 | } 117 | } 118 | 119 | /// 120 | /// Précharge une image dans le cache de manière asynchrone 121 | /// 122 | public Task PreloadImageAsync(string imagePath) 123 | { 124 | return ConvertToBase64Async(imagePath); 125 | } 126 | 127 | /// 128 | /// NOUVEAU: Obtenir les statistiques du cache 129 | /// 130 | public (int count, int pending) GetCacheStats() 131 | { 132 | return (_base64Cache.Count, _pendingConversions.Count); 133 | } 134 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Services/ThumbnailService.cs: -------------------------------------------------------------------------------- 1 | //using Android.Graphics; 2 | //using static Android.Graphics.ImageDecoder; 3 | using SkiaSharp; 4 | 5 | namespace Blazor.Maui.PhotoSlideshow.Services; 6 | 7 | public class ThumbnailService 8 | { 9 | // OPTIMISÉ: Réduit de 300px → 200px pour moins de CPU/mémoire 10 | private const int ThumbnailHeight = 200; 11 | // OPTIMISÉ: Réduit de 75 → 60 pour fichiers plus petits 12 | private const int ThumbnailQuality = 60; 13 | 14 | /// 15 | /// Crée une miniature optimisée pour l'affichage en mosaïque 16 | /// OPTIMISÉ: Décodage direct à la taille cible + orientation simplifiée 17 | /// 18 | public async Task CreateThumbnailAsync(string sourceImagePath, string thumbnailPath) 19 | { 20 | try 21 | { 22 | if (File.Exists(thumbnailPath)) 23 | return thumbnailPath; 24 | 25 | await using var sourceStream = File.OpenRead(sourceImagePath); 26 | using var codec = SKCodec.Create(sourceStream); 27 | 28 | if (codec == null) 29 | return null; 30 | 31 | var origin = codec.EncodedOrigin; 32 | 33 | // OPTIMISÉ: Calculer la taille cible AVANT le décodage 34 | var originalWidth = codec.Info.Width; 35 | var originalHeight = codec.Info.Height; 36 | 37 | // Ajuster pour l'orientation 38 | if (origin.IsRotate90or270()) 39 | { 40 | (originalWidth, originalHeight) = (originalHeight, originalWidth); 41 | } 42 | 43 | var (targetWidth, targetHeight) = CalculateThumbnailSize(originalWidth, originalHeight); 44 | 45 | // OPTIMISÉ: Décoder directement à une taille réduite (plus rapide que decode puis resize) 46 | // Utiliser le sous-échantillonnage pour décoder moins de pixels 47 | var sampleSize = CalculateSampleSize(codec.Info.Width, codec.Info.Height, targetWidth, targetHeight); 48 | 49 | var bitmap = SKBitmap.Decode(codec, new SKImageInfo( 50 | codec.Info.Width / sampleSize, 51 | codec.Info.Height / sampleSize, 52 | SKColorType.Rgba8888 53 | )); 54 | 55 | if (bitmap == null) 56 | return null; 57 | 58 | // Appliquer l'orientation si nécessaire 59 | using var orientedBitmap = origin != SKEncodedOrigin.TopLeft 60 | ? ApplyOrientationOptimized(bitmap, origin) 61 | : bitmap; 62 | 63 | // Resize final à la taille exacte souhaitée (depuis une taille déjà réduite) 64 | using var resizedBitmap = orientedBitmap.Resize( 65 | new SKImageInfo(targetWidth, targetHeight), 66 | SKFilterQuality.Low // OPTIMISÉ: Low au lieu de Medium (plus rapide) 67 | ); 68 | 69 | if (resizedBitmap == null) 70 | return null; 71 | 72 | using var image = SKImage.FromBitmap(resizedBitmap); 73 | using var data = image.Encode(SKEncodedImageFormat.Jpeg, ThumbnailQuality); 74 | 75 | await using var outputStream = File.OpenWrite(thumbnailPath); 76 | data.SaveTo(outputStream); 77 | 78 | // Cleanup du bitmap original si différent de orientedBitmap 79 | if (origin == SKEncodedOrigin.TopLeft) 80 | bitmap.Dispose(); 81 | 82 | return thumbnailPath; 83 | } 84 | catch (Exception ex) 85 | { 86 | Console.WriteLine($"Erreur création miniature: {ex.Message}"); 87 | return null; 88 | } 89 | } 90 | 91 | /// 92 | /// OPTIMISÉ: Calcule le facteur de sous-échantillonnage pour décoder moins de pixels 93 | /// 94 | private int CalculateSampleSize(int sourceWidth, int sourceHeight, int targetWidth, int targetHeight) 95 | { 96 | int sampleSize = 1; 97 | 98 | // Trouver la plus grande puissance de 2 qui garde l'image >= taille cible 99 | while (sourceWidth / (sampleSize * 2) >= targetWidth && 100 | sourceHeight / (sampleSize * 2) >= targetHeight) 101 | { 102 | sampleSize *= 2; 103 | } 104 | 105 | return sampleSize; 106 | } 107 | 108 | /// 109 | /// OPTIMISÉ: Version simplifiée de l'orientation (moins de transformations) 110 | /// 111 | private SKBitmap ApplyOrientationOptimized(SKBitmap bitmap, SKEncodedOrigin origin) 112 | { 113 | // Pour les orientations simples, on peut éviter certaines transformations 114 | if (origin == SKEncodedOrigin.TopLeft) 115 | return bitmap; 116 | 117 | var surface = SKSurface.Create(new SKImageInfo( 118 | origin.IsRotate90or270() ? bitmap.Height : bitmap.Width, 119 | origin.IsRotate90or270() ? bitmap.Width : bitmap.Height 120 | )); 121 | 122 | using (var canvas = surface.Canvas) 123 | { 124 | canvas.Clear(SKColors.Transparent); 125 | 126 | // Appliquer uniquement les transformations essentielles 127 | switch (origin) 128 | { 129 | case SKEncodedOrigin.TopRight: 130 | canvas.Scale(-1, 1, bitmap.Width / 2f, 0); 131 | break; 132 | case SKEncodedOrigin.BottomRight: 133 | canvas.RotateDegrees(180, bitmap.Width / 2f, bitmap.Height / 2f); 134 | break; 135 | case SKEncodedOrigin.BottomLeft: 136 | canvas.Scale(1, -1, 0, bitmap.Height / 2f); 137 | break; 138 | case SKEncodedOrigin.RightTop: 139 | canvas.Translate(bitmap.Height, 0); 140 | canvas.RotateDegrees(90); 141 | break; 142 | case SKEncodedOrigin.LeftBottom: 143 | canvas.Translate(0, bitmap.Width); 144 | canvas.RotateDegrees(-90); 145 | break; 146 | // OPTIMISÉ: Orientations moins courantes simplifiées 147 | case SKEncodedOrigin.LeftTop: 148 | case SKEncodedOrigin.RightBottom: 149 | // Fallback: rotation simple 150 | canvas.Translate(0, bitmap.Width); 151 | canvas.RotateDegrees(-90); 152 | break; 153 | } 154 | 155 | canvas.DrawBitmap(bitmap, 0, 0); 156 | } 157 | 158 | return SKBitmap.FromImage(surface.Snapshot()); 159 | } 160 | 161 | private (int width, int height) CalculateThumbnailSize(int originalWidth, int originalHeight) 162 | { 163 | var ratio = (double)originalWidth / originalHeight; 164 | var width = (int)(ThumbnailHeight * ratio); 165 | return (width, ThumbnailHeight); 166 | } 167 | } 168 | 169 | internal static class SKEncodedOriginExtensions 170 | { 171 | public static bool IsRotate90or270(this SKEncodedOrigin origin) 172 | { 173 | return origin is SKEncodedOrigin.LeftTop 174 | or SKEncodedOrigin.RightTop 175 | or SKEncodedOrigin.RightBottom 176 | or SKEncodedOrigin.LeftBottom; 177 | } 178 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Components/Pages/Home.razor.cs: -------------------------------------------------------------------------------- 1 | using Blazor.Maui.PhotoSlideshow.Services; 2 | using Microsoft.AspNetCore.Components; 3 | using Blazor.Maui.PhotoSlideshow.Models; 4 | 5 | namespace Blazor.Maui.PhotoSlideshow.Components.Pages; 6 | 7 | public partial class Home : IDisposable 8 | { 9 | [Inject] private SlideshowService SlideshowService { get; set; } = default!; 10 | [Inject] private ImageCacheService ImageCacheService { get; set; } = default!; 11 | [Inject] private ImageConverterService ImageConverter { get; set; } = default!; 12 | 13 | private bool _isRunning = false; 14 | private bool _showSettings = false; 15 | private string _networkFolderInput = string.Empty; 16 | private List _currentImages = new(); 17 | private Dictionary _imageSourceCache = new(); 18 | private string? _fullscreenImageBase64 = null; 19 | private bool _isFullscreenExiting = false; 20 | 21 | // Compteur pour debouncing des rafraîchissements UI 22 | private int _imageUpdateCounter = 0; 23 | private const int UI_UPDATE_BATCH_SIZE = 20; 24 | private (int count, int pending) _cacheStats = (0, 0); 25 | 26 | protected override async Task OnInitializedAsync() 27 | { 28 | _networkFolderInput = ImageCacheService.NetworkFolder; 29 | 30 | SlideshowService.OnImagesChanged += OnImagesChanged; 31 | SlideshowService.OnFullScreenChanged += OnFullScreenChanged; 32 | 33 | await SlideshowService.InitializeAsync(); 34 | UpdateImageSnapshot(); 35 | 36 | // Précharger les premières images visibles en arrière-plan 37 | _ = PreloadVisibleImagesAsync(); 38 | 39 | // Démarrer l'animation automatiquement après un court délai 40 | await Task.Delay(1000); 41 | if (_currentImages.Any() && !_isRunning) 42 | { 43 | ToggleAnimation(); 44 | } 45 | 46 | // Timer pour mettre à jour les stats du cache 47 | _ = UpdateCacheStatsLoop(); 48 | } 49 | 50 | /// 51 | /// Obtenir la source de l'image (Base64) avec chargement progressif 52 | /// 53 | private string GetImageSource(string imagePath) 54 | { 55 | // Si déjà en cache local, retourner immédiatement 56 | if (_imageSourceCache.TryGetValue(imagePath, out var source)) 57 | return source; 58 | 59 | // Retourner un placeholder et charger en arrière-plan 60 | _ = LoadImageSourceAsync(imagePath); 61 | 62 | return "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'%3E%3Crect fill='%232a2a2a' width='100' height='100'/%3E%3C/svg%3E"; 63 | } 64 | 65 | /// 66 | /// Charger l'image de manière asynchrone avec cache local 67 | /// 68 | private async Task LoadImageSourceAsync(string imagePath) 69 | { 70 | try 71 | { 72 | var source = await ImageConverter.ConvertToBase64Async(imagePath); 73 | _imageSourceCache[imagePath] = source; 74 | 75 | // Rafraîchir l'UI uniquement si nécessaire 76 | await InvokeAsync(StateHasChanged); 77 | } 78 | catch (Exception ex) 79 | { 80 | Console.WriteLine($"Erreur chargement image: {ex.Message}"); 81 | } 82 | } 83 | 84 | /// 85 | /// Précharger uniquement les images visibles 86 | /// 87 | private async Task PreloadVisibleImagesAsync() 88 | { 89 | // Limiter le préchargement aux 50 premières images pour éviter la surcharge 90 | var random = new Random(); 91 | var imagesToPreload = _currentImages 92 | .Take(50) 93 | .OrderBy(_ => random.Next()) 94 | .Where(img => !string.IsNullOrEmpty(img.CachedPath)) 95 | .Select(img => img.CachedPath!) 96 | .ToList(); 97 | 98 | // Précharger par lots de 10 pour ne pas surcharger 99 | foreach (var batch in imagesToPreload.Chunk(10)) 100 | { 101 | var tasks = batch.Select(path => LoadImageSourceAsync(path)); 102 | await Task.WhenAll(tasks); 103 | await Task.Delay(100); // Petit délai entre les lots 104 | } 105 | } 106 | 107 | /// 108 | /// Mise à jour périodique des stats du cache 109 | /// 110 | private async Task UpdateCacheStatsLoop() 111 | { 112 | while (!_isDisposed) 113 | { 114 | _cacheStats = ImageConverter.GetCacheStats(); 115 | await Task.Delay(2000); 116 | } 117 | } 118 | 119 | private bool _isDisposed = false; 120 | 121 | /// 122 | /// Debouncing - rafraîchir UI tous les 20 images au lieu de chaque fois 123 | /// 124 | private void OnImagesChanged() 125 | { 126 | _imageUpdateCounter++; 127 | 128 | // Rafraîchir uniquement tous les N images OU quand le chargement est terminé 129 | if (_imageUpdateCounter % UI_UPDATE_BATCH_SIZE == 0 || SlideshowService.IsLoadingComplete) 130 | { 131 | InvokeAsync(() => 132 | { 133 | UpdateImageSnapshot(); 134 | 135 | // Réinitialiser l'image plein écran si fermée 136 | var hasFullscreen = _currentImages.Any(img => img.IsFullScreen); 137 | if (!hasFullscreen) 138 | { 139 | _fullscreenImageBase64 = null; 140 | } 141 | 142 | StateHasChanged(); 143 | 144 | // Précharger les nouvelles images 145 | _ = PreloadVisibleImagesAsync(); 146 | }); 147 | } 148 | else 149 | { 150 | // Mise à jour silencieuse sans StateHasChanged() 151 | UpdateImageSnapshot(); 152 | } 153 | } 154 | 155 | private void OnFullScreenChanged(int index) 156 | { 157 | InvokeAsync(async () => 158 | { 159 | // NOUVEAU: Si une image plein écran existe déjà, déclencher l'animation de sortie 160 | var previousFullscreenImage = _currentImages.FirstOrDefault(img => img.IsFullScreen); 161 | if (previousFullscreenImage != null && _fullscreenImageBase64 != null) 162 | { 163 | // Ajouter une classe CSS pour l'animation de sortie 164 | _isFullscreenExiting = true; 165 | StateHasChanged(); 166 | 167 | // Attendre la fin de l'animation de sortie 168 | await Task.Delay(800); // Durée de l'animation CSS 169 | } 170 | 171 | _isFullscreenExiting = false; 172 | UpdateImageSnapshot(); 173 | 174 | // Charger l'image plein écran AVANT de rafraîchir l'UI 175 | var fullscreenImage = _currentImages.FirstOrDefault(img => img.IsFullScreen); 176 | if (fullscreenImage?.FullscreenPath != null) 177 | { 178 | Console.WriteLine($"🔄 Chargement image plein écran: {Path.GetFileName(fullscreenImage.FullscreenPath)}"); 179 | 180 | _fullscreenImageBase64 = null; // Réinitialiser 181 | //StateHasChanged(); // Afficher "Chargement..." 182 | 183 | // Charger l'image 184 | _fullscreenImageBase64 = await ImageConverter.ConvertToBase64Async(fullscreenImage.FullscreenPath); 185 | 186 | if (string.IsNullOrEmpty(_fullscreenImageBase64)) 187 | { 188 | Console.WriteLine($"❌ Échec chargement image plein écran"); 189 | } 190 | else 191 | { 192 | Console.WriteLine($"✅ Image plein écran chargée ({_fullscreenImageBase64.Length} caractères)"); 193 | } 194 | } 195 | else 196 | { 197 | _fullscreenImageBase64 = null; 198 | } 199 | 200 | StateHasChanged(); 201 | }); 202 | } 203 | 204 | private void UpdateImageSnapshot() 205 | { 206 | _currentImages = SlideshowService.Images.ToList(); 207 | } 208 | 209 | private void ToggleAnimation() 210 | { 211 | if (_isRunning) 212 | { 213 | SlideshowService.StopAnimation(); 214 | } 215 | else 216 | { 217 | SlideshowService.StartAnimation(); 218 | } 219 | _isRunning = !_isRunning; 220 | } 221 | 222 | private void ToggleSettings() 223 | { 224 | _showSettings = !_showSettings; 225 | if (_showSettings) 226 | { 227 | _networkFolderInput = ImageCacheService.NetworkFolder; 228 | } 229 | } 230 | 231 | private async Task SaveSettings() 232 | { 233 | if (!string.IsNullOrWhiteSpace(_networkFolderInput)) 234 | { 235 | ImageCacheService.NetworkFolder = _networkFolderInput; 236 | _showSettings = false; 237 | await ClearCacheAndReload(); 238 | } 239 | } 240 | 241 | private async Task ClearCacheAndReload() 242 | { 243 | SlideshowService.StopAnimation(); 244 | _isRunning = false; 245 | ImageConverter.ClearCache(); 246 | _imageSourceCache.Clear(); 247 | _fullscreenImageBase64 = null; 248 | _imageUpdateCounter = 0; 249 | 250 | await SlideshowService.InitializeAsync(); 251 | UpdateImageSnapshot(); 252 | StateHasChanged(); 253 | } 254 | 255 | public void Dispose() 256 | { 257 | _isDisposed = true; 258 | SlideshowService.OnImagesChanged -= OnImagesChanged; 259 | SlideshowService.OnFullScreenChanged -= OnFullScreenChanged; 260 | SlideshowService.StopAnimation(); 261 | _imageSourceCache.Clear(); 262 | _fullscreenImageBase64 = null; 263 | ImageConverter.ClearCache(); 264 | } 265 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from `dotnet new gitignore` 5 | 6 | # dotenv files 7 | .env 8 | 9 | # User-specific files 10 | *.rsuser 11 | *.suo 12 | *.user 13 | *.userosscache 14 | *.sln.docstates 15 | 16 | # User-specific files (MonoDevelop/Xamarin Studio) 17 | *.userprefs 18 | 19 | # Mono auto generated files 20 | mono_crash.* 21 | 22 | # Build results 23 | [Dd]ebug/ 24 | [Dd]ebugPublic/ 25 | [Rr]elease/ 26 | [Rr]eleases/ 27 | x64/ 28 | x86/ 29 | [Ww][Ii][Nn]32/ 30 | [Aa][Rr][Mm]/ 31 | [Aa][Rr][Mm]64/ 32 | bld/ 33 | [Bb]in/ 34 | [Oo]bj/ 35 | [Ll]og/ 36 | [Ll]ogs/ 37 | 38 | # Visual Studio 2015/2017 cache/options directory 39 | .vs/ 40 | # Uncomment if you have tasks that create the project's static files in wwwroot 41 | #wwwroot/ 42 | 43 | # Visual Studio 2017 auto generated files 44 | Generated\ Files/ 45 | 46 | # MSTest test Results 47 | [Tt]est[Rr]esult*/ 48 | [Bb]uild[Ll]og.* 49 | 50 | # NUnit 51 | *.VisualState.xml 52 | TestResult.xml 53 | nunit-*.xml 54 | 55 | # Build Results of an ATL Project 56 | [Dd]ebugPS/ 57 | [Rr]eleasePS/ 58 | dlldata.c 59 | 60 | # Benchmark Results 61 | BenchmarkDotNet.Artifacts/ 62 | 63 | # .NET 64 | project.lock.json 65 | project.fragment.lock.json 66 | artifacts/ 67 | 68 | # Tye 69 | .tye/ 70 | 71 | # ASP.NET Scaffolding 72 | ScaffoldingReadMe.txt 73 | 74 | # StyleCop 75 | StyleCopReport.xml 76 | 77 | # Files built by Visual Studio 78 | *_i.c 79 | *_p.c 80 | *_h.h 81 | *.ilk 82 | *.meta 83 | *.obj 84 | *.iobj 85 | *.pch 86 | *.pdb 87 | *.ipdb 88 | *.pgc 89 | *.pgd 90 | *.rsp 91 | *.sbr 92 | *.tlb 93 | *.tli 94 | *.tlh 95 | *.tmp 96 | *.tmp_proj 97 | *_wpftmp.csproj 98 | *.log 99 | *.tlog 100 | *.vspscc 101 | *.vssscc 102 | .builds 103 | *.pidb 104 | *.svclog 105 | *.scc 106 | 107 | # Chutzpah Test files 108 | _Chutzpah* 109 | 110 | # Visual C++ cache files 111 | ipch/ 112 | *.aps 113 | *.ncb 114 | *.opendb 115 | *.opensdf 116 | *.sdf 117 | *.cachefile 118 | *.VC.db 119 | *.VC.VC.opendb 120 | 121 | # Visual Studio profiler 122 | *.psess 123 | *.vsp 124 | *.vspx 125 | *.sap 126 | 127 | # Visual Studio Trace Files 128 | *.e2e 129 | 130 | # TFS 2012 Local Workspace 131 | $tf/ 132 | 133 | # Guidance Automation Toolkit 134 | *.gpState 135 | 136 | # ReSharper is a .NET coding add-in 137 | _ReSharper*/ 138 | *.[Rr]e[Ss]harper 139 | *.DotSettings.user 140 | 141 | # TeamCity is a build add-in 142 | _TeamCity* 143 | 144 | # DotCover is a Code Coverage Tool 145 | *.dotCover 146 | 147 | # AxoCover is a Code Coverage Tool 148 | .axoCover/* 149 | !.axoCover/settings.json 150 | 151 | # Coverlet is a free, cross platform Code Coverage Tool 152 | coverage*.json 153 | coverage*.xml 154 | coverage*.info 155 | 156 | # Visual Studio code coverage results 157 | *.coverage 158 | *.coveragexml 159 | 160 | # NCrunch 161 | _NCrunch_* 162 | .*crunch*.local.xml 163 | nCrunchTemp_* 164 | 165 | # MightyMoose 166 | *.mm.* 167 | AutoTest.Net/ 168 | 169 | # Web workbench (sass) 170 | .sass-cache/ 171 | 172 | # Installshield output folder 173 | [Ee]xpress/ 174 | 175 | # DocProject is a documentation generator add-in 176 | DocProject/buildhelp/ 177 | DocProject/Help/*.HxT 178 | DocProject/Help/*.HxC 179 | DocProject/Help/*.hhc 180 | DocProject/Help/*.hhk 181 | DocProject/Help/*.hhp 182 | DocProject/Help/Html2 183 | DocProject/Help/html 184 | 185 | # Click-Once directory 186 | publish/ 187 | 188 | # Publish Web Output 189 | *.[Pp]ublish.xml 190 | *.azurePubxml 191 | # Note: Comment the next line if you want to checkin your web deploy settings, 192 | # but database connection strings (with potential passwords) will be unencrypted 193 | *.pubxml 194 | *.publishproj 195 | 196 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 197 | # checkin your Azure Web App publish settings, but sensitive information contained 198 | # in these scripts will be unencrypted 199 | PublishScripts/ 200 | 201 | # NuGet Packages 202 | *.nupkg 203 | # NuGet Symbol Packages 204 | *.snupkg 205 | # The packages folder can be ignored because of Package Restore 206 | **/[Pp]ackages/* 207 | # except build/, which is used as an MSBuild target. 208 | !**/[Pp]ackages/build/ 209 | # Uncomment if necessary however generally it will be regenerated when needed 210 | #!**/[Pp]ackages/repositories.config 211 | # NuGet v3's project.json files produces more ignorable files 212 | *.nuget.props 213 | *.nuget.targets 214 | 215 | # Microsoft Azure Build Output 216 | csx/ 217 | *.build.csdef 218 | 219 | # Microsoft Azure Emulator 220 | ecf/ 221 | rcf/ 222 | 223 | # Windows Store app package directories and files 224 | AppPackages/ 225 | BundleArtifacts/ 226 | Package.StoreAssociation.xml 227 | _pkginfo.txt 228 | *.appx 229 | *.appxbundle 230 | *.appxupload 231 | 232 | # Visual Studio cache files 233 | # files ending in .cache can be ignored 234 | *.[Cc]ache 235 | # but keep track of directories ending in .cache 236 | !?*.[Cc]ache/ 237 | 238 | # Others 239 | ClientBin/ 240 | ~$* 241 | *~ 242 | *.dbmdl 243 | *.dbproj.schemaview 244 | *.jfm 245 | *.pfx 246 | *.publishsettings 247 | orleans.codegen.cs 248 | 249 | # Including strong name files can present a security risk 250 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 251 | #*.snk 252 | 253 | # Since there are multiple workflows, uncomment next line to ignore bower_components 254 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 255 | #bower_components/ 256 | 257 | # RIA/Silverlight projects 258 | Generated_Code/ 259 | 260 | # Backup & report files from converting an old project file 261 | # to a newer Visual Studio version. Backup files are not needed, 262 | # because we have git ;-) 263 | _UpgradeReport_Files/ 264 | Backup*/ 265 | UpgradeLog*.XML 266 | UpgradeLog*.htm 267 | ServiceFabricBackup/ 268 | *.rptproj.bak 269 | 270 | # SQL Server files 271 | *.mdf 272 | *.ldf 273 | *.ndf 274 | 275 | # Business Intelligence projects 276 | *.rdl.data 277 | *.bim.layout 278 | *.bim_*.settings 279 | *.rptproj.rsuser 280 | *- [Bb]ackup.rdl 281 | *- [Bb]ackup ([0-9]).rdl 282 | *- [Bb]ackup ([0-9][0-9]).rdl 283 | 284 | # Microsoft Fakes 285 | FakesAssemblies/ 286 | 287 | # GhostDoc plugin setting file 288 | *.GhostDoc.xml 289 | 290 | # Node.js Tools for Visual Studio 291 | .ntvs_analysis.dat 292 | node_modules/ 293 | 294 | # Visual Studio 6 build log 295 | *.plg 296 | 297 | # Visual Studio 6 workspace options file 298 | *.opt 299 | 300 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 301 | *.vbw 302 | 303 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 304 | *.vbp 305 | 306 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 307 | *.dsw 308 | *.dsp 309 | 310 | # Visual Studio 6 technical files 311 | *.ncb 312 | *.aps 313 | 314 | # Visual Studio LightSwitch build output 315 | **/*.HTMLClient/GeneratedArtifacts 316 | **/*.DesktopClient/GeneratedArtifacts 317 | **/*.DesktopClient/ModelManifest.xml 318 | **/*.Server/GeneratedArtifacts 319 | **/*.Server/ModelManifest.xml 320 | _Pvt_Extensions 321 | 322 | # Paket dependency manager 323 | .paket/paket.exe 324 | paket-files/ 325 | 326 | # FAKE - F# Make 327 | .fake/ 328 | 329 | # CodeRush personal settings 330 | .cr/personal 331 | 332 | # Python Tools for Visual Studio (PTVS) 333 | __pycache__/ 334 | *.pyc 335 | 336 | # Cake - Uncomment if you are using it 337 | # tools/** 338 | # !tools/packages.config 339 | 340 | # Tabs Studio 341 | *.tss 342 | 343 | # Telerik's JustMock configuration file 344 | *.jmconfig 345 | 346 | # BizTalk build output 347 | *.btp.cs 348 | *.btm.cs 349 | *.odx.cs 350 | *.xsd.cs 351 | 352 | # OpenCover UI analysis results 353 | OpenCover/ 354 | 355 | # Azure Stream Analytics local run output 356 | ASALocalRun/ 357 | 358 | # MSBuild Binary and Structured Log 359 | *.binlog 360 | 361 | # NVidia Nsight GPU debugger configuration file 362 | *.nvuser 363 | 364 | # MFractors (Xamarin productivity tool) working folder 365 | .mfractor/ 366 | 367 | # Local History for Visual Studio 368 | .localhistory/ 369 | 370 | # Visual Studio History (VSHistory) files 371 | .vshistory/ 372 | 373 | # BeatPulse healthcheck temp database 374 | healthchecksdb 375 | 376 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 377 | MigrationBackup/ 378 | 379 | # Ionide (cross platform F# VS Code tools) working folder 380 | .ionide/ 381 | 382 | # Fody - auto-generated XML schema 383 | FodyWeavers.xsd 384 | 385 | # VS Code files for those working on multiple tools 386 | .vscode/* 387 | !.vscode/settings.json 388 | !.vscode/tasks.json 389 | !.vscode/launch.json 390 | !.vscode/extensions.json 391 | *.code-workspace 392 | 393 | # Local History for Visual Studio Code 394 | .history/ 395 | 396 | # Windows Installer files from build outputs 397 | *.cab 398 | *.msi 399 | *.msix 400 | *.msm 401 | *.msp 402 | 403 | # JetBrains Rider 404 | *.sln.iml 405 | .idea/ 406 | 407 | ## 408 | ## Visual studio for Mac 409 | ## 410 | 411 | 412 | # globs 413 | Makefile.in 414 | *.userprefs 415 | *.usertasks 416 | config.make 417 | config.status 418 | aclocal.m4 419 | install-sh 420 | autom4te.cache/ 421 | *.tar.gz 422 | tarballs/ 423 | test-results/ 424 | 425 | # Mac bundle stuff 426 | *.dmg 427 | *.app 428 | 429 | # content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore 430 | # General 431 | .DS_Store 432 | .AppleDouble 433 | .LSOverride 434 | 435 | # Icon must end with two \r 436 | Icon 437 | 438 | 439 | # Thumbnails 440 | ._* 441 | 442 | # Files that might appear in the root of a volume 443 | .DocumentRevisions-V100 444 | .fseventsd 445 | .Spotlight-V100 446 | .TemporaryItems 447 | .Trashes 448 | .VolumeIcon.icns 449 | .com.apple.timemachine.donotpresent 450 | 451 | # Directories potentially created on remote AFP share 452 | .AppleDB 453 | .AppleDesktop 454 | Network Trash Folder 455 | Temporary Items 456 | .apdisk 457 | 458 | # content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore 459 | # Windows thumbnail cache files 460 | Thumbs.db 461 | ehthumbs.db 462 | ehthumbs_vista.db 463 | 464 | # Dump file 465 | *.stackdump 466 | 467 | # Folder config file 468 | [Dd]esktop.ini 469 | 470 | # Recycle Bin used on file shares 471 | $RECYCLE.BIN/ 472 | 473 | # Windows Installer files 474 | *.cab 475 | *.msi 476 | *.msix 477 | *.msm 478 | *.msp 479 | 480 | # Windows shortcuts 481 | *.lnk 482 | 483 | # Vim temporary swap files 484 | *.swp 485 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Resources/Images/dotnet_bot.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Services/ImageCacheService.cs: -------------------------------------------------------------------------------- 1 | using System.Security.Cryptography; 2 | using System.Text; 3 | using System.Collections.Concurrent; 4 | using System.Text.Json; 5 | 6 | namespace Blazor.Maui.PhotoSlideshow.Services; 7 | 8 | public class ImageCacheService 9 | { 10 | private const string NetworkFolderKey = "NetworkFolderPath"; 11 | private const string DefaultNetworkFolder = ""; 12 | private const string ImageListCacheFile = "image_list_cache.json"; 13 | 14 | private readonly string _thumbnailsFolder; 15 | private readonly string _imageListCachePath; 16 | private readonly SemaphoreSlim _cacheLock = new(10, 10); 17 | private readonly ThumbnailService _thumbnailService; 18 | private Task>? _imageLoadingTask; 19 | private readonly ConcurrentBag _discoveredImages = new(); 20 | private FileSystemWatcher? _folderWatcher; 21 | 22 | public event Action? OnImagesDiscovered; 23 | public event Action? OnNewImageDetected; 24 | 25 | public string NetworkFolder 26 | { 27 | get => Preferences.Default.Get(NetworkFolderKey, DefaultNetworkFolder); 28 | set 29 | { 30 | Preferences.Default.Set(NetworkFolderKey, value); 31 | _imageLoadingTask = null; 32 | _discoveredImages.Clear(); 33 | DeleteImageListCache(); 34 | StopFolderWatcher(); 35 | } 36 | } 37 | 38 | public bool IsNetworkFolderConfigured => !string.IsNullOrWhiteSpace(NetworkFolder); 39 | 40 | public ImageCacheService(ThumbnailService thumbnailService) 41 | { 42 | _thumbnailService = thumbnailService; 43 | _thumbnailsFolder = Path.Combine(FileSystem.CacheDirectory, "thumbnails"); 44 | _imageListCachePath = Path.Combine(FileSystem.CacheDirectory, ImageListCacheFile); 45 | 46 | Directory.CreateDirectory(_thumbnailsFolder); 47 | } 48 | 49 | /// 50 | /// Récupère le chemin de la miniature (pour mosaïque) 51 | /// 52 | public async Task GetThumbnailPathAsync(string networkPath) 53 | { 54 | var cacheFileName = GetCacheFileName(networkPath, "_thumb"); 55 | var thumbnailPath = Path.Combine(_thumbnailsFolder, cacheFileName); 56 | 57 | if (File.Exists(thumbnailPath)) 58 | return thumbnailPath; 59 | 60 | return await CreateThumbnailFromNetworkAsync(networkPath, thumbnailPath); 61 | } 62 | 63 | /// 64 | /// Retourne directement le chemin réseau pour l'affichage plein écran 65 | /// Pas de cache - lecture directe depuis le réseau 66 | /// 67 | public Task GetFullSizeImagePathAsync(string networkPath) 68 | { 69 | // Vérifier que le fichier existe 70 | if (!File.Exists(networkPath)) 71 | { 72 | Console.WriteLine($"⚠️ Fichier introuvable: {networkPath}"); 73 | return Task.FromResult(null); 74 | } 75 | 76 | Console.WriteLine($"📥 Lecture directe depuis réseau: {Path.GetFileName(networkPath)}"); 77 | 78 | // Retourner directement le chemin réseau 79 | return Task.FromResult(networkPath); 80 | } 81 | 82 | private async Task CreateThumbnailFromNetworkAsync(string networkPath, string thumbnailPath) 83 | { 84 | await _cacheLock.WaitAsync(); 85 | try 86 | { 87 | if (File.Exists(thumbnailPath)) 88 | return thumbnailPath; 89 | 90 | if (!File.Exists(networkPath)) 91 | return null; 92 | 93 | return await _thumbnailService.CreateThumbnailAsync(networkPath, thumbnailPath); 94 | } 95 | catch (Exception ex) 96 | { 97 | Console.WriteLine($"Erreur création miniature: {ex.Message}"); 98 | return null; 99 | } 100 | finally 101 | { 102 | _cacheLock.Release(); 103 | } 104 | } 105 | 106 | public void StartLoadingImagesInBackground() 107 | { 108 | if (_imageLoadingTask != null) 109 | return; 110 | 111 | _imageLoadingTask = Task.Run(async () => 112 | { 113 | var networkFolder = NetworkFolder; 114 | 115 | if (string.IsNullOrWhiteSpace(networkFolder) || !Directory.Exists(networkFolder)) 116 | return new List(); 117 | 118 | var cachedData = await LoadImageListFromCacheAsync(networkFolder); 119 | if (cachedData != null) 120 | { 121 | Console.WriteLine($"Cache chargé: {cachedData.Images.Count} images"); 122 | 123 | foreach (var image in cachedData.Images) 124 | { 125 | _discoveredImages.Add(image); 126 | } 127 | OnImagesDiscovered?.Invoke(_discoveredImages.Count); 128 | 129 | _ = Task.Run(() => IncrementalScanAsync(networkFolder, cachedData)); 130 | StartFolderWatcher(networkFolder); 131 | 132 | return cachedData.Images; 133 | } 134 | 135 | var images = await ScanNetworkFolderAsync(networkFolder); 136 | await SaveImageListToCacheAsync(networkFolder, images); 137 | StartFolderWatcher(networkFolder); 138 | 139 | return images; 140 | }); 141 | } 142 | 143 | private async Task IncrementalScanAsync(string networkFolder, ImageListCache cachedData) 144 | { 145 | try 146 | { 147 | var lastScanDate = cachedData.LastUpdate; 148 | var newImages = new List(); 149 | 150 | Console.WriteLine($"Scan incrémental depuis {lastScanDate}..."); 151 | 152 | var enumerationOptions = new EnumerationOptions 153 | { 154 | RecurseSubdirectories = true, 155 | IgnoreInaccessible = true, 156 | ReturnSpecialDirectories = false, 157 | BufferSize = 16384 158 | }; 159 | 160 | foreach (var file in Directory.EnumerateFiles(networkFolder, "*.*", enumerationOptions)) 161 | { 162 | if (!IsImageFile(file)) 163 | continue; 164 | 165 | var fileInfo = new FileInfo(file); 166 | if (fileInfo.LastWriteTime > lastScanDate || !cachedData.Images.Contains(file)) 167 | { 168 | if (!_discoveredImages.Contains(file)) 169 | { 170 | newImages.Add(file); 171 | _discoveredImages.Add(file); 172 | OnNewImageDetected?.Invoke(file); 173 | await Task.Delay(1); 174 | } 175 | } 176 | } 177 | 178 | if (newImages.Count > 0) 179 | { 180 | Console.WriteLine($"🆕 {newImages.Count} nouvelles images détectées"); 181 | var allImages = cachedData.Images.Concat(newImages).Distinct().ToList(); 182 | await SaveImageListToCacheAsync(networkFolder, allImages); 183 | OnImagesDiscovered?.Invoke(_discoveredImages.Count); 184 | } 185 | } 186 | catch (Exception ex) 187 | { 188 | Console.WriteLine($"Erreur scan incrémental: {ex.Message}"); 189 | } 190 | } 191 | 192 | private void StartFolderWatcher(string networkFolder) 193 | { 194 | try 195 | { 196 | StopFolderWatcher(); 197 | 198 | _folderWatcher = new FileSystemWatcher(networkFolder) 199 | { 200 | IncludeSubdirectories = true, 201 | NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime, 202 | EnableRaisingEvents = true 203 | }; 204 | 205 | _folderWatcher.Created += async (s, e) => 206 | { 207 | if (IsImageFile(e.FullPath)) 208 | { 209 | await Task.Delay(500); 210 | if (!_discoveredImages.Contains(e.FullPath)) 211 | { 212 | _discoveredImages.Add(e.FullPath); 213 | OnNewImageDetected?.Invoke(e.FullPath); 214 | OnImagesDiscovered?.Invoke(_discoveredImages.Count); 215 | 216 | var allImages = _discoveredImages.ToList(); 217 | await SaveImageListToCacheAsync(networkFolder, allImages); 218 | } 219 | } 220 | }; 221 | 222 | Console.WriteLine("👁️ Surveillance activée"); 223 | } 224 | catch (Exception ex) 225 | { 226 | Console.WriteLine($"⚠️ Impossible de surveiller: {ex.Message}"); 227 | } 228 | } 229 | 230 | private void StopFolderWatcher() 231 | { 232 | if (_folderWatcher != null) 233 | { 234 | _folderWatcher.EnableRaisingEvents = false; 235 | _folderWatcher.Dispose(); 236 | _folderWatcher = null; 237 | } 238 | } 239 | 240 | private async Task> ScanNetworkFolderAsync(string networkFolder) 241 | { 242 | var images = new List(); 243 | 244 | try 245 | { 246 | var enumerationOptions = new EnumerationOptions 247 | { 248 | RecurseSubdirectories = true, 249 | IgnoreInaccessible = true, 250 | ReturnSpecialDirectories = false, 251 | BufferSize = 16384 252 | }; 253 | 254 | int batchCount = 0; 255 | foreach (var file in Directory.EnumerateFiles(networkFolder, "*.*", enumerationOptions)) 256 | { 257 | if (IsImageFile(file)) 258 | { 259 | images.Add(file); 260 | _discoveredImages.Add(file); 261 | batchCount++; 262 | 263 | if (batchCount % 50 == 0) 264 | { 265 | OnImagesDiscovered?.Invoke(_discoveredImages.Count); 266 | await Task.Delay(1); 267 | } 268 | } 269 | } 270 | 271 | OnImagesDiscovered?.Invoke(_discoveredImages.Count); 272 | } 273 | catch (Exception ex) 274 | { 275 | Console.WriteLine($"Erreur chargement: {ex.Message}"); 276 | } 277 | 278 | return images; 279 | } 280 | 281 | private async Task LoadImageListFromCacheAsync(string networkFolder) 282 | { 283 | try 284 | { 285 | if (!File.Exists(_imageListCachePath)) 286 | return null; 287 | 288 | var json = await File.ReadAllTextAsync(_imageListCachePath); 289 | var cache = JsonSerializer.Deserialize(json); 290 | 291 | if (cache?.NetworkFolder != networkFolder) 292 | return null; 293 | 294 | var absoluteImages = cache.Images 295 | .Select(relativePath => Path.Combine(networkFolder, relativePath)) 296 | .ToList(); 297 | 298 | cache.Images = absoluteImages; 299 | 300 | if (cache.Images.Count > 0) 301 | { 302 | var sampleSize = Math.Min(10, cache.Images.Count); 303 | var sample = cache.Images.Take(sampleSize); 304 | if (sample.All(img => !File.Exists(img))) 305 | { 306 | Console.WriteLine("⚠️ Cache invalide"); 307 | return null; 308 | } 309 | } 310 | 311 | return cache; 312 | } 313 | catch (Exception ex) 314 | { 315 | Console.WriteLine($"Erreur lecture cache: {ex.Message}"); 316 | return null; 317 | } 318 | } 319 | 320 | private async Task SaveImageListToCacheAsync(string networkFolder, List images) 321 | { 322 | try 323 | { 324 | var relativeImages = images 325 | .Select(path => Path.GetRelativePath(networkFolder, path)) 326 | .ToList(); 327 | 328 | var cache = new ImageListCache 329 | { 330 | NetworkFolder = networkFolder, 331 | LastUpdate = DateTime.Now, 332 | Images = relativeImages 333 | }; 334 | 335 | var json = JsonSerializer.Serialize(cache, new JsonSerializerOptions { WriteIndented = false }); 336 | 337 | var jsonSizeMb = json.Length / (1024.0 * 1024.0); 338 | Console.WriteLine($"💾 Cache: {images.Count} images, {jsonSizeMb:F2} Mo"); 339 | 340 | await File.WriteAllTextAsync(_imageListCachePath, json); 341 | } 342 | catch (Exception ex) 343 | { 344 | Console.WriteLine($"Erreur sauvegarde: {ex.Message}"); 345 | } 346 | } 347 | 348 | private void DeleteImageListCache() 349 | { 350 | try 351 | { 352 | if (File.Exists(_imageListCachePath)) 353 | File.Delete(_imageListCachePath); 354 | } 355 | catch (Exception ex) 356 | { 357 | Console.WriteLine($"Erreur suppression: {ex.Message}"); 358 | } 359 | } 360 | 361 | public List GetDiscoveredImages() => _discoveredImages.ToList(); 362 | 363 | public async Task> GetAllNetworkImagesAsync() 364 | { 365 | if (_imageLoadingTask == null) 366 | StartLoadingImagesInBackground(); 367 | 368 | return await _imageLoadingTask!; 369 | } 370 | 371 | public bool IsLoadingComplete => _imageLoadingTask?.IsCompleted ?? false; 372 | 373 | public async Task RefreshImageListAsync() 374 | { 375 | StopFolderWatcher(); 376 | _imageLoadingTask = null; 377 | _discoveredImages.Clear(); 378 | DeleteImageListCache(); 379 | StartLoadingImagesInBackground(); 380 | await GetAllNetworkImagesAsync(); 381 | } 382 | 383 | private bool IsImageFile(string path) 384 | { 385 | var ext = Path.GetExtension(path).ToLower(); 386 | return ext is ".jpg" or ".jpeg" or ".png" or ".bmp" or ".gif"; 387 | } 388 | 389 | private string GetCacheFileName(string networkPath, string suffix = "") 390 | { 391 | using var md5 = MD5.Create(); 392 | var hash = md5.ComputeHash(Encoding.UTF8.GetBytes(networkPath)); 393 | var hashString = BitConverter.ToString(hash).Replace("-", "").ToLower(); 394 | return $"{hashString}{suffix}{Path.GetExtension(networkPath)}"; 395 | } 396 | 397 | public void ClearCache() 398 | { 399 | try 400 | { 401 | StopFolderWatcher(); 402 | _discoveredImages.Clear(); 403 | _imageLoadingTask = null; 404 | DeleteImageListCache(); 405 | 406 | if (Directory.Exists(_thumbnailsFolder)) 407 | { 408 | Directory.Delete(_thumbnailsFolder, true); 409 | Directory.CreateDirectory(_thumbnailsFolder); 410 | } 411 | } 412 | catch (Exception ex) 413 | { 414 | Console.WriteLine($"Erreur nettoyage: {ex.Message}"); 415 | } 416 | } 417 | 418 | /// 419 | /// Méthode de compatibilité - retourne les thumbnails 420 | /// 421 | public async Task GetCachedImagePathAsync(string networkPath) 422 | { 423 | return await GetThumbnailPathAsync(networkPath); 424 | } 425 | 426 | private class ImageListCache 427 | { 428 | public string NetworkFolder { get; set; } = string.Empty; 429 | public DateTime LastUpdate { get; set; } 430 | public List Images { get; set; } = new(); 431 | } 432 | } -------------------------------------------------------------------------------- /Blazor.Maui.PhotoSlideshow/Services/SlideshowService.cs: -------------------------------------------------------------------------------- 1 | using Blazor.Maui.PhotoSlideshow.Models; 2 | 3 | namespace Blazor.Maui.PhotoSlideshow.Services; 4 | 5 | public class SlideshowService 6 | { 7 | private readonly ImageCacheService _cacheService; 8 | private List _images = new(); 9 | private List _allNetworkImages = new(); 10 | private Random _random = new(); 11 | private System.Timers.Timer? _cycleTimer; 12 | private System.Timers.Timer? _loadingTimer; 13 | private int _currentFullscreenIndex = -1; 14 | private int _lastProcessedDiscoveredCount = 0; 15 | private bool _isLoadingComplete = false; 16 | private readonly SemaphoreSlim _loadingSemaphore = new(3, 3); 17 | private string? _nextFullscreenImagePath; // Préchargement 18 | private bool _isAnimationRunning = false; 19 | private bool _isShowingFullscreen = false; 20 | private HashSet _displayedImages = new(); // Track des images déjà affichées 21 | 22 | // AUGMENTÉ : Afficher beaucoup de miniatures pour créer un grand mur 23 | private const int MAX_VISIBLE_IMAGES = 150; // Grand mur de miniatures 24 | private const int INITIAL_RANDOM_COUNT = 30; // Nombre d'images aléatoires au démarrage 25 | 26 | public event Action? OnImagesChanged; 27 | public event Action? OnFullScreenChanged; 28 | 29 | public List Images => _images; 30 | public int MosaicDisplayDuration { get; set; } = 5000; // 5 secondes de mosaïque 31 | public int FullscreenDisplayDuration { get; set; } = 3000; // 3 secondes en plein écran 32 | public int TotalImages => _allNetworkImages.Count; 33 | public int LoadedImages => _lastProcessedDiscoveredCount; 34 | public bool IsLoadingComplete => _isLoadingComplete; 35 | public bool IsAnimationRunning => _isAnimationRunning; 36 | 37 | public SlideshowService(ImageCacheService cacheService) 38 | { 39 | _cacheService = cacheService; 40 | _cacheService.OnImagesDiscovered += OnNetworkImagesDiscovered; 41 | } 42 | 43 | public Task InitializeAsync() 44 | { 45 | _cacheService.StartLoadingImagesInBackground(); 46 | StartProgressiveLoading(); 47 | return Task.CompletedTask; 48 | } 49 | 50 | private void OnNetworkImagesDiscovered(int count) 51 | { 52 | _allNetworkImages = _cacheService.GetDiscoveredImages(); 53 | 54 | MainThread.BeginInvokeOnMainThread(() => 55 | { 56 | OnImagesChanged?.Invoke(); 57 | }); 58 | } 59 | 60 | /// 61 | /// Sélectionne des images aléatoires non encore affichées 62 | /// 63 | private List GetRandomUnusedImages(int count) 64 | { 65 | var unusedImages = _allNetworkImages 66 | .Where(path => !_displayedImages.Contains(path)) 67 | .ToList(); 68 | 69 | // Si pas assez d'images non utilisées, réinitialiser 70 | if (unusedImages.Count < count) 71 | { 72 | _displayedImages.Clear(); 73 | unusedImages = _allNetworkImages.ToList(); 74 | Console.WriteLine("🔄 Réinitialisation du pool d'images"); 75 | } 76 | 77 | // Mélanger et prendre les N premières 78 | var shuffled = unusedImages.OrderBy(_ => _random.Next()).Take(count).ToList(); 79 | 80 | // Marquer comme affichées 81 | foreach (var img in shuffled) 82 | { 83 | _displayedImages.Add(img); 84 | } 85 | 86 | return shuffled; 87 | } 88 | 89 | private async Task LoadImageAtIndexAsync(int index) 90 | { 91 | if (index >= _allNetworkImages.Count) 92 | return; 93 | 94 | if (_images.Count >= MAX_VISIBLE_IMAGES) 95 | return; 96 | 97 | await _loadingSemaphore.WaitAsync(); 98 | try 99 | { 100 | var networkPath = _allNetworkImages[index]; 101 | 102 | if (_images.Any(i => i.NetworkPath == networkPath)) 103 | return; 104 | 105 | var item = new ImageItem 106 | { 107 | NetworkPath = networkPath, 108 | Opacity = 1.0 109 | }; 110 | 111 | // Charger la MINIATURE pour la mosaïque (rapide et léger) 112 | item.CachedPath = await _cacheService.GetThumbnailPathAsync(item.NetworkPath); 113 | 114 | if (!string.IsNullOrEmpty(item.CachedPath)) 115 | { 116 | _images.Add(item); 117 | _displayedImages.Add(networkPath); // Marquer comme affichée 118 | } 119 | } 120 | finally 121 | { 122 | _loadingSemaphore.Release(); 123 | } 124 | } 125 | 126 | /// 127 | /// Charge un lot d'images aléatoires 128 | /// 129 | private async Task LoadRandomImagesAsync(List imagePaths) 130 | { 131 | var tasks = imagePaths.Select(async path => 132 | { 133 | if (_images.Count >= MAX_VISIBLE_IMAGES) 134 | return; 135 | 136 | await _loadingSemaphore.WaitAsync(); 137 | try 138 | { 139 | if (_images.Any(i => i.NetworkPath == path)) 140 | return; 141 | 142 | var item = new ImageItem 143 | { 144 | NetworkPath = path, 145 | Opacity = 1.0 146 | }; 147 | 148 | item.CachedPath = await _cacheService.GetThumbnailPathAsync(item.NetworkPath); 149 | 150 | if (!string.IsNullOrEmpty(item.CachedPath)) 151 | { 152 | _images.Add(item); 153 | } 154 | } 155 | finally 156 | { 157 | _loadingSemaphore.Release(); 158 | } 159 | }); 160 | 161 | await Task.WhenAll(tasks); 162 | } 163 | 164 | private void StartProgressiveLoading() 165 | { 166 | _loadingTimer = new System.Timers.Timer(300); 167 | _loadingTimer.Elapsed += async (s, e) => 168 | { 169 | try 170 | { 171 | var discoveredImages = _cacheService.GetDiscoveredImages(); 172 | 173 | if (discoveredImages.Count > 0) 174 | { 175 | _allNetworkImages = discoveredImages; 176 | 177 | // Au tout premier chargement, charger des images aléatoires 178 | if (_images.Count == 0 && _allNetworkImages.Count >= INITIAL_RANDOM_COUNT) 179 | { 180 | Console.WriteLine($"🎲 Chargement initial de {INITIAL_RANDOM_COUNT} images aléatoires"); 181 | var randomImages = GetRandomUnusedImages(INITIAL_RANDOM_COUNT); 182 | await LoadRandomImagesAsync(randomImages); 183 | _lastProcessedDiscoveredCount = 0; // On continuera après avec les suivantes 184 | 185 | await MainThread.InvokeOnMainThreadAsync(() => 186 | { 187 | OnImagesChanged?.Invoke(); 188 | }); 189 | return; 190 | } 191 | } 192 | 193 | if (_images.Count >= MAX_VISIBLE_IMAGES) 194 | { 195 | _isLoadingComplete = true; 196 | _loadingTimer?.Stop(); 197 | 198 | await MainThread.InvokeOnMainThreadAsync(() => 199 | { 200 | OnImagesChanged?.Invoke(); 201 | }); 202 | return; 203 | } 204 | 205 | if (_lastProcessedDiscoveredCount < _allNetworkImages.Count) 206 | { 207 | var remainingSlots = MAX_VISIBLE_IMAGES - _images.Count; 208 | var batchSize = Math.Min(20, remainingSlots); 209 | var imagesToLoadCount = Math.Min(batchSize, _allNetworkImages.Count - _lastProcessedDiscoveredCount); 210 | 211 | var tasks = Enumerable.Range(_lastProcessedDiscoveredCount, imagesToLoadCount) 212 | .Select(i => LoadImageAtIndexAsync(i)) 213 | .ToList(); 214 | 215 | await Task.WhenAll(tasks); 216 | 217 | _lastProcessedDiscoveredCount += imagesToLoadCount; 218 | 219 | await MainThread.InvokeOnMainThreadAsync(() => 220 | { 221 | OnImagesChanged?.Invoke(); 222 | }); 223 | } 224 | 225 | if (_cacheService.IsLoadingComplete && _lastProcessedDiscoveredCount >= _allNetworkImages.Count) 226 | { 227 | _loadingTimer?.Stop(); 228 | _isLoadingComplete = true; 229 | 230 | await MainThread.InvokeOnMainThreadAsync(() => 231 | { 232 | OnImagesChanged?.Invoke(); 233 | }); 234 | } 235 | } 236 | catch (Exception ex) 237 | { 238 | Console.WriteLine($"Erreur chargement progressif: {ex.Message}"); 239 | } 240 | }; 241 | _loadingTimer.Start(); 242 | } 243 | 244 | public void StartAnimation() 245 | { 246 | _isAnimationRunning = true; 247 | _isShowingFullscreen = false; 248 | 249 | // Précharger la première image plein écran 250 | _ = PreloadNextFullscreenImageAsync(); 251 | 252 | // Démarrer le cycle : mosaïque → plein écran → mosaïque... 253 | StartCycleTimer(); 254 | 255 | Console.WriteLine("🚀 Animation démarrée !"); 256 | OnImagesChanged?.Invoke(); 257 | } 258 | 259 | public void StopAnimation() 260 | { 261 | _isAnimationRunning = false; 262 | _cycleTimer?.Stop(); 263 | 264 | // Fermer l'image plein écran si elle est affichée 265 | if (_isShowingFullscreen) 266 | { 267 | HideFullscreen(); 268 | } 269 | 270 | Console.WriteLine("⏸️ Animation arrêtée"); 271 | OnImagesChanged?.Invoke(); 272 | } 273 | 274 | /// 275 | /// Démarre le cycle alternant entre mosaïque et plein écran 276 | /// 277 | private void StartCycleTimer() 278 | { 279 | // Commencer par afficher la mosaïque 280 | _cycleTimer = new System.Timers.Timer(MosaicDisplayDuration); 281 | _cycleTimer.Elapsed += (s, e) => 282 | { 283 | MainThread.BeginInvokeOnMainThread(() => ToggleCycle()); 284 | }; 285 | _cycleTimer.Start(); 286 | } 287 | 288 | /// 289 | /// Bascule entre mosaïque et plein écran 290 | /// 291 | private void ToggleCycle() 292 | { 293 | if (_isShowingFullscreen) 294 | { 295 | // On est en plein écran → fermer et revenir à la mosaïque 296 | HideFullscreen(); 297 | 298 | // Reprogrammer le timer pour la durée de la mosaïque 299 | _cycleTimer?.Stop(); 300 | _cycleTimer = new System.Timers.Timer(MosaicDisplayDuration); 301 | _cycleTimer.Elapsed += (s, e) => MainThread.BeginInvokeOnMainThread(() => ToggleCycle()); 302 | _cycleTimer.Start(); 303 | 304 | Console.WriteLine("📋 Retour à la mosaïque"); 305 | } 306 | else 307 | { 308 | // On est en mosaïque → afficher une image en plein écran 309 | ShowNextFullscreen(); 310 | 311 | // Reprogrammer le timer pour la durée du plein écran 312 | _cycleTimer?.Stop(); 313 | _cycleTimer = new System.Timers.Timer(FullscreenDisplayDuration); 314 | _cycleTimer.Elapsed += (s, e) => MainThread.BeginInvokeOnMainThread(() => ToggleCycle()); 315 | _cycleTimer.Start(); 316 | 317 | Console.WriteLine("🖼️ Affichage plein écran"); 318 | } 319 | } 320 | 321 | /// 322 | /// Affiche une image en plein écran - ATTEND que l'image soit préchargée 323 | /// 324 | private async void ShowNextFullscreen() 325 | { 326 | if (!_images.Any()) 327 | return; 328 | 329 | _isShowingFullscreen = true; 330 | 331 | // Sélectionner une image aléatoire 332 | _currentFullscreenIndex = _random.Next(_images.Count); 333 | var currentImage = _images[_currentFullscreenIndex]; 334 | currentImage.IsFullScreen = true; 335 | 336 | // Utiliser l'image préchargée puis la réinitialiser 337 | string? fullscreenPath = _nextFullscreenImagePath; 338 | 339 | // Si pas préchargée, charger maintenant 340 | if (string.IsNullOrEmpty(fullscreenPath)) 341 | { 342 | Console.WriteLine("⏳ Image plein écran non préchargée, chargement..."); 343 | fullscreenPath = await _cacheService.GetFullSizeImagePathAsync(currentImage.NetworkPath); 344 | } 345 | else 346 | { 347 | // Réinitialiser car on l'a utilisée 348 | _nextFullscreenImagePath = null; 349 | } 350 | 351 | if (!string.IsNullOrEmpty(fullscreenPath)) 352 | { 353 | currentImage.FullscreenPath = fullscreenPath; 354 | Console.WriteLine($"✅ Affichage plein écran: {Path.GetFileName(currentImage.NetworkPath)}"); 355 | 356 | OnFullScreenChanged?.Invoke(_currentFullscreenIndex); 357 | } 358 | else 359 | { 360 | Console.WriteLine($"❌ Impossible de charger l'image plein écran"); 361 | currentImage.IsFullScreen = false; 362 | _isShowingFullscreen = false; 363 | } 364 | 365 | // Précharger la prochaine image pour le prochain cycle 366 | _ = PreloadNextFullscreenImageAsync(); 367 | } 368 | 369 | /// 370 | /// Ferme l'image plein écran et revient à la mosaïque 371 | /// 372 | private void HideFullscreen() 373 | { 374 | if (_currentFullscreenIndex >= 0 && _currentFullscreenIndex < _images.Count) 375 | { 376 | var oldImage = _images[_currentFullscreenIndex]; 377 | oldImage.IsFullScreen = false; 378 | oldImage.FullscreenPath = null; 379 | 380 | Console.WriteLine($"🗑️ Fermeture plein écran: {Path.GetFileName(oldImage.NetworkPath)}"); 381 | 382 | // Remplacer par une image aléatoire non encore affichée 383 | ReplaceImageWithNewOne(_currentFullscreenIndex); 384 | } 385 | 386 | _isShowingFullscreen = false; 387 | OnImagesChanged?.Invoke(); 388 | } 389 | 390 | private async Task PreloadNextFullscreenImageAsync() 391 | { 392 | try 393 | { 394 | if (!_images.Any()) 395 | return; 396 | 397 | var nextIndex = _random.Next(_images.Count); 398 | var nextImage = _images[nextIndex]; 399 | 400 | Console.WriteLine($"🔄 Préchargement plein écran: {Path.GetFileName(nextImage.NetworkPath)}"); 401 | 402 | _nextFullscreenImagePath = await _cacheService.GetFullSizeImagePathAsync(nextImage.NetworkPath); 403 | 404 | if (!string.IsNullOrEmpty(_nextFullscreenImagePath)) 405 | { 406 | Console.WriteLine($"✅ Préchargement réussi: {Path.GetFileName(nextImage.NetworkPath)}"); 407 | } 408 | else 409 | { 410 | Console.WriteLine($"⚠️ Préchargement échoué pour {Path.GetFileName(nextImage.NetworkPath)}"); 411 | } 412 | } 413 | catch (Exception ex) 414 | { 415 | Console.WriteLine($"Erreur préchargement: {ex.Message}"); 416 | _nextFullscreenImagePath = null; 417 | } 418 | } 419 | 420 | private async void ReplaceImageWithNewOne(int indexToReplace) 421 | { 422 | try 423 | { 424 | // Utiliser GetRandomUnusedImages pour éviter les répétitions 425 | var newImages = GetRandomUnusedImages(1); 426 | 427 | if (!newImages.Any()) 428 | { 429 | Console.WriteLine("⚠️ Aucune nouvelle image disponible"); 430 | return; 431 | } 432 | 433 | var newPath = newImages[0]; 434 | 435 | var item = new ImageItem 436 | { 437 | NetworkPath = newPath, 438 | Opacity = 1.0 439 | }; 440 | 441 | item.CachedPath = await _cacheService.GetThumbnailPathAsync(item.NetworkPath); 442 | 443 | if (!string.IsNullOrEmpty(item.CachedPath)) 444 | { 445 | _images[indexToReplace] = item; 446 | Console.WriteLine($"🔄 Miniature remplacée: {Path.GetFileName(newPath)}"); 447 | OnImagesChanged?.Invoke(); 448 | } 449 | } 450 | catch (Exception ex) 451 | { 452 | Console.WriteLine($"Erreur remplacement image: {ex.Message}"); 453 | } 454 | } 455 | 456 | public void Dispose() 457 | { 458 | _cacheService.OnImagesDiscovered -= OnNetworkImagesDiscovered; 459 | _cycleTimer?.Dispose(); 460 | _loadingTimer?.Dispose(); 461 | _loadingSemaphore?.Dispose(); 462 | } 463 | } --------------------------------------------------------------------------------