Categories
Uncategorized

Bash: Getting the systemd version and comparing it

This is just a quick post, but I wanted to spare both future me, and anyone else, from struggling with the precise syntax to extract the systemd version in a bash script and applying some work-around on older versions.

I recently had to work around a bug in systemd (specifically https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=927911), and needed to modify a service file if the systemd version was less than 241.

To do this, you can extract the version using systemctl --version, pipe it to a fun sed pattern, then use it:

#!/bin/bash

systemdver=$(systemctl --version | sed -nE "s/systemd ([0-9]+).*/\1/p")

# If the systemd version is prior to 241, do something
if [[ $systemdver -lt 241 ]];
then
   echo 'do whatever'
fi

Replace 241 with which ever version you need to compare against.

That’s it, hope this helps someone.

Categories
javascript Uncategorized web

Clipping image edges at runtime with CSS clip-path

This is going to be a rare front-end post from me, but I thought I’d share a handy technique for making a web browser treat the non-transparent edge of an image as the actual edge, rather than using the bounding box as it does by default.

I spent some time this year building a collage editing tool for an artist friend of mine, who runs workshops where students create collages out of existing images; I created a digital app to help out in the time of COVID, which you can find at https://collageit.co.uk (it’s actually pretty fun to play with).

The thing is that, when editing a collage, images overlap with each other a lot, and users interact with images in a more physical manner than just with ‘layers’, as you might find in a lot of image editors; that’s the nature of collage art. So, why does the default browser behaviour make this so difficult to implement?

Let’s say I have this image below. The image has a transparent background. From a visual perspective, the edge of this image is the edge of the circle, right?

Just a red button.

But, as you may know, the browser (and mostly every other image rendering system) will treat the edge of the image as the bounding box.

The actual image box.

This means that any mouse-over events or other interactions will all be with the image’s bounding box edge. If I want things to happen only when a user clicks on the actual image, things get tricky.

CSS clip-path

I’m going to start off just showing the working solution, which I’ve set up in codepen. Try it out with some of your own images if you like.

Due to canvas security restrictions, any images you want to load into the codepen need an Access-Control-Allow-Origin header in order to work. Imgur is a pretty good source that works.

So, we can display an image, and have the browser interact with the ‘actual’ edge of the image, rather than the bounding box.

How does this work?

The actual clipping behaviour is done with a CSS clip-path property. This property allows you to define a custom polygon that clips both the actual displayed portion of an image, as well as the area where mouse interactions are detected.

/* A simple clip example */
clip-path: polygon(50% 0, 100% 50%, 50% 100%, 0 50%);

However, we can actually exploit this property to provide explicit x + y positions for the clip:

clip-path: polygon(55px 49px,55px 50px,54px 50px,54px 51px,53px 51px,53px 52px,52px 52px, ....);

There isn’t really a limit to the length of the clip-path, so we could actually define the entire edge of the image using this mechanism if we wanted.

This is how I’m clipping the image in my approach.

Marching Squares

You may have realised (especially if you load your own images in the codepen) that I haven’t actually pre-computed this path and loaded it in, or embedded it in my HTML ahead of time. This path is computed at runtime when we load the image!

We do this using something called the Marching Squares algorithm. Basically, it’s an algorithm that detects a contour (or edge) of something. In this case, I use it to detect the path around the image where the alpha component of the image transitions to opaque.

I’m using an implementation of Marching Squares by Mike Bostock, from the d3 graphics library. The license is included in the codepen source; if you use that code, please maintain the license!

So, what are the steps here?

  1. Load the image from whatever source.
let loadPromise = new Promise((resolve, reject) => {        
        const imageElement = new Image();
        imageElement.crossOrigin = "anonymous";
        imageElement.onload = ev => {
            resolve(imageElement);
        };
        imageElement.onerror = ev => {
            reject(`Could not load image from ${imageUrl}.`);
        }
        imageElement.src = imageUrl;
});

// Wait for the load to finish.
const loadedImage = await loadPromise;

  1. Resize an in-memory canvas and render the image into it.
// I've defined 'workingCanvas' elsewhere.
const canvasWidth = workingCanvas.width = loadedImage.width;
const canvasHeight = workingCanvas.height = loadedImage.height;

const drawContext = workingCanvas.getContext("2d");

// Wipe the canvas.
drawContext.clearRect(0, 0, workingCanvas.width, workingCanvas.height);

// Draw the image.
drawContext.drawImage(loadedImage, 0 ,0);

  1. Get the raw pixel data for the image so we can analyse it.
// Get the raw pixel data that we can analyse.
const pixelData = drawContext.getImageData(0, 0, workingCanvas.width, workingCanvas.height)
                             .data;
  1. Define a function that, for any given x,y coordinate, can assess whether the point is part of the image.
// This is used by the marching squares algorithm
// to determine the outline of the non-transparent
// pixels on the image.    
const defineNonTransparent = function (x, y)
{
    // Get the alpha value for a pixel.
    var a=pixelData[(y*canvasWidth+x)*4+3];
    
    // This determines the alpha tolerance; I'm extremely intolerant of transparency;
    // any transparency is basically counted as the edge of the image.
    return(a>99);
}
  1. Finally, get the edge points of the image.
// Get the edges.
var points = contour(defineNonTransparent);

From the edge points we can trivially construct a clip path to use in the css polygon construct.

function getClipPath(imgData) 
{
    let clipPathSet = [];

    imgData.boundingPoints.forEach(p => clipPathSet.push(`${p.x}px ${p.y}px`));

    return clipPathSet.join(',');
};

Limitations

There are a couple of limitations to this approach (which I can largely accept for my purposes):

  1. The algorithm can only detect one edge in an image; so if your image is made up of multiple disconnected parts, only one of them is going to be picked up and clipped.
  2. I can’t detect internal transparency with this algorithm right now, so if you have a blank space inside the image, that’ll be treated as part of the image rather than something you can click through.
  3. This isn’t going to work in old browsers (IE is out, basically).

It’s quite likely that there are better ways to do this, and I’d be interested to learn of better solutions if you have them!

Categories
c# Uncategorized

Detecting Init-Only Properties with Reflection in C# 9

This is a super-quick post to hopefully save someone the trouble of figuring out how to detect init-only properties (as I had to this morning).

Init-only properties are a new feature in C# 9, and let you define properties that can only be set in the constructor or in an object initialisation block:

public class MyObject
{
    public string InitOnlyProperty { get; init; }
}

static void Main(string[] args)
{
    var newInstance = new MyObject
    {
        InitOnlyProperty = "value"
    };

    // Compiler error!!
    newInstance.InitOnlyProperty = "something";
}

The init; used instead of set; marks the property as init-only.

If you want to check if any given property is init-only at runtime, it’s a little more complicated than just checking a single flag on PropertyInfo.

Looking at the generated IL for our code in dotPeek, we can see that the generated set method’s return value has an additional modreq option for System.Runtime.CompilerServices.IsExternalInit.

// .property instance string InitOnlyProperty()
public string InitOnlyProperty
{
    // .method public hidebysig specialname instance string
        // get_InitOnlyProperty() cil managed
    [CompilerGenerated] get
    // .maxstack 8
    // 
    // IL_0000: ldarg.0      // this
    // IL_0001: ldfld        string InitOnlyDetection.Program/MyObject::'<InitOnlyProperty>k__BackingField'
    // IL_0006: ret
    // 
    {
        return this.\u003CInitOnlyProperty\u003Ek__BackingField;
    }

    // .method public hidebysig specialname instance void modreq ([System.Runtime]System.Runtime.CompilerServices.IsExternalInit)
        // set_InitOnlyProperty(
        // string 'value'
        // ) cil managed
    [CompilerGenerated] set
    // .maxstack 8
    // 
    // IL_0000: ldarg.0      // this
    // IL_0001: ldarg.1      // 'value'
    // IL_0002: stfld        string InitOnlyDetection.Program/MyObject::'<InitOnlyProperty>k__BackingField'
    // IL_0007: ret
    // 
    {
        this.\u003CInitOnlyProperty\u003Ek__BackingField = value;
    }
}

So, we can detect init-only properties with the following extension method:

using System.Linq;
using System.Reflection;

public static class PropertyExtensions
{
    /// <summary>
    /// Determines if this property is marked as init-only.
    /// </summary>
    /// <param name="property">The property.</param>
    /// <returns>True if the property is init-only, false otherwise.</returns>
    public static bool IsInitOnly(this PropertyInfo property)
    {
        if (!property.CanWrite)
        {
            return false;
        }

        var setMethod = property.SetMethod;

        // Get the modifiers applied to the return parameter.
        var setMethodReturnParameterModifiers = setMethod.ReturnParameter.GetRequiredCustomModifiers();

        // Init-only properties are marked with the IsExternalInit type.
        return setMethodReturnParameterModifiers.Contains(typeof(System.Runtime.CompilerServices.IsExternalInit));
    }
}

There you go, told you it would be super quick!