Editor/Tileset/TilesetImageRefresh.cs

Internal class that tracks and updates tileset textures dynamically. It periodically scans the file system to reload tileset source images if their files are modified.

File Access
using Editor;
using Sandbox;
using Saandy.Tilemapper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Saandy.Editor.Tilemapper;

/// <summary>Refreshes source images even when no tileset inspector or painter is open.</summary>
internal static class TilesetImageRefresh
{
	private sealed class ImageState
	{
		public string Path;
		public (DateTime Modified, long Length) Observed;
		public (DateTime Modified, long Length) Loaded;
		public Texture Texture;
		public bool Warned;
	}

	private static readonly Dictionary<TilesetResource, ImageState> Images = new();
	private static DateTime _nextCheck;

	[EditorEvent.Frame]
	private static void OnFrame()
	{
		var now = DateTime.UtcNow;
		if ( now < _nextCheck ) return;
		_nextCheck = now.AddSeconds( 0.5 );

		var tilesets = ResourceLibrary.GetAll<TilesetResource>().Where( x => x.IsValid() ).ToHashSet();
		foreach ( var stale in Images.Keys.Where( x => !tilesets.Contains( x ) ).ToArray() )
			Images.Remove( stale );

		foreach ( var tileset in tilesets )
		{
			if ( string.IsNullOrWhiteSpace( tileset.FilePath ) ) continue;
			var path = AssetSystem.FindByPath( tileset.FilePath )?.AbsolutePath;
			if ( string.IsNullOrWhiteSpace( path ) ) continue;

			if ( !Images.TryGetValue( tileset, out var state ) || state.Path != path )
				Images[tileset] = state = new ImageState { Path = path };

			try
			{
				var file = new FileInfo( path );
				if ( !file.Exists ) continue;
				var stamp = (file.LastWriteTimeUtc, file.Length);
				// Wait for two matching observations so an image exporter can finish writing.
				if ( state.Observed != stamp )
				{
					state.Observed = stamp;
					state.Warned = false;
					continue;
				}

				if ( state.Texture != null && state.Texture.IsValid && state.Loaded == stamp )
				{
					// A .tileset reload may have cleared its cache without changing the image.
					if ( tileset.GetTexture() != state.Texture ) tileset.SetEditorTexture( state.Texture );
					continue;
				}

				using var bitmap = Bitmap.CreateFromBytes( File.ReadAllBytes( path ) );
				var texture = bitmap?.ToTexture();
				if ( texture == null || !texture.IsValid ) continue;
				tileset.SetEditorTexture( texture );
				state.Texture = texture;
				state.Loaded = stamp;
				state.Warned = false;
			}
			catch ( Exception e )
			{
				// Keep the previous texture and retry if the source is locked or mid-save.
				if ( !state.Warned ) Log.Warning( $"Could not refresh tileset image '{path}': {e.Message}" );
				state.Warned = true;
			}
		}
	}
}