I’m still baffled by source code I wrote when I was on meth

Apologies to most people reading this who are not programmers. This post won’t make much sense. But I try to avoid drug references on my programming blog, so this belongs here… And also an apology to anyone who saw this post published by mistake the first time, before I added the image.

I still use this monstrosity of a program I wrote a few years ago. I shouldn’t, because it tries to do too many different things in that it was my scratchpad for all new code I learned for a few years, but it works well for some of them, so I use it even though I know it has its quirks. It’s more or less a file browser, image viewer, video and audio player (via Direct Show which is now obsolete), and can do some minor image editing. But mostly it’s an image viewer. It builds and maintains its own cache of thumbnails, which looks kind of like the large icons view in Windows Explorer. Then double-clicking those thumbnails opens the program’s built in image viewer.

Here’s what it looks like:

RomyView

Anyway, one of its quirks is that there’s a bug somewhere in the custom TaskScheduler (I think) and that can have weird effects like hanging the whole application after deleting a directory. (Sometimes.) So while looking at all the code that references my own TaskSchedulers, I came across this code, written while I was super duper high…

/// <summary>Load a Shell thumbnail image and add it to the cache.</summary>
public static async Task<ThumbnailCacheItem> LoadAndCacheThumbnailAsync(string path, CancellationToken token, bool requiresCurrentDirectory = false)
{
    var item = ThumbnailCacheItem.Invalid;
    var tcs = new TaskCompletionSource<ThumbnailCacheItem>();
    var isSmallImage = false;
    var failed = false;

    try
    {
        using (CancellationTokenSource cts = new CancellationTokenSource(),
            linked = CancellationTokenSource.CreateLinkedTokenSource(token, cts.Token))
        {
            Action checkCancelled = () =>
            {
                if (requiresCurrentDirectory && !Path.GetDirectoryName(path).EqualsIgnoreCultureAndCase(IO.CurrentDirectory))
                    linked.Cancel();

                linked.Token.ThrowIfCancellationRequested();
            };

            await Tasks.Run(() =>
            {
                checkCancelled();
                var fileSystemInfo = IO.Exists(path);

                if (!fileSystemInfo.Item1)
                {
                    /* Neither a file nor a directory exists. This is possible if it was deleted after this 
                        * method was called but before we got here, and just means we have nothing to do here. */
                    linked.Cancel();
                    linked.Token.ThrowIfCancellationRequested();
                }

                var isDirectory = fileSystemInfo.Item2;
                var isFile = fileSystemInfo.Item3;

                var fileSystemType = isDirectory ? FileSystemType.Directory : FileSystemType.File;

                var isMedia = isFile && IO.IsMediaFile(path);
                var isImage = isFile && IO.IsImageFile(path);
                var isPng = isImage && IO.IsPng(path);
                var isZip = isFile && IO.IsZip(path);
                var isPsd = isFile && IO.IsPsdFile(path);
                var isTextFile = IO.IsTextFile(path);

                Bitmap cacheBitmap = null;
                Bitmap fullsizeImage = null;
                try
                {
                    // For simplicity, we define a small bitmap as one with file size less than 1MB.
                    var isBitmapGlyph = IO.IsBmp(path) && new FileInfo(path).Length < 1024L * 1024L;

                    /* Don't use the shell for icon images. It will
                        * display them with shadows and looks like shit. */
                    if (isFile && IO.IsIcon(path))
                    {
                        // Load the largest icon.
                        using (var iconImage = (new IconFileReader { Filename = path }.FirstIcon).ToBitmap())
                        {
                            if (iconImage == null)
                                throw new FileReadException(string.Format("Error reading '{0}'", path));

                            fullsizeImage = iconImage.Clone() as Bitmap;
                            isSmallImage = true;
                        }
                    }
                    else if (isPng || isBitmapGlyph || isPsd)
                    {
                        /* Also don't use the shell for png images, or gifs, for similar reasons as for icons. */
                        fullsizeImage = ImageFile.OpenBitmap(path);

                        if (isBitmapGlyph)
                            isSmallImage = true;

                        if (fullsizeImage == null)
                            throw new FileReadException(string.Format("Error reading '{0}'", path));
                    }
                    checkCancelled();

                    isSmallImage |= IO.IsGif(path);

                    if (fullsizeImage != null && (isSmallImage || isPng || isPsd))
                    {
                        /* If this is a small image, or if it is likely that conversion to jpeg will
                            * produce a thumbnail of inferior quality, we store the actual image in the
                            * cache, instead of a thumbnail.
                            *
                            * Also, the method to get the thumbnail from the shell below will lose the
                            * transparency for small png images, whereas this way, we will display them
                            * with transparency, even in the thumbnails. */
                        cacheBitmap = new Bitmap(fullsizeImage);

                        if (cacheBitmap.Width > 256 || cacheBitmap.Height > 256)
                            cacheBitmap = cacheBitmap.Resize(256, 256) as Bitmap;
                    }
                    else
                    {
                        cacheBitmap = !isZip ? ShellItemImageFactory.GetImage(path) : Icon.ExtractAssociatedIcon(path).ToBitmap();

                        if (cacheBitmap == null)
                            throw new FileReadException(string.Format("Error reading '{0}'", path));
                    }

                    checkCancelled();

                    if (cacheBitmap != null)
                        item = ThumbnailCache.AddNewCacheItem(path, cacheBitmap, fileSystemType, isSmallImage);
                }
                catch (Exception ex)
                {
                    /* An exception here is not necesarily an error. e.g. It will throw 
                        * if you deliberately delete images as they're being cached. */
                    ex.Log();
                    failed = tcs.TrySetException(ex);
                }
                finally
                {
                    if (fullsizeImage != null)
                        fullsizeImage.Dispose();
                }
                return Task.FromResult(item);
            }, token, TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness).ConfigureAwait(false);

            /* The TaskCreationOptions are critically important here.
                * We do not want to be running on the main thread. */

            if (!failed)
                tcs.TrySetResult(item);
        }
    }
    catch (OperationCanceledException) { tcs.TrySetCanceled(); }

    // Prevent the UI from becoming unresponsive when adding many thumbnails.
    await tcs.Task.YieldTo(uiScheduler);

    return await tcs.Task;
}

That’s the code that adds a new thumbnail object to the thumbnail cache, which is a special kind of object cache where the objects are reused once the configurable size is exceeded, and is also persisted to disk, in my own bastardized binary format.

This code showed up in my search results because I was looking for all references to Tasks.Run, which is not standard code, but that calls my own TaskScheduler instead of the built in one.

And yet, this is good code. It’s not verbose, which is surprising. The code is easy to read and it calls out to loads of extension methods and other complex code. So depending on the file type that it finds, it might decide to cache the actual image directly for small files, use my custom icon reader that reads all icons from an ICO file directly, use my custom image reader that can read all kinds of image files, including PSD (Photoshop files), or invoke the Windows shell interfaces, in code that I also managed to figure out myself (because that shit is not implemented in the dot net Framework), which then uses different interfaces depending on the version of Windows. All in all, this is really good code… better than what I write at work nowadays.

I’m baffled.


Also, I found that the bug has nothing to do with my custom TaskScheduler, because it still happens after all references to it are removed. I’ve given up looking for the bug for now.

Advertisements

About Jerome

I am a senior C# developer in Johannesburg, South Africa. I am also a recovering addict, who spent nearly eight years using methamphetamine. I write on my recovery blog about my lessons learned and sometimes give advice to others who have made similar mistakes, often from my viewpoint as an atheist, and I also write some C# programming articles on my programming blog.
This entry was posted in Addiction, Computer, Methamphetamine, Programming and tagged . Bookmark the permalink.

2 Responses to I’m still baffled by source code I wrote when I was on meth

  1. That’s hilarious. My ex was addicted to meth, and while most of the time he’d just disappear into a black hole and mindlessly watch internet videos for 2-3 days locked in a dark room when he relapsed, once in a while he’d actually have these moments of ‘pure genius’ where he’d see things in a way he never had before. See a situation clearly, or the solution to a problem. Obviously that was the exception to the norm, but every once in a while……

    Liked by 1 person

    • Jerome says:

      Yes, I think it was the same with me. Most of the time I’d be a zombie, and when I tweaked on writing code it would be verbose as I struggled to do even trivial things. That’s why I looked at this and went, WTF… this is good code.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s