JavaScript shutting the stable door after the horse has bolted?

Anyone up for some JavaScript shenanigans? Take a look at this:

<!doctype html>
<html lang="en">
<button onclick="pick()">Choose a folder</button>
<script>
async function pick() {
  const folder = await showDirectoryPicker();
  const open = indexedDB.open("demo", 1);
  open.onupgradeneeded = () => open.result.createObjectStore("handles"); // first time: make the store
  open.onsuccess = () => open.result.transaction("handles", "readwrite").objectStore("handles").put(folder, "folder");
}
</script>
</html> 

It’s a web page that contains a tiny piece of JavaScript that creates a handle for a local filesystem and stores it in an indexedDB when you press a button with the caption “Choose a folder”. Why do we need this? Well, suppose you have a web application that wants to store data on the local machine. Something that is not usually allowed, what with all the nasty sites out there. Well, the application can ask for a handle to a folder on your machine that you are happy for the browser to work with. That’s what showDirectoryPicker does. It asks the user to pick a folder where the browser can put stuff for this site. I don’t want the user to have to do this every time they use my web based application. So I need to store it locally.

I can use a local indexedDB to do that. This is not really a database, it’s more of an object store. However, it is terribly useful. So I’ll open the database and add the folder reference to the database. That’s what the code above does. But it contains some code that hurt my head for a while:

  const open = indexedDB.open("demo", 1);
  open.onupgradeneeded = () => open.result.createObjectStore("handles");// first time: make the store
  open.onsuccess = () => open.result.transaction("handles", "readwrite").objectStore("handles").put(folder, "folder");

The first statement opens a connection to a database called demo. It wants version 1. Fair enough. The second statement binds a function to the onupgradeneeded event on the connection. This fires when the database version is wrong or if the database is not there. The handler creates a new database called handles. So, if we ask for a database and it isn’t there, we make one. Lovely. The next statement creates a handler for the “happy path” - otherwise known as onsuccess. This is the code that runs once the database connection is open. When that happens we want to make an object called “folder” which contains the folder we created earlier. That’s what the transaction does. Now, when the website loads all my application has to do is look in the local database for the handle so it can use local files. Also lovely. All the code makes sense. So why did it make my head hurt?

Well, it’s because when I first looked at it I thought we were closing the stable door after the horse has bolted. The first statement does the open. And the, after that, we put two event handlers into place to deal with what happens when the open runs. At first sight this seems wrong. How do the handlers get called when they aren’t set up? But it makes sense. And it is all to do with how JavaScript does things.

The first thing you need to know is that indexedDB.open doesn’t open the database. It starts opening the database. So when open returns the database isn’t open. It’s being opened.

The second thing you need to know is that open won’t call the event handlers when it wants to fire the events. It will put the events into an ordered list to be dealt with later. So the fact that it might not have anything assigned to deal with the events isn’t a problem.

The third thing you need to do is when JavaScript finishes the code that was called when the pick button was pressed it then goes through the list of events that have been raised and calls each one in turn. This happens when the event handlers have been assigned, so they all run and do what we want.

This makes perfect sense. In the code above the user presses the “Choose a folder” button. This calls the pick function which pops up the file picker, captures the folder and then pops it in the database. We don’t want our button handler to have to hang around waiting for the database to catch up. We want it to return to the user so that they can do other things. When the database does catch up, the events need to fire and sort everything out.

JavaScript is super clever. But it can also be super-confusing sometimes.

Achievement unlocked: Sony Portable Cassette Deck

It even has ferrite and ferrite heads!

In a rush of blood to the head I’ve gone and bought a Sony TC-153SD portable stereo cassette deck. I really, really, wanted one of these back in the day but I couldn’t afford one. But now I can. It cost less than a video game. The seller posted a video of it playing back music which sounds about right (although one of the channels is not working) and it is probably running slow. It arrives next week. I’m really looking forward to taking the back off and taking a look at all those discrete components.

Totally unrelated favourite line of the day: “I work in the civil service and at the weekends I’m rude to people”.

Last chance to see...

I got an email today telling me that Karoo, my internet provider, will be turning off their web server hosting in a few weeks. This was the first place I put my blog back in the day, along with the much missed Microsoft Spoke. I you want to relive the heady mix of travel, computing and bad jokes that was my life in the early 2000’s you can go and look here. Some of the links are broken, some go to the wrong place and some of the jokes are not very funny. So it’s pretty much like my blog today….

Return of the Rather Useful Seminar

Well, that’s the title slide done

I’m back in PowerPoint writing slides. Not done this for a while. I’m going back to Hull University to deliver a Rather Useful Seminar. This time I’ll be talking about how I made the Custard Cream Camera and how I think Vibe Coding (hate the name) is a thing. If you’re a Computer Science student at the university you might have to go along. It’s in the timetable. For the rest of the world, I’ll record a video. Should be fun.

Let there be a mended light

I did something terrible on Saturday night. I turned the kitchen lights off and on again. This really upset one of them, which made a pop and then didn’t work. These are LED lights which last a long time. But apparently not forever. So on Sunday I wandered into the garage, fought my way through my cardboard box collection and found a spare light left over from the original kitchen installation 14 or so years ago. I couldn’t believe my luck. Then I wired the replacement light in and discovered that the power supply has failed. Not the light. At which point I started believing my luck again.

The replacement power supply arrived today. Knowing my luck as I now do, I was expecting it to be the wiring that had broken. But no, we now have our light back.

Telling your VS Code windows apart with colour

This makes things pretty obvious…

I often have two copies of Visual Studio Code open on the same project. Both are on my desktop. One runs locally. The other is connected to a different platform through a Remote connection. I do this a lot when I'm writing code for a Raspberry Pi and it can be rather confusing. The two windows look exactly the same, and more than once I've typed into the wrong editor, or built and run my code on the wrong machine.

What I wanted was to make the editor pages a different colour in each window, so I can see at a glance which one I'm in. My first thought was to write an extension. Before I did, I checked whether one already existed. It turns out you don't need an extension at all. VS Code can do this with its own settings.

The trick: User settings and Remote settings

VS Code keeps more than one level of settings, and later levels override earlier ones:

  1. Default: built into VS Code.
  2. User: your local installation. Applies to every local window.
  3. Remote: stored on the remote machine. Applies to every window connected to that machine, whatever project is open.
  4. Workspace: the project's own .vscode/settings.json.

If you put one colour scheme in your User settings and a different one in the Remote settings, every window shows where it is running. You set it once per machine and it works for every project, with nothing added to the projects themselves.

Colouring the remote window

Open a remote window. The box in the bottom-left corner shows the connection, for example SSH: myserver. Press Ctrl+Shift+P and run Preferences: Open Remote Settings (JSON). This command only appears in a remote window.

Add a colour scheme like this:

{
    "workbench.colorCustomizations": {
        "editor.background": "#0d1b2a",
        "editor.foreground": "#e0e6ed"
    }
}

Save the file and the editor changes colour straight away. The settings are stored on the remote machine itself, so that machine shows the same colours whichever computer you connect from.

Colouring the local window (optional)

You only need this step if you want to change your local colours as well. Colouring the remote window is usually enough to tell them apart.

In a local window, run Preferences: Open User Settings (JSON) and add a workbench.colorCustomizations entry in the same way. If the file already has one, add your colours to it rather than creating a second entry, because only the last one counts.

Going further

editor.background only changes the editor page itself. The line-number gutter, the current-line highlight and the terminal keep their theme colours. These settings colour the rest of the window too:

"workbench.colorCustomizations": {
    "editor.background": "#0d1b2a",
    "editor.foreground": "#e0e6ed",
    "editorGutter.background": "#0d1b2a",
    "editor.lineHighlightBackground": "#1b2d42",
    "terminal.background": "#0d1b2a",
    "titleBar.activeBackground": "#1f4e79",
    "statusBar.background": "#1f4e79"
}

The title bar and status bar are the most useful, because you can see them even when no file is open.

Some other things worth knowing:

  • Each remote machine has its own settings, so you can give each one its own colour. Each WSL distribution counts as a separate remote too.
  • Dev containers lose their settings when rebuilt, because the settings are stored inside the container. To keep the colours, put them in the project's devcontainer.json under customizations.vscode.settings.
  • Project settings win. If a project's .vscode/settings.json sets workbench.colorCustomizations, it overrides your colours in both windows. Colour extensions write their settings there, so check that file if your colours don't appear.

What about extensions?

There are extensions that do something similar. Peacock is the best known. It has a peacock.remoteColor setting that gives remote windows a different colour, but it colours the title bar, activity bar and status bar rather than the editor page. Others, such as Color Stamp and Unique Window Colors, colour windows by project. That doesn't help here, because the same project would get the same colour on both sides.

For my purposes the built-in settings do the job, and there's nothing to install.

Mini Brands Vinyl Records Tag Reader

The record player is really cute and yes, the records do rotate.

The Mini Brands Really Works Vinyl Playset Series 1 by ZURU plays "records" which contain an RFID tag that triggers sound samples held in the player. It is rather fun. I wondered if I could read the tags and identify the records using a PICO. Turns out that I can. I’ve created a tiny MicroPython program that talks to an MRFC522 card reader and prints out the tag number and track details of each record that you show it. You can find the code here.

AI has got me learning the saxophone

The ease with which you can get something working using AI has come as a bit of shock to me. Worse still, the solutions it comes up with (and the conversations you can have with it) seem to indicate that it “knows” what it is doing and the code it writes is actually pretty good. Every now and then I catch it out, which is pleasing, but I’m sure that each time this happens something is written down in ledger somewhere and the mistake will not be repeated…..

As someone who spent a lifetime learning how to put solutions together, this is a bit worrying. I’m not sure anyone can do what I do without some of my skills, but I’m going to have to ditch a whole bunch of coding smarts I’ve spent years acquiring and instead spend my time specifying and analysing code and then discussing it with a machine. Ho hum. It was ever thus I suppose. My intimate knowledge of the George III operating system turned out to have a finite shelf life too.

Anyhoo, as a partial antidote to all this I’ve started learning to play the saxophone. AI can learn lots of things, but it is going to be a long time before it can come up with an embouchure like mine. I’m not doing this because I want to create the bad jazz equivalent of fiddling while Rome burns. It’s more that I quite like the idea of being bad at something that can’t be fixed by adding a bit of AI.

Ghosts Movie is worth the trip

Rather than stand out in the cold watching my money go up in flames (which is how I’ve spent quite a few November the Fifths over the years) we thought we’d go and see a move. We saw “Ghosts: the Possession of Button House”. Very enjoyable. If you’ve seen the TV show and know the characters you’ll really enjoy it. And if you haven’t seen the show don’t worry. Everything is nicely explained and when you go home you’ve got the TV shows to look forward too. Good fun.

Download everything at the Hardware Meetup

I’m not sure why it does this, or how it knows, but for the first half an hour of the hardware meetup this week I was unable to do anything much because the laptop was busy downloading updates and updating its search index. It’s as if it goes “I’m away from home and using a mobile for my network connection. This is the perfect time to get busy”. Oh well, a good time was had in spite of me not being able to do much. The next meetup will be on Wednesday 18th of November. I’ll plug the laptop in at home for a few hours before I head out to it.

We are still not in Kansas

AI unreality continues. One of my favourite cameras has decidedly dodgy batteries. You can’t get them any more, so I thought I’d have a go at making my own. This might not actually come to anything, I was interested to see how ChatGPT would get on converting photos into 3D designs.

So, I took a bunch of pictures against a ruled background and then had a bit of to and froing with measurements and hints. After about 20 minutes we came up with the design you can see above, which I 3D printed. It looks like it will fit into the slot in the camera.

This is the design it came up with

I want to stress that I didn’t use any kind of 3D scanner to make this. I did give ChatGPT some measurements and told it that the slot near the contacts was a slot not a bump. But it did everything else. So we are now in a world where you can create a duplicate of a 3D object with nothing more than a camera and some paper with lines on. Strange times indeed.

Instax film holders now on Thingiverse

I was chatting yesterday about the Instax film holders I made a while back and I realised I’d not got around to putting them on Thingiverse, which is where I put my 3D designs. Anyhoo, I’ve fixed that. You can find them here. They let you use Instax Wide instant film in old cameras made for glass slide film. They are a bit of a faff to use. You have to take sheets out of the Instax film cartridge and put them into the holder and then, after exposure, put the sheets back in the holder to be developed in an Instax camera. A lot of work, but the pictures (and the way that you are using a machine from the century before last) makes up for this. You can also find more details of the holders on GitHub here.

Ducks in colour and black and white…

Busy Busy

Me: “So much to do, so little time…
FX: Knock on the door and door opening
Harry: “Hi, I’m Harry the handyman”.
Me: “Great. Can you fix the broken door handle?”
Harry: “Nope”
Me: “Can you fix the puncture in the car tyre?”
Harry: “Nope”
Me: “Can you fix the outside light?”
Harry: “Nope”
Me: “So what makes you think you’re so handy?”
Harry: “Well, I only live round the corner…..”

Actually, I did manage to fix all these today. So no need for Harry.