Skip to content

Conversation

@Shakes4cc
Copy link

@Shakes4cc Shakes4cc commented Jan 25, 2026

Implements magic number checks to detect images in files without extensions.

PR Checklist

  • Functionality has been tested, no obvious bugs
    I've never built something made with C# before (I only use python and C) so I tried installing Visual Studio to build and test the application, but I couldn't stop getting "Metadata file '.dll' could not be found" errors even after spending an hour attempting various fixes. The changes are simple enough that I hope you will accept them after a quick test on your end.
  • Code style follows project conventions
  • Documentation/comments updated (if applicable)
    Not applicable, I would say.

Brief Description of Changes

Please briefly describe the main changes in this PR:
As indicated in the title, the goal is allowing QuickLook to preview image files even when the extension has been removed, which can be useful for example when exploring a browser's cache folders.
This complements the already present support for extension-less video files.

Related Issue (if any)

Please provide related issue numbers:
None.

Additional Notes

Add any extra notes here:
None.

Summary by Sourcery

New Features:

  • Enable image handling for extension-less files by inspecting magic numbers for common formats such as PNG, JPEG, GIF, BMP, and WebP.

Implements magic number checks to detect images in files without extensions.
@sourcery-ai
Copy link

sourcery-ai bot commented Jan 25, 2026

Reviewer's Guide

Adds content-based magic number detection to the image viewer plugin so it can handle extension-less image files while preserving existing extension-based behavior and directory checks.

Class diagram for Plugin image handling with magic number checks

classDiagram
    class Plugin {
        +bool CanHandle(string path)
        -static bool IsImageByMagicNumber(string path)
    }

    class WebHandler {
        +static bool TryCanHandle(string path)
    }

    class Directory {
        +static bool Exists(string path)
    }

    class Path {
        +static bool HasExtension(string path)
    }

    class File {
        +static bool Exists(string path)
    }

    class FileStream {
        +FileStream(string path, FileMode mode, FileAccess access, FileShare share)
        +long Length
        +int Read(byte[] buffer, int offset, int count)
        +void Dispose()
    }

    Plugin ..> WebHandler : uses
    Plugin ..> Directory : uses
    Plugin ..> Path : uses
    Plugin ..> File : uses
    Plugin ..> FileStream : uses

    class FileMode {
    }

    class FileAccess {
    }

    class FileShare {
    }

    FileStream ..> FileMode : uses
    FileStream ..> FileAccess : uses
    FileStream ..> FileShare : uses
Loading

Flow diagram for CanHandle image detection with magic numbers

flowchart TD
    A[Start CanHandle path] --> B{WebHandler.TryCanHandle path}
    B -- true --> Z[Return true]
    B -- false --> C{Directory.Exists path}
    C -- true --> Y[Return false]
    C -- false --> D{Has well known image extension}
    D -- true --> Z
    D -- false --> E{Path.HasExtension path}
    E -- false --> F[Call IsImageByMagicNumber path]
    F --> G{IsImageByMagicNumber result}
    G -- true --> Z
    G -- false --> Y
    E -- true --> Y
Loading

File-Level Changes

Change Details Files
Refine CanHandle logic to support magic-number-based detection of extension-less image files.
  • Return early for directory paths before performing any file checks.
  • Keep existing extension-based detection for well-known image types, but return immediately when a match is found.
  • Add a fallback path that, when no extension is present, delegates detection to a new magic number helper method.
  • Explicitly return false when none of the earlier checks succeed.
QuickLook.Plugin/QuickLook.Plugin.ImageViewer/Plugin.cs
Introduce magic number inspection to detect common image formats by file header bytes.
  • Add IsImageByMagicNumber helper that opens the file safely with shared read access and validates minimal length before reading.
  • Read up to 12 bytes from the file and compare against known headers for PNG, JPEG, GIF, BMP, and WebP.
  • Gracefully handle missing files, short files, and IO exceptions by returning false rather than throwing.
QuickLook.Plugin/QuickLook.Plugin.ImageViewer/Plugin.cs

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue, and left some high level feedback:

  • The IsImageByMagicNumber method catches all exceptions and silently returns false; consider narrowing the exception types or at least logging unexpected exceptions to avoid hiding underlying IO or permission issues.
  • The magic number comparisons are currently done with repeated index checks; you might improve readability and maintainability by defining static readonly byte signatures (e.g., PngSignature, JpegSignature) and using a small helper to compare spans/arrays.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The `IsImageByMagicNumber` method catches all exceptions and silently returns `false`; consider narrowing the exception types or at least logging unexpected exceptions to avoid hiding underlying IO or permission issues.
- The magic number comparisons are currently done with repeated index checks; you might improve readability and maintainability by defining static readonly byte signatures (e.g., `PngSignature`, `JpegSignature`) and using a small helper to compare spans/arrays.

## Individual Comments

### Comment 1
<location> `QuickLook.Plugin/QuickLook.Plugin.ImageViewer/Plugin.cs:153-156` </location>
<code_context>
+            if (bytesRead < 4)
+                return false;
+
+            // PNG: 89 50 4E 47 0D 0A 1A 0A
+            if (bytesRead >= 8 &&
+                buffer[0] == 0x89 && buffer[1] == 0x50 && buffer[2] == 0x4E && buffer[3] == 0x47 &&
+                buffer[4] == 0x0D && buffer[5] == 0x0A && buffer[6] == 0x1A && buffer[7] == 0x0A)
+            {
+                return true;
</code_context>

<issue_to_address>
**suggestion:** Consider extracting magic numbers into constants or using spans for cleaner signature checks.

The current chain of `buffer[i] == ...` checks works but is hard to read and extend as you add more formats. Defining each signature as a `ReadOnlySpan<byte>` and comparing via `SequenceEqual` on a slice of `buffer`, or moving each format check into a small helper method, would make the code clearer and easier to maintain while avoiding duplicated index logic.

Suggested implementation:

```csharp
            var buffer = new byte[12];
            var bytesRead = fs.Read(buffer, 0, buffer.Length);
            if (bytesRead < 4)
                return false;

            ReadOnlySpan<byte> pngSignature = new byte[] { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

            // PNG: 89 50 4E 47 0D 0A 1A 0A
            if (bytesRead >= pngSignature.Length &&
                buffer.AsSpan(0, pngSignature.Length).SequenceEqual(pngSignature))
            {
                return true;
            }

        if (Directory.Exists(path))

```

If `System` is not already imported at the top of this file, add `using System;` so that `ReadOnlySpan<byte>` and `AsSpan` are available. You can follow this pattern to add other signatures (e.g., JPEG, GIF, WEBP) by defining additional `ReadOnlySpan<byte>` values and comparing them via `buffer.AsSpan(start, length).SequenceEqual(signature)` to keep all magic numbers centralized and readable.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant