Skip to content

[housekeeping] Automated PR to fix formatting errors on net10.0 #30149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/BlazorWebView/src/Maui/BlazorWebView.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.Extensions.FileProviders;
using Microsoft.Maui.Controls;
using Microsoft.Maui;
using Microsoft.Maui.Controls;

namespace Microsoft.AspNetCore.Components.WebView.Maui
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
using Microsoft.AspNetCore.Components.WebView.WebView2;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Maui.Platform;
using Microsoft.Web.WebView2.Core;
using Windows.ApplicationModel;
using Windows.Storage.Streams;
using Microsoft.Maui.Platform;
using WebView2Control = Microsoft.UI.Xaml.Controls.WebView2;

namespace Microsoft.AspNetCore.Components.WebView.Maui
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public void StartUrlSchemeTask(WKWebView webView, IWKUrlSchemeTask urlSchemeTask
}

var logger = _webViewHandler.Logger;

logger.LogDebug("Intercepting request for {Url}.", url);

// 1. First check if the app wants to modify or override the request.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
using Microsoft.Maui.MauiBlazorWebView.DeviceTests.Components;
using WebViewAppShared;
using Xunit;

namespace Microsoft.Maui.MauiBlazorWebView.DeviceTests.Elements;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ public Task RequestsCanBeInterceptedAndCancelledForDifferentHosts(string uriBase

// 1. Create the response
e.SetResponse(403, "Forbidden");

// 2. Let the app know we are handling it entirely
e.Handled = true;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public BlazorWebViewTests(ITestOutputHelper output)
{
Output = output;
}

public ITestOutputHelper Output { get; }

sealed class BlazorWebViewWithCustomFiles : BlazorWebView
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ await ExecuteScriptAsync(webView,
}

throw new Exception($"Failed to deserialize result from controlDiv: {result}");

static bool TryDeserialize<TInner>(string? result, out TInner? value)
{
if (result is null or "null" or "undefined")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ await Assert.ThrowsAsync<HybridWebViewInvokeJavaScriptException>(() =>
hybridWebView.InvokeJavaScriptAsync<ResponseObject>(
function,
HybridWebViewTestContext.Default.ResponseObject));

Assert.True(intercepted, "Request was not intercepted");
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ async Task LoadPhotoAsync(FileResult photo)
}

var stream = await photo.OpenReadAsync();

// Get image dimensions
try
{
Expand All @@ -223,7 +223,7 @@ async Task LoadPhotoAsync(FileResult photo)
{
ImageDimensions = $"Unknown dimensions • {stream.Length:N0} bytes";
}

PhotoSource = ImageSource.FromStream(() => stream);
ImageByteLength = stream.Length;

Expand All @@ -247,18 +247,18 @@ async Task LoadPhotoAsync(List<FileResult> photo)
foreach (var item in photo)
{
var stream = await item.OpenReadAsync();

// Get image dimensions
var dimensions = GetImageDimensions(stream);
stream.Position = 0; // Reset stream position for ImageSource

var photoInfo = new PhotoInfo
{
Source = ImageSource.FromStream(() => stream),
Dimensions = $"{dimensions.Width} × {dimensions.Height}",
FileSize = $"{stream.Length:N0} bytes"
};

PhotoList.Add(photoInfo);
ImageByteLength += stream.Length;
}
Expand Down
78 changes: 39 additions & 39 deletions src/Essentials/src/MediaPicker/ImageProcessor.shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,22 @@ namespace Microsoft.Maui.Essentials;
/// </summary>
internal static class ImageProcessor
{
/// <summary>
/// Processes an image by applying resizing and compression using MAUI Graphics.
/// </summary>
/// <param name="inputStream">The input image stream.</param>
/// <param name="maxWidth">Maximum width constraint (null for no constraint).</param>
/// <param name="maxHeight">Maximum height constraint (null for no constraint).</param>
/// <param name="qualityPercent">Compression quality percentage (0-100).</param>
/// <param name="originalFileName">Original filename to determine format preservation logic.</param>
/// <returns>A new stream containing the processed image.</returns>
public static async Task<Stream> ProcessImageAsync(Stream inputStream,
int? maxWidth, int? maxHeight, int qualityPercent, string originalFileName = null)
{
/// <summary>
/// Processes an image by applying resizing and compression using MAUI Graphics.
/// </summary>
/// <param name="inputStream">The input image stream.</param>
/// <param name="maxWidth">Maximum width constraint (null for no constraint).</param>
/// <param name="maxHeight">Maximum height constraint (null for no constraint).</param>
/// <param name="qualityPercent">Compression quality percentage (0-100).</param>
/// <param name="originalFileName">Original filename to determine format preservation logic.</param>
/// <returns>A new stream containing the processed image.</returns>
public static async Task<Stream> ProcessImageAsync(Stream inputStream,
int? maxWidth, int? maxHeight, int qualityPercent, string originalFileName = null)
{
#if !(IOS || ANDROID || WINDOWS)
// For platforms without MAUI Graphics support, return null to indicate no processing available
await Task.CompletedTask; // Avoid async warning
return null;
// For platforms without MAUI Graphics support, return null to indicate no processing available
await Task.CompletedTask; // Avoid async warning
return null;
#else
if (inputStream is null)
{
Expand Down Expand Up @@ -76,7 +76,7 @@ public static async Task<Stream> ProcessImageAsync(Stream inputStream,
image?.Dispose();
}
#endif
}
}

#if IOS || ANDROID || WINDOWS
/// <summary>
Expand Down Expand Up @@ -140,33 +140,33 @@ private static bool ShouldUsePngFormat(string originalFileName, int qualityPerce
}
#endif

/// <summary>
/// Determines if image processing is needed based on the provided options.
/// </summary>
public static bool IsProcessingNeeded(int? maxWidth, int? maxHeight, int qualityPercent)
{
/// <summary>
/// Determines if image processing is needed based on the provided options.
/// </summary>
public static bool IsProcessingNeeded(int? maxWidth, int? maxHeight, int qualityPercent)
{
#if !(IOS || ANDROID || WINDOWS)
// On platforms without MAUI Graphics support, always return false - no processing available
return false;
// On platforms without MAUI Graphics support, always return false - no processing available
return false;
#else
return (maxWidth.HasValue || maxHeight.HasValue) || qualityPercent < 100;
#endif
}

/// <summary>
/// Determines the output file extension based on processed image data and quality settings.
/// </summary>
/// <param name="imageData">The processed image stream to analyze</param>
/// <param name="qualityPercent">Compression quality percentage</param>
/// <param name="originalFileName">Original filename for format hints (optional)</param>
/// <returns>File extension including the dot (e.g., ".jpg", ".png")</returns>
public static string DetermineOutputExtension(Stream imageData, int qualityPercent, string originalFileName = null)
{
}

/// <summary>
/// Determines the output file extension based on processed image data and quality settings.
/// </summary>
/// <param name="imageData">The processed image stream to analyze</param>
/// <param name="qualityPercent">Compression quality percentage</param>
/// <param name="originalFileName">Original filename for format hints (optional)</param>
/// <returns>File extension including the dot (e.g., ".jpg", ".png")</returns>
public static string DetermineOutputExtension(Stream imageData, int qualityPercent, string originalFileName = null)
{
#if !(IOS || ANDROID)
// On platforms without MAUI Graphics support, fall back to simple logic
bool originalWasPng = !string.IsNullOrEmpty(originalFileName) &&
originalFileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
return (qualityPercent >= 95 || originalWasPng) ? ".png" : ".jpg";
// On platforms without MAUI Graphics support, fall back to simple logic
bool originalWasPng = !string.IsNullOrEmpty(originalFileName) &&
originalFileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase);
return (qualityPercent >= 95 || originalWasPng) ? ".png" : ".jpg";
#else
// Try to detect format from the actual processed image data
var detectedFormat = DetectImageFormat(imageData);
Expand All @@ -184,7 +184,7 @@ public static string DetermineOutputExtension(Stream imageData, int qualityPerce
// Otherwise: use JPEG for better compression
return (qualityPercent >= 95 || (qualityPercent >= 90 && originalWasPng)) ? ".png" : ".jpg";
#endif
}
}

#if IOS || ANDROID || WINDOWS
/// <summary>
Expand Down
22 changes: 12 additions & 10 deletions src/Essentials/src/MediaPicker/MediaPicker.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ void OnResult(Intent intent)
}
return new FileResult(path);
}

return null;
}
catch (OperationCanceledException)
Expand All @@ -163,13 +163,13 @@ async Task<FileResult> PickUsingPhotoPicker(MediaPickerOptions options, bool pho
}

var path = FileSystemUtils.EnsurePhysicalPath(androidUri);

// Apply compression/resizing if needed for photos
if (photo && ImageProcessor.IsProcessingNeeded(options?.MaximumWidth, options?.MaximumHeight, options?.CompressionQuality ?? 100))
{
path = await CompressImageIfNeeded(path, options);
}

return new FileResult(path);
}

Expand Down Expand Up @@ -211,13 +211,13 @@ async Task<List<FileResult>> PickMultipleUsingPhotoPicker(MediaPickerOptions opt
if (!uri?.Equals(AndroidUri.Empty) ?? false)
{
var path = FileSystemUtils.EnsurePhysicalPath(uri);

// Apply compression/resizing if needed for photos
if (photo && ImageProcessor.IsProcessingNeeded(options?.MaximumWidth, options?.MaximumHeight, options?.CompressionQuality ?? 100))
{
path = await CompressImageIfNeeded(path, options);
}

resultList.Add(new FileResult(path));
}
}
Expand Down Expand Up @@ -285,10 +285,12 @@ static async Task<string> CompressImageIfNeeded(string imagePath, MediaPickerOpt
await processedStream.CopyToAsync(outputStream);

// Delete original file
try { originalFile.Delete(); } catch { }
try
{ originalFile.Delete(); }
catch { }
return processedPath;
}

// If ImageProcessor returns null (e.g., on .NET Standard), ImageProcessor.IsProcessingNeeded would have returned false,
// so we shouldn't reach this point. Return original path as fallback.
return imagePath;
Expand All @@ -297,7 +299,7 @@ static async Task<string> CompressImageIfNeeded(string imagePath, MediaPickerOpt
{
// If processing fails, return original path
}

return imagePath;
}

Expand Down Expand Up @@ -381,12 +383,12 @@ void OnResult(Intent resultIntent)
{
var tempResultList = resultList.Select(fr => fr.FullPath).ToList();
resultList.Clear();

var compressionTasks = tempResultList.Select(async path =>
{
return await CompressImageIfNeeded(path, options);
});

var compressedPaths = await Task.WhenAll(compressionTasks);
resultList.AddRange(compressedPaths.Select(path => new FileResult(path)));
}
Expand Down
26 changes: 13 additions & 13 deletions src/Essentials/src/MediaPicker/MediaPicker.ios.cs
Original file line number Diff line number Diff line change
Expand Up @@ -455,18 +455,18 @@ internal static async Task<FileResult> CreateCompressedFromFileResult(FileResult
using var originalStream = await originalResult.OpenReadAsync();
using var processedStream = await ImageProcessor.ProcessImageAsync(
originalStream, maximumWidth, maximumHeight, compressionQuality, originalResult.FileName);

// If ImageProcessor returns null (e.g., on .NET Standard), return original file
if (processedStream is null)
{
return originalResult;
}

// Read processed stream into memory
var memoryStream = new MemoryStream();
await processedStream.CopyToAsync(memoryStream);
memoryStream.Position = 0;

return new ProcessedImageFileResult(memoryStream, originalResult.FileName);
}
catch
Expand Down Expand Up @@ -498,12 +498,12 @@ bool ShouldUsePngFormat()
// 1. High quality (>=90) and no resizing needed (preserves original format)
// 2. Original file was PNG
// 3. Image might have transparency (PNG supports alpha channel)

bool highQualityNoResize = compressionQuality >= 90 && !maximumWidth.HasValue && !maximumHeight.HasValue;
bool originalWasPng = !string.IsNullOrEmpty(originalFileName) &&
bool originalWasPng = !string.IsNullOrEmpty(originalFileName) &&
(originalFileName.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
originalFileName.EndsWith(".PNG", StringComparison.OrdinalIgnoreCase));

// For very high quality or when original was PNG, preserve PNG format
return (compressionQuality >= 95 && !maximumWidth.HasValue && !maximumHeight.HasValue) || originalWasPng;
}
Expand All @@ -513,12 +513,12 @@ internal override Task<Stream> PlatformOpenReadAsync()
if (data == null)
{
var normalizedImage = uiImage.NormalizeOrientation();

// First, apply resizing if needed
var workingImage = normalizedImage;
var originalSize = normalizedImage.Size;
var newSize = CalculateResizedDimensions(originalSize.Width, originalSize.Height, maximumWidth, maximumHeight);

if (newSize.Width != originalSize.Width || newSize.Height != originalSize.Height)
{
// Resize the image
Expand All @@ -527,10 +527,10 @@ internal override Task<Stream> PlatformOpenReadAsync()
workingImage = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
}

// Then determine output format and apply compression
bool usePng = ShouldUsePngFormat();

if (usePng)
{
// Use PNG format - lossless compression, supports transparency
Expand Down Expand Up @@ -560,18 +560,18 @@ internal override Task<Stream> PlatformOpenReadAsync()

return Task.FromResult(data.AsStream());
}

static CoreGraphics.CGSize CalculateResizedDimensions(nfloat originalWidth, nfloat originalHeight, int? maxWidth, int? maxHeight)
{
if (!maxWidth.HasValue && !maxHeight.HasValue)
return new CoreGraphics.CGSize(originalWidth, originalHeight);

nfloat scaleWidth = maxWidth.HasValue ? (nfloat)maxWidth.Value / originalWidth : nfloat.MaxValue;
nfloat scaleHeight = maxHeight.HasValue ? (nfloat)maxHeight.Value / originalHeight : nfloat.MaxValue;

// Use the smaller scale to ensure both constraints are respected
nfloat scale = (nfloat)Math.Min(Math.Min((double)scaleWidth, (double)scaleHeight), 1.0); // Don't scale up

return new CoreGraphics.CGSize(originalWidth * scale, originalHeight * scale);
}
}
Expand Down
Loading