Skip to content

Commit

Permalink
Fix some warnings and style issues
Browse files Browse the repository at this point in the history
  • Loading branch information
lilith committed Jan 29, 2024
1 parent cefd3c0 commit b678d91
Show file tree
Hide file tree
Showing 34 changed files with 111 additions and 155 deletions.
2 changes: 2 additions & 0 deletions src/Imageflow.both.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=BGRA/@EntryIndexedValue">BGRA</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=BGRA/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=framewise/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=imageflow/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
2 changes: 1 addition & 1 deletion src/Imageflow/Bindings/ImageInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static ImageInfo FromDynamic(JsonNode imageInfo)
return new ImageInfo(imageInfo);
}

public Fluent.PixelFormat FrameDecodesInto { get; private init; }
public PixelFormat FrameDecodesInto { get; private init; }
public long ImageWidth { get; private init; }
public long ImageHeight { get; private init; }
public string PreferredMimeType { get; private init; }
Expand Down
8 changes: 1 addition & 7 deletions src/Imageflow/Bindings/ImageflowAssertionFailed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,5 @@
/// <summary>
/// For bugs
/// </summary>
public class ImageflowAssertionFailed : Exception
{
public ImageflowAssertionFailed(string message) : base(message)
{

}
}
public class ImageflowAssertionFailed(string message) : Exception(message);
}
3 changes: 1 addition & 2 deletions src/Imageflow/Bindings/ImageflowException.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,9 @@ private static ErrorFetchResult TryGetErrorString(JobContextHandle c, ulong buff

internal static ImageflowException FromContext(JobContextHandle c, ulong defaultBufferSize = 2048, string? additionalInfo = null)
{
var result = ErrorFetchResult.BufferTooSmall;
for (var bufferSize = defaultBufferSize; bufferSize < MaxBufferSize; bufferSize *= 2)
{
result = TryGetErrorString(c, bufferSize, out var message);
var result = TryGetErrorString(c, bufferSize, out var message);
switch (result)
{
case ErrorFetchResult.Success:
Expand Down
24 changes: 12 additions & 12 deletions src/Imageflow/Bindings/JobContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ internal static byte[] SerializeToJson<T>(T obj){
{
Indented = true
});
System.Text.Json.JsonSerializer.Serialize(utf8JsonWriter, obj, options);
JsonSerializer.Serialize(utf8JsonWriter, obj, options);
utf8JsonWriter.Flush();
return ms.ToArray();
}
Expand All @@ -84,23 +84,23 @@ internal static byte[] SerializeNode(JsonNode node, bool indented = true){
[RequiresDynamicCode("Use SendMessage(string method, JsonNode message) instead for AOT compatibility")]
public IJsonResponseProvider SendMessage<T>(string method, T message){
AssertReady();
return SendJsonBytes(method, JobContext.SerializeToJson(message));
return SendJsonBytes(method, SerializeToJson(message));
}
public IJsonResponseProvider SendMessage(string method, JsonNode message){
AssertReady();
return SendJsonBytes(method, JobContext.SerializeNode(message));
return SendJsonBytes(method, SerializeNode(message));
}

[Obsolete("Use ExecuteJsonNode instead for AOT compatibility")]
[RequiresUnreferencedCode("Use ExecuteJsonNode instead for AOT compatibility")]
[RequiresDynamicCode("Use ExecuteJsonNode instead for AOT compatibility")]
public IJsonResponseProvider Execute<T>(T message){
AssertReady();
return SendJsonBytes("v0.1/execute", JobContext.SerializeToJson(message));
return SendJsonBytes("v0.1/execute", SerializeToJson(message));
}
public IJsonResponseProvider ExecuteJsonNode(JsonNode message){
AssertReady();
return SendJsonBytes("v0.1/execute", JobContext.SerializeNode(message));
return SendJsonBytes("v0.1/execute", SerializeNode(message));
}

internal IJsonResponseProvider Execute(byte[] utf8Message){
Expand All @@ -110,7 +110,7 @@ internal IJsonResponseProvider Execute(byte[] utf8Message){
public ImageInfo GetImageInfo(int ioId)
{
AssertReady();
using (var response = SendJsonBytes("v0.1/get_image_info", JobContext.SerializeNode(new JsonObject(){ {"io_id", ioId} })))
using (var response = SendJsonBytes("v0.1/get_image_info", SerializeNode(new JsonObject(){ {"io_id", ioId} })))
{
var node = response.DeserializeJsonNode();
if (node == null) throw new ImageflowAssertionFailed("get_image_info response is null");
Expand All @@ -120,11 +120,11 @@ public ImageInfo GetImageInfo(int ioId)
{
if (successValue?.GetValue<bool>() != true)
{
throw ImageflowException.FromContext(this.Handle);
throw ImageflowException.FromContext(Handle);
}
var dataValue = responseObj.TryGetPropertyValue("data", out var dataValueObj) ? dataValueObj : null;
if (dataValue == null) throw new ImageflowAssertionFailed("get_image_info response does not have a data property");
var imageInfoValue = (dataValue.AsObject()?.TryGetPropertyValue("image_info", out var imageInfoValueObj) ?? false) ? imageInfoValueObj : null;
var imageInfoValue = (dataValue.AsObject().TryGetPropertyValue("image_info", out var imageInfoValueObj)) ? imageInfoValueObj : null;

if (imageInfoValue == null) throw new ImageflowAssertionFailed("get_image_info response does not have an image_info property");
return ImageInfo.FromDynamic(imageInfoValue);
Expand All @@ -150,7 +150,7 @@ public ImageInfo GetImageInfo(int ioId)
public VersionInfo GetVersionInfo()
{
AssertReady();
using (var response = SendJsonBytes("v1/get_version_info", JobContext.SerializeNode(new JsonObject())))
using (var response = SendJsonBytes("v1/get_version_info", SerializeNode(new JsonObject())))
{
var node = response.DeserializeJsonNode();
if (node == null) throw new ImageflowAssertionFailed("get_version_info response is null");
Expand All @@ -160,11 +160,11 @@ public VersionInfo GetVersionInfo()
{
if (successValue?.GetValue<bool>() != true)
{
throw ImageflowException.FromContext(this.Handle);
throw ImageflowException.FromContext(Handle);
}
var dataValue = responseObj.TryGetPropertyValue("data", out var dataValueObj) ? dataValueObj : null;
if (dataValue == null) throw new ImageflowAssertionFailed("get_version_info response does not have a data property");
var versionInfoValue = (dataValue.AsObject()?.TryGetPropertyValue("version_info", out var versionInfoValueObj) ?? false) ? versionInfoValueObj : null;
var versionInfoValue = (dataValue.AsObject().TryGetPropertyValue("version_info", out var versionInfoValueObj)) ? versionInfoValueObj : null;

if (versionInfoValue == null) throw new ImageflowAssertionFailed("get_version_info response does not have an version_info property");
return VersionInfo.FromNode(versionInfoValue);
Expand Down Expand Up @@ -254,7 +254,7 @@ public IJsonResponseProvider ExecuteImageResizer4CommandString( int inputId, int

internal void AddToDisposeQueue(IDisposable d)
{
if (_toDispose == null) _toDispose = new List<IDisposable>(1);
_toDispose ??= new List<IDisposable>(1);
_toDispose.Add(d);
}

Expand Down
3 changes: 1 addition & 2 deletions src/Imageflow/Bindings/JsonResponse.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System.Text;
using System.Text.Json.Nodes;
using JsonNamingPolicy = System.Text.Json.JsonNamingPolicy;
using JsonSerializerOptions = System.Text.Json.JsonSerializerOptions;
using Utf8JsonReader = System.Text.Json.Utf8JsonReader;

namespace Imageflow.Bindings
Expand Down Expand Up @@ -71,6 +69,7 @@ public void Dispose()

}

// ReSharper disable once InconsistentNaming
public static class IJsonResponseProviderExtensions
{

Expand Down
21 changes: 8 additions & 13 deletions src/Imageflow/Bindings/NativeLibraryLoading.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
using System.Collections.Concurrent;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

#if !NET8_0_OR_GREATER
using System.Reflection;
#endif
namespace Imageflow.Bindings
{
internal class LoadLogger : ILibraryLoadLogger
Expand Down Expand Up @@ -225,9 +226,9 @@ private static IEnumerable<Tuple<bool,string>> BaseFolders(IEnumerable<string>?
yield return Tuple.Create(true, AppDomain.CurrentDomain.RelativeSearchPath);
}
// look in System.AppContext.BaseDirectory
if (!string.IsNullOrEmpty(System.AppContext.BaseDirectory))
if (!string.IsNullOrEmpty(AppContext.BaseDirectory))
{
yield return Tuple.Create(true, System.AppContext.BaseDirectory);
yield return Tuple.Create(true, AppContext.BaseDirectory);
}

// Look in the base directory from which .NET looks for managed assemblies
Expand Down Expand Up @@ -269,19 +270,15 @@ internal static IEnumerable<string> SearchPossibilitiesForFile(string filename,
{
// First try the simple arch subdir since that is where the nuget native packages unpack
path = Path.Combine(directory, ArchitectureSubdir.Value, filename);
if (!attemptedPaths.Contains(path))
{
attemptedPaths.Add(path);
if (attemptedPaths.Add(path)){
yield return path;
}
}

// Try the folder itself
path = Path.Combine(directory, filename);

if (!attemptedPaths.Contains(path))
{
attemptedPaths.Add(path);
if (attemptedPaths.Add(path)){
yield return path;
}

Expand All @@ -290,9 +287,7 @@ internal static IEnumerable<string> SearchPossibilitiesForFile(string filename,
// Last try native runtimes directory in case this is happening in .NET Core
path = Path.Combine(directory, "runtimes",
PlatformRuntimePrefix.Value + "-" + ArchitectureSubdir.Value, "native", filename);
if (!attemptedPaths.Contains(path))
{
attemptedPaths.Add(path);
if (attemptedPaths.Add(path)){
yield return path;
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/Imageflow/Bindings/NativeMethods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public enum Lifetime
OutlivesContext = 1,
}

// ReSharper disable once InconsistentNaming
public const int ABI_MAJOR = 3;
// ReSharper disable once InconsistentNaming
public const int ABI_MINOR = 0;

[DllImport("imageflow", CallingConvention = CallingConvention.Cdecl)]
Expand Down
2 changes: 1 addition & 1 deletion src/Imageflow/Bindings/PinBox.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ internal class PinBox : CriticalFinalizerObject, IDisposable
private List<GCHandle>? _pinned;
internal void AddPinnedData(GCHandle handle)
{
if (_pinned == null) _pinned = new List<GCHandle>();
_pinned ??= new List<GCHandle>();
_pinned.Add(handle);
}

Expand Down
1 change: 0 additions & 1 deletion src/Imageflow/Bindings/VersionInfo.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Text.Json.Nodes;
using System.Xml;

namespace Imageflow.Bindings
{
Expand Down
10 changes: 5 additions & 5 deletions src/Imageflow/Fluent/BuildDecodeResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ namespace Imageflow.Fluent
{
public class BuildDecodeResult
{
public string? PreferredMimeType { get; internal set; }
public string? PreferredExtension { get;internal set; }
public int IoId { get; internal set;}
public int Width { get; internal set;}
public int Height { get; internal set;}
public string? PreferredMimeType { get; internal init; }
public string? PreferredExtension { get;internal init; }
public int IoId { get; internal init;}
public int Width { get; internal init;}
public int Height { get; internal init;}

}

Expand Down
2 changes: 1 addition & 1 deletion src/Imageflow/Fluent/BuildEncodeResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ internal BuildEncodeResult()
/// If this Destination is a BytesDestination, returns the ArraySegment - otherwise null
/// Returns the byte segment for the given output ID (if that output is a BytesDestination)
/// </summary>
public ArraySegment<byte>? TryGetBytes() => (Destination is BytesDestination d) ? d.GetBytes() : (ArraySegment<byte>?)null;
public ArraySegment<byte>? TryGetBytes() => (Destination is BytesDestination d) ? d.GetBytes() : default;
}
// Width = er.w,
// Height = er.h,
Expand Down
6 changes: 2 additions & 4 deletions src/Imageflow/Fluent/BuildEndpoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,8 @@ internal BuildEndpoint(ImageJob builder,JsonNode nodeData, BuildNode? inputNode,
[Obsolete("Use Finish().WithCancellationTimeout")]
public FinishJobBuilder FinishWithTimeout(int milliseconds)
{
using (var tokenSource = new CancellationTokenSource(milliseconds))
{
return FinishWithToken(tokenSource.Token);
}
using var tokenSource = new CancellationTokenSource(milliseconds);
return FinishWithToken(tokenSource.Token);
}

}
Expand Down
6 changes: 3 additions & 3 deletions src/Imageflow/Fluent/BuildJobResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,15 @@ internal static BuildJobResult From(IJsonResponseProvider response, Dictionary<i
{
throw new ImageflowAssertionFailed(requiredMessage);
}

var ioId = ioIdValue?.GetValue<int>() ?? throw new ImageflowAssertionFailed(requiredMessage);
encodeResults.Add(new BuildEncodeResult
{
IoId = ioIdValue?.GetValue<int>() ?? throw new ImageflowAssertionFailed(requiredMessage),
IoId = ioId,
Width = wValue?.GetValue<int>() ?? throw new ImageflowAssertionFailed(requiredMessage),
Height = hValue?.GetValue<int>() ?? throw new ImageflowAssertionFailed(requiredMessage),
PreferredExtension = preferredExtensionValue?.GetValue<string>() ?? throw new ImageflowAssertionFailed(requiredMessage),
PreferredMimeType = preferredMimeTypeValue?.GetValue<string>() ?? throw new ImageflowAssertionFailed(requiredMessage),
Destination = outputs[ioIdValue?.GetValue<int>() ?? throw new ImageflowAssertionFailed(requiredMessage)]
Destination = outputs[ioId]
});
}

Expand Down
13 changes: 5 additions & 8 deletions src/Imageflow/Fluent/BuildNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public BuildEndpoint Encode(IOutputDestination destination, int ioId, IEncoderPr
// return new BuildEndpoint(Builder,
// new {encode = new {io_id = ioId, preset = encoderPreset?.ToImageflowDynamic()}}, this, null);
return new BuildEndpoint(Builder,
new JsonObject() {["encode"] = new JsonObject() {["io_id"] = ioId, ["preset"] = encoderPreset?.ToJsonNode()}}, this, null);
new JsonObject() {["encode"] = new JsonObject() {["io_id"] = ioId, ["preset"] = encoderPreset.ToJsonNode()}}, this, null);
}
/// <summary>
/// Encode the result to the given destination (such as a BytesDestination or StreamDestination)
Expand Down Expand Up @@ -81,7 +81,7 @@ public BuildNode ConstrainWithin(uint? w, uint? h)
/// <param name="h"></param>
/// <param name="hints"></param>
/// <returns></returns>
public BuildNode ConstrainWithin(uint? w, uint? h, ResampleHints hints)
public BuildNode ConstrainWithin(uint? w, uint? h, ResampleHints? hints)
{
var jsonObject = new JsonObject
{
Expand Down Expand Up @@ -408,7 +408,7 @@ public BuildNode DrawImageExactTo(BuildNode canvas, Rectangle to, ResampleHints
["h"] = to.Height,
["x"] = to.X,
["y"] = to.Y,
["blend"] = blend?.ToString()?.ToLowerInvariant(),
["blend"] = blend?.ToString().ToLowerInvariant(),
["hints"] = hints?.ToJsonNode()
}
});
Expand Down Expand Up @@ -678,11 +678,8 @@ public BuildNode Watermark(IBytesSource source, WatermarkOptions watermark) =>
/// <returns></returns>
public BuildNode Watermark(IBytesSource source, int? ioId, WatermarkOptions watermark)
{
if (ioId == null)
{
ioId = this.Builder.GenerateIoId();
}
this.Builder.AddInput(ioId.Value, source);
ioId ??= Builder.GenerateIoId();
Builder.AddInput(ioId.Value, source);
// return To(new
// {
// watermark = watermark.ToImageflowDynamic(ioId.Value)
Expand Down
7 changes: 3 additions & 4 deletions src/Imageflow/Fluent/Constraint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public Constraint SetConstraintMode(ConstraintMode mode)

public Constraint SetHints(ResampleHints hints)
{
this.Hints = hints;
Hints = hints;
return this;
}

Expand All @@ -62,7 +62,7 @@ public object ToImageflowDynamic()
{
return new
{
mode = Mode.ToString()?.ToLowerInvariant(),
mode = Mode.ToString().ToLowerInvariant(),
w = W,
h = H,
hints = Hints?.ToImageflowDynamic(),
Expand All @@ -73,8 +73,7 @@ public object ToImageflowDynamic()

internal JsonNode ToJsonNode()
{
var node = new JsonObject();
node.Add("mode", Mode.ToString()?.ToLowerInvariant());
var node = new JsonObject { { "mode", Mode.ToString().ToLowerInvariant() } };
if (W != null) node.Add("w", W);
if (H != null) node.Add("h", H);
if (Hints != null) node.Add("hints", Hints.ToJsonNode());
Expand Down
2 changes: 1 addition & 1 deletion src/Imageflow/Fluent/DecodeCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public DecodeCommands SetJpegDownscaling(int targetWidthHint,
public DecodeCommands SetWebPDownscaling(int targetWidthHint,
int targetHeightHint)
{
this.WebPDownscaleHint = new Size(targetWidthHint, targetHeightHint);
WebPDownscaleHint = new Size(targetWidthHint, targetHeightHint);
return this;
}

Expand Down
3 changes: 1 addition & 2 deletions src/Imageflow/Fluent/Enumerations.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Text.Json.Serialization;
using Imageflow.Bindings;
using Imageflow.Bindings;

namespace Imageflow.Fluent
{
Expand Down
4 changes: 2 additions & 2 deletions src/Imageflow/Fluent/FinishJobBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public FinishJobBuilder SetCancellationToken(CancellationToken token)
public FinishJobBuilder WithCancellationTimeout(int milliseconds)
{
_tokenSource = new CancellationTokenSource(milliseconds);
return this.WithCancellationToken(_tokenSource.Token);
return WithCancellationToken(_tokenSource.Token);
}
/// <summary>
/// Replaces the CancellationToken with a timeout
Expand All @@ -66,7 +66,7 @@ public FinishJobBuilder WithCancellationTimeout(int milliseconds)
public FinishJobBuilder SetCancellationTimeout(int milliseconds)
{
_tokenSource = new CancellationTokenSource(milliseconds);
return this.WithCancellationToken(_tokenSource.Token);
return WithCancellationToken(_tokenSource.Token);
}

public Task<BuildJobResult> InProcessAsync() => _builder.FinishAsync(new JobExecutionOptions(),_security, _token);
Expand Down
Loading

0 comments on commit b678d91

Please sign in to comment.