ImageGlass v10 is a complete rewrite in C# with .NET 11, using Avalonia 12 for cross-platform image viewing and SkiaSharp 4.152.x for high-performance rendering. The primary targets are Windows, macOS, Linux on x64 and ARM64 with AOT (Ahead-of-Time) publishing enabled.
/sourceβ v10 source code (the active codebase; thisCLAUDE.mdlives here). All development happens here./v9β legacy v9 source code (WinForms/.NET, archived).
Default to v10 (
/source). Do not read, modify, or reference the v9 source in/v9unless the user explicitly asks about v9 or requests porting/comparison work.
Key Projects:
ImageGlass.Lib: Core library (net11.0) β UI controls, rendering, codecs, themes, localization, settingsImageGlass.Win32: Windows desktop app (net11.0-windows10.0.19041.0) β entry point with Win32 APIs and platform-specific servicesImageGlass.Linux: Linux desktop app (net11.0) β entry point with Linux-specific servicesImageGlass.Mac: macOS desktop app (net11.0) β entry point with macOS-specific services
- All platform projects (Win32, Linux, Mac) use
PublishAot=trueandPublishTrimmed=truewith trim analyzer enabled. - Win32 project additionally uses
DisableRuntimeMarshalling=trueand CsWin32 code generation. - Avoid reflection-based serialization; use custom JSON converters in
Common/Types/JsonTypeConverters/. - Test AOT builds:
dotnet publish ImageGlass.Win32 -c Releaseproduces a self-contained, trimmed executable.
- Use
Lockfor protecting shared state (notobjectlocks). - Use
InterlockedBoolinstead of plainboolfor concurrent flags. - Use
ConcurrentDictionaryfor thread-safe collections (PhotoManagerindex). - Always check
IsDisposedbefore accessing resources in multi-threaded contexts. - Example:
PhotoManagerusesLock _lockto protect_items,_dict, and_cachedIndexes.
- Use
try/finallyorusingstatements for allSKObjectacquisitions. - Override
OnDisposing()inPhDisposablesubclasses to clean up unmanaged resources. - Example:
MipmapTileCacheevicts withRequestDispose()(neverDispose()) so an in-flight render lease stays valid. - Always dispose
SKImageRefleases when done; useKeepAlive()pattern inMipmapTileCache.
- Respect cache limits:
MipmapTileCachecaps 100 tiles;PhotoManager_CachinghonorsConfig.MaxMemoryCacheInMb,Config.MaxFileSizeCacheInMb,Config.MaxDimensionCache. - LRU eviction is mandatory in tile and photo caches to prevent unbounded growth.
- Hard decode ceiling: no
SKBitmapor rasterSKImagemay exceedint.MaxValuebytes, whatever the free RAM. That is ~536 MP at 4 bpp, ~268 MP atRgbaF16, ~134 MP atRgbaF32. There is no bypass:SKImage.FromPixelsfrom anSKData, a raw pointer, or anSKPixmapall fail at the same boundary, so host-owned-buffer tricks do not help. Both codecs shrink to fit instead of failing (see "Oversized image decode"). - Mark a finished bitmap
SetImmutable()beforeSKImage.FromBitmap(SkiaCodec.ToSKImageNoCopy), otherwise Skia duplicates the entire pixel buffer and doubles peak memory. - Profile memory with large images and GIF animations to ensure caches don't leak.
- Interfaces first in
ImageGlass.Lib/Common/ServiceProviders/*:IFileSearchProvider,IShellProvider,IPrintProvider, etc. - Implementations per platform:
ImageGlass.Win32/Common/ServiceProviders/*:Win32FileSearchProvider,Win32ShellProvider, etc.ImageGlass.Linux/Common/ServiceProviders/*:LinuxPrintProvider,LinuxShellProvider, etc.ImageGlass.Mac/Common/ServiceProviders/*:MacPrintProvider,MacShellProvider, etc.
- Register service providers in each platform's
Program.csbefore app bootstrap. - Avoid platform-specific code in library; use dependency injection via
Core.API,Core.FileSearchProvider, etc.
-
Core Static Hub (
Core.cs,Core_Events.cs): Central event dispatcher and singleton registryCore.AppInstance: App lifecycle & unique instance enforcementCore.Config: Global configuration stateCore.Photos: Photo collection and file searching- Events:
LanguageChanged,ThemeChanged,PhotoUnloaded,PhotoSaved,ColorProfileChanged - Service provider slots:
ShellProvider,PreviewProvider,FileSearchProvider,PrintProvider,API
-
Service Providers (Plug-in Pattern)
- Platform-agnostic interfaces in
ImageGlass.Lib/Common/ServiceProviders/* - Platform implementations:
- Win32:
ImageGlass.Win32/Common/ServiceProviders/* - Linux:
ImageGlass.Linux/Common/ServiceProviders/* - macOS:
ImageGlass.Mac/Common/ServiceProviders/*
- Win32:
- Shared concrete providers in library:
PhotoPreviewProvider,SlideshowProvider,UpdateProvider - Examples:
IFileSearchProvider,IShellProvider,IPrintProvider,IWindowColorProfileProvider,IPhotoPreviewProvider - Registered at startup in each platform's
Program.cs; initialized inApp.xaml.cs
- Platform-agnostic interfaces in
-
Photo & Codec Abstraction
PhotoManager: Thread-safe collection withAvaloniaList<Photo>+ConcurrentDictionaryindex- Codecs:
SkiaCodec(fast SkiaSharp pipeline) andMagickCodec(Magick.NET fallback for obscure formats) - Async loading via
PhotoLoadingOptions+ frame animation support viaSkiaAnimator/AnimatorImpl - Caching:
PhotoManager_Caching.csuses spiral pattern, LRU eviction, memory budgets
-
Viewer & Rendering (
ViewerControl)- Partial classes split by concern:
ViewerControl_Render.cs,ViewerControl_ZoomAndPan.cs,ViewerControl_Events.cs,ViewerControl_Animation.cs,ViewerControl_NavButtons.cs, etc. - High-performance mipmap tile caching:
MipmapTileCachewith LRU eviction for large images (8192Γ8192+) - Gesture recognizers:
PhPanGestureRecognizer,PhPinchGestureRecognizeraccumulate points for smooth interaction - SkiaSharp rendering in
ViewerControl_Render.cs+PhotoRenderer.cs - Navigation buttons:
NavButtonsOverlay(separatePhControloverlay) renders left/right arrow buttons on hover; usesRequestAnimationFramefor frame-rate-independent slide+fade animation; click detection on pointer release (does not interfere with panning); config-bound viaEnableNavButtonsPropertyStyledProperty - Image info overlay:
ImageInfoOverlayControl(a non-hit-testablePhOverlayin the viewer panel) shows theConfig.ImageInfoTagsitems in a bar at the top.MainWindow.Status_ChangedpushesAppStatusInfo.GetItems()into it (the app name is left out). One setting,ImageInfoOverlayMode:Hidden,Always/AlwaysAutoHide(every window),Borderless/BorderlessAutoHide(only while the title bar is hidden,ImageInfoOverlayControl.IsTitleBarHidden: full screen or frameless); auto-hide tracks the pointer on the window with a hysteresis zone and a delayed hide, and a running slideshow (Config.EnableSlideshow) makes every visible mode auto-hide. It is set in Settings > Layout only, with no menu item or hotkey.CoveredHeightis how far the bar reaches, whichMainWindowViewinsets the in-app message by
- Partial classes split by concern:
ImageGlass.Lib/
βββ Common/
β βββ Actions/ # Action definitions
β βββ Commands/ # Command definitions
β βββ AppThemes/ # Theme system: IgTheme, IgThemeColors, AppThemeColors, IgThemeMetadata
β βββ BHelper/ # Static helper methods (see "Reusing Shared Code"): Color, Format, General, JsonEx, Path, ProcessHelper, Sound, Task
β βββ Extensions/ # Extension methods (see "Reusing Shared Code"): Color_Exts, DrawingContext_Exts, ISolidColorBrush_Exts, Point_Exts, Rect_Exts, Size_Exts, SKObject_Exts
β βββ Localization/ # Lang.cs, LangId enum
β βββ Photoing/ # Photo management, codecs, animators
β β βββ Animators/ # SkiaAnimator, AnimatorImpl
β β βββ Codecs/ # Codec pipeline
β β β βββ MagickCodecs/ # Magick.NET fallback codec
β β β βββ Registry/ # CodecRegistry
β β β βββ SkiaCodecs/ # SkiaSharp fast-path codec
β β β βββ SvgCodecs/ # SVG (vector) codec
β β βββ Manager/ # PhotoManager & PhotoManager_*.cs (search, watcher, caching)
β β βββ Photos/ # Photo, PhotoMetadata, PhotoColorProfile, etc.
β βββ Printing/ # Print layouts, layout engine, page renderer, PDF writer, PrintSession (see "Printing")
β βββ ServiceProviders/ # Interface contracts + shared providers
β β βββ AppAPIs/ # App API provider interfaces
β β βββ FileSearchService/ # File search service abstractions
β β βββ Update/ # Update provider abstractions
β β βββ I*.cs # Interfaces (IFileSearchProvider, IShellProvider, etc.)
β β βββ PhotoPreviewProvider.cs
β β βββ SlideshowProvider.cs
β β βββ UpdateProvider.cs
β βββ Types/ # Base classes + shared types: PhReactive, PhDisposable, InterlockedBool, Resx, Const, Hotkey, SKImageRef, Enums, Dir
β βββ JsonTypeConverters/ # AOT-safe JSON converters (see "Reusing Shared Code")
βββ Plugins/ # Native plugin host: PluginRegistry, codec proxies
βββ Settings/ # Config.cs, Config_Static.cs, ConfigMetadata.cs
βββ Tools/ # Built-in & external tool framework
β βββ Builtins/ # ColorPicker, CropImage, FrameNav, ImageResizer, LosslessCompression
β βββ External/ # External tool process management
βββ UI/
β βββ BaseControls/ # Ph* controls (see "Designing UI"): PhControl, PhButton, PhTextBox, PhTextBlock, PhToolButton, PhMenuItem, PhHotkeyPicker, PhGridSplitter, PhVirtualizingUniformPanel, PhCommandPreview, PhSearchBoxControl, PhTableControl
β βββ Gallery/ # Gallery browsing UI (GalleryControl)
β βββ Styles/ # App-wide XAML styles + resource dictionaries (see "Designing UI"); merged in App.axaml
β βββ Toolbar/ # Toolbar UI and model (ToolbarControl)
β βββ Viewer/ # ViewerControl (partial classes by feature)
β β βββ Checkerboard/ # Transparency checkerboard background
β β βββ NavButtons/ # NavButtonsOverlay, NavButtonsInfo, NavButtonClickedEventArgs
β β βββ Renderer/ # MipmapTileCache, PhotoRenderer
β β βββ Selection/ # Selection tools
β β βββ ZoomAndPan/ # Gesture recognizers, zoom/pan math
β βββ Windowing/ # PhWindow, ModalWindow, DialogWindow, PhColorPickerDialog
βββ ViewModels/ # MainWindowViewModel, MainWindowModel, SettingsViewModel
βββ Windows/ # Top-level windows: MainWindow, AboutWindow, SettingsWindow, UpdateWindow, ExportFramesWindow
βββ Main/ # MainWindow_View partial
βββ Print/ # PrintWindow, its view, preview and layout tiles
βββ Settings/ # Settings UI: Controls/, Pages/, Windows/
ImageGlass.Win32/
βββ Program.cs # Entry point, service registration, AOT bootstrap
βββ Properties/ # PublishProfiles
βββ Windows/ # MainWindow32.cs (Win32-specific window)
βββ Common/
βββ ServiceProviders/ # Win32 implementations (Win32FileSearchProvider, etc.)
βββ WinAPI/ # P/Invoke wrappers (Win32*.cs files)
ImageGlass.Linux/
βββ Program.cs # Entry point, service registration
βββ Common/
βββ ServiceProviders/ # Linux implementations (LinuxPrintProvider, etc.)
ImageGlass.Mac/
βββ Program.cs # Entry point, service registration
βββ Common/
βββ Sandbox/ # macOS sandbox helpers
βββ ServiceProviders/ # macOS implementations (MacPrintProvider, etc.)
- Classes inheriting from Control/UserControl: Use
PhControlbase (e.g.,ToolbarControl : PhControl) - View Models: Suffix with
ViewModel(e.g.,MainWindowViewModel : PhReactive) - Async methods: Always suffix with
Async - Codecs/Providers: Prefix with platform/source (e.g.,
SkiaCodec,Win32FileSearchProvider,MagickCodec) - Partial class files: Name by concern (e.g.,
ViewerControl_Render.cs,PhotoManager_Caching.cs,AppAPIProvider_Hotkeys.cs)
Before adding a helper, converter, or extension, check these folders; the utility you need likely already exists.
Extension methods on framework types. Prefer these over re-implementing:
Color_Exts:ToBrush(),WithAlpha(),NoAlpha(),Blend(),WithBrightness(),IsLight(),BlackOrWhite()/InvertBlackOrWhite(),ToHex(),ToRgbaString(),ToCmyk()/ToCmykString(),ToHslString(),ToHsvString(),ToCIELAB()/ToCIELABString()ISolidColorBrush_Exts,DrawingContext_Exts,Point_Exts,Rect_Exts,Size_Exts: Avalonia geometry & drawing helpersSKObject_Exts:IsDisposed()and other SkiaSharp guards
Color.cs:ColorFromHex()Format.cs:FormatSize(),FormatDateTime(),SimplifyFractions(), star-rating formattingGeneral.cs:OS,GenerateWrappedIndexes()(spiral cache order),ComputeIndexInRange(),ResizeRatio(),GetInAppError()Path.cs:ConfigDir()/BaseDir(),ResolvePath(),CheckPath(),OpenUrlAsync(),OpenFilePath()/OpenFolderPath(),DeleteFile()ResolvePath()is the single public path normalizer: it unwrapsig://, strips quotes, expands env vars, follows.lnkand macOS.app, then makes the result absolute. Never add a second normalizer beside it; if a caller needs only part of that, make the missing piece aprivatehelper insideResolvePathrather than a parallel public API.
ProcessHelper.cs:RunExeAsync()/RunExeCmd(),RunSync(),ExitApp()Sound.cs:PlayNotificationSoundAsync()(extracts the bundledAssets/Sounds/notification.wavto_temp, then plays it via NetCoreAudio on Windows/macOS, or a probed CLI player on Linux)JsonEx.cs:CreateJsonOptions(),ReadJsonFromFile()/WriteJsonToFileAsync()(AOT-safe viaJsonTypeInfo<T>); both go throughFileIO.cs, so every JSON file is multi-instance safeFileIO.cs:OpenReadShared()/WriteAllTextSharedAsync(), the multi-instance-safe file primitives (see "Concurrent file writes")Task.cs:Debounce(),GcCollect()
AOT-safe converters for Config serialization. Reuse an existing one, or add a new converter here; never use reflection-based serialization.
JsonStringEnumSafeConverter<T>(always use for enums; never the built-inJsonStringEnumConverter)JsonStringToHotkeyConverter,JsonArrayToZoomFactorConverter,JsonArrayToRectConverter/JsonArrayToPixelRectConverter,JsonArrayToDoubleConverter/JsonArrayToIntConverter,JsonDateTimeConverter,JsonHashSetToStringConverter,JsonObservableCollectionToStringConverter
When building or restyling UI, reuse the app's existing controls, design tokens, styles, icons, and fonts instead of raw Avalonia controls or hardcoded values.
- Base controls (
UI/BaseControls/, all inheritPhControl):PhButton,PhTextBox,PhTextBlock,PhToolButton,PhMenuItem,PhHotkeyPicker,PhGridSplitter,PhVirtualizingUniformPanel,PhCommandPreview,PhTableControl(read-only data table: aligned auto-fit columns + hover/focus-revealed icon-button actions; use for settings tables),PhOverlay(floating surface in the in-app message style: setIsShownto fade it in or out,TransitionDirectionpicks the side it slides in from,Autofades in place; place it withMargin/Padding/alignment;MessageOverlayControl,ImageInfoOverlayControlandMotionPhotoOverlayControlderive from it). - Windows & dialogs (
UI/Windowing/): inheritPhWindow; for modal/dialog flows useModalWindow/DialogWindow; usePhColorPickerDialogfor color picking. - Feature controls:
ViewerControl(UI/Viewer/),GalleryControl(UI/Gallery/),ToolbarControl(UI/Toolbar/).
- Themed resources via
Resx/ResxId(Common/Types/Resx.cs): resolve in XAML with{DynamicResource <ResxId-name>}, or in code withResx.Get<T>(ResxId.X)/Resx.CreateBinding(ResxId.X). The resource name equals theResxIdenum name. These keys are populated at runtime by theUpdate*methods inCore.cs(UpdateBaseResources,UpdateAppThemedColorResources,UpdateViewerBackgroundBrushResource,UpdateAccentColorResources; seeCore.cs:387-635). To add a new themed value: add aResxIdentry and set it inside the matchingUpdate*method. - Brush vs Color:
ResxIdkeys ending inBrushresolve to anIBrush; keys ending inColorresolve to aColor. Use the*Colorvariant where aColoris required (e.g.GradientStop.Color). - Theme & situational colors (
Common/AppThemes/AppThemeColors.cs): the static source of truth for text success/warning/danger, situational backgrounds, and window backgrounds. TheUpdate*methods deriveResxresources from these, so reuse them rather than duplicating hex literals.IgThemeColors.csis the per-theme-pack color model. - Shared styles & tokens (
UI/Styles/, merged inApp.axaml): control styles (ButtonStyle,TextBoxStyle,ComboBoxStyle,CheckBoxStyle,RadioButtonStyle,MenuStyle,SliderStyle,ListBoxItemStyle,ControlStyle) and resource dictionaries (CommonResources,MenuResources,ComboBoxResources,ScrollBarResources,IconResources). Reuse tokens fromCommonResources.axaml:ControlCornerRadius(7),OverlayCornerRadius(10),PhAccentFill/PhAccentFillPointerOver/PhAccentFillPressed, and the shared disabled palette (PhControlFillDisabled,PhControlGlyphDisabled,PhControlBorderDisabled,PhControlContentOpacityDisabled,PhSvgCssDisabled).
Reuse the StreamGeometry icon resources via {StaticResource IconName}: IconSearch, IconSettings, IconSave, IconSaveAs, IconCrop, IconCopy, IconReset, IconClose, IconEllipsis, IconArrowPrevious / IconArrowNext / IconArrowLeft / IconArrowRight, IconPlay, IconPause, IconImageForward, IconLivePhoto, IconFolderOpen. In code-behind, resolve the same geometries with Resx.GetIcon(ResxIconId.X) (enum name equals the resource key). Add new icons here as StreamGeometry and add a matching ResxIconId entry in Resx.cs. Platform stock icons (window/system bitmaps) come from Resx.GetStockIcon(StockIconId.X) / Resx.GetDefaultWindowIcon().
- Font family:
Const.FONT_CODE(OS-specific monospace stack for code / credits / metadata text). - Font sizes:
Const.FONT_SIZE_BODY,FONT_SIZE_TITLE,FONT_SIZE_SUBTITLE,FONT_SIZE_SMALL. Reference in XAML via{x:Static types:Const.FONT_SIZE_SMALL}(withxmlns:types="using:ImageGlass.Common.Types"); do not hardcode sizes.
- All ViewModels inherit from
PhReactive : INotifyPropertyChanged - Thread-safe property change notifications using
Lock(notobject) - Use with Avalonia compiled bindings:
{CompiledBinding PropertyName} - Example:
public class MainWindowViewModel : PhReactive { public string Title { get; set { if (field.Equals(value)) return; field = value; OnPropertyChanged(); } } = BHelper.AppName; }
- Inherit when managing unmanaged resources (SKImage, file handles, etc.)
- Override
OnDisposing()(called on Dispose, not destructor) - Uses
InterlockedBool _isDisposedfor thread-safe disposal checks - Use with
await usingin async contexts - Example:
public sealed class MipmapTileCache : PhDisposable { protected override void OnDisposing() { lock (_lock) { foreach (var bitmap in _tiles.Values) { bitmap.Dispose(); } _tiles.Clear(); } } }
- Use instead of
boolfor concurrent state flags - Atomic read/write using
VolatileandInterlockedoperations - Example:
_isPreviewing,_isFirstDraw,_isDisposedin ViewerControl - Check with
.Valueproperty or implicit conversion
- Always check
SKObject.IsDisposed()before using SkiaSharp objects - Defined in
ImageGlass.Common.Extensions.SKObject_Exts - Returns
trueif object isnullorHandle == IntPtr.Zero - Example:
if (_skImage.IsDisposed()) { _skImage = null; }
# Restore and build
dotnet build
# Publish AOT-enabled binary (ImageGlass.Win32)
dotnet publish ImageGlass.Win32 -c Release -o ./bin/publish
# Run from source
dotnet run --project ImageGlass.Win32 -- [image_path] [additional_args]- Open solution in Visual Studio 2026
- Set
ImageGlass.Win32as startup project - Breakpoints work normally in C# code
- Avalonia Hot Reload: Available with
--debugflag (limited to XAML/styles) - Profiling: Use Visual Studio's memory profiler for cache leak detection
- No dedicated test projects in v10 (focus on functional validation)
- Manual testing via
dotnet run - Test command-line parsing with sample images
- Profile memory usage with large images and GIF animations
- LangVersion:
Preview(C# 15 features available) - Features:
runtime-async=onin all projects (a .NET 11 preview, NativeAOT-supported):async Task/ValueTaskmethods compile to runtime-async methods instead of<X>d__Nstate machines;async voidand async iterators still use the compiler's. Remove it from all four projects to fall back. - Nullable:
enableacross projects - AllowUnsafeBlocks:
true(for P/Invoke, SkiaSharp interop) - PublishAot:
truein all platform projects (Win32, Linux, Mac) - PublishTrimmed:
truein all projects (library + platform) - PublishSingleFile + SelfContained + PublishReadyToRun:
truein all platform projects - DisableRuntimeMarshalling:
truein Win32 only (AOT-safe marshalling)
App.Initialize()
β Core.InitializeAsync()
β PhotoManager.Add/SearchAsync()
β ViewerControl.LoadPhotoAsync(photoPath)
β Codec.DecodeAsync() (SkiaCodec or MagickCodec with fallback)
β shrink to fit the pixel ceiling if needed β Photo.DecodeScale
β PhotoRenderer.RenderAsync()
β AnimatorImpl for GIF/WEBP animation
β PhotoLoading/PhotoAnimatorFrameChanged events
β MipmapTileCache.Create() if image > 8192Γ8192
- Images past the
int.MaxValue-byte ceiling are decoded smaller rather than refused. - Skia (
SkiaCodec.GetDecodableImageInfo): steps down through the codec's native scales, JPEG eighths largest-first. Non-JPEG codecs cannot scale and throw a readableNotSupportedException. - Magick (
SkiaCodec.FromMagick): resizes in place to fit, so it lands closer to the ceiling than Skia can. Callers must be handing over an image they are about to discard. - The reduction flows
SkiaDecoderOutput/MagickCodecAdapterβCodecDecodeResult.DecodeScaleβPhoto.DecodeScale, andAppStatusInfo.Dimensionshows it. Photo.SizeandViewerControl.BitmapSizefollow the DECODED size so zoom, selection, crop, and the color picker stay consistent; onlyPhoto.Metadata.Width/Heightkeep the true file dimensions.
- A multi-size
.ico/.curopens on its largest frame (then deepest color, then first).MagickCodecpicks it intoPhotoMetadata.DefaultFrameIndexfrom the frames it already pinged, and the metadataWidth/Heightdescribe that frame so the preview and its zoom match the final image. - Built-in Magick only. The index is in Magick's frame order (the ICO directory order), and WIC numbers ICO frames differently, so
Photo.GetDefaultFrameIndex()returns 0 unless the decode codec isCodecRegistry.FallbackDecodeCodec. Plugin-decoded icons open on frame 0; no ABI change. ReadOptions.FrameIndexis the frame a load opens on:LoadAsync__re-points it once metadata is loaded, and bothFromConfigresets (ViewPhotoAsync, the prefetch) passGetDefaultFrameIndex(), because a cached photo is shown with no decode and Save As writesReadOptions.FrameIndex.ApplyDecodeResultmust record the decoded frame in_frameIndex: the viewer asksGetFrameAsync(Math.Max(0, FrameIndex)), so a missing index decodes and shows frame 0 again.
- Change language:
Core.LanguageChanged?.Invoke() - Change theme:
Core.ThemeChanged?.Invoke(new ThemePackChangedEventArgs(...)) - UI elements auto-refresh via bindings + event subscribers
Occurs in Program.cs before Avalonia app setup (Linux/Mac have equivalent registrations):
FileSearchProvider(shell enumeration in the view order of File Explorer or a supported third-party file manager; see "Explorer sort order & the foreground shell")ShellProvider(context menu, file properties, Windows Share API)PrintProvider(GDI printing through the spooler; Print Pictures as the system dialog; see "Printing")ColorProfileProvider(Monitor color profile retrieval via Win32 APIs)PreviewProvider(thumbnail cache via Windows shell)
Config.cshandles JSON serialization with custom converters- Converters in
Common/Types/JsonTypeConverters/(e.g.,JsonStringToHotkeyConverter,JsonArrayToZoomFactorConverter) - Cached in
AppData\Local\ImageGlass\, or the startup dir in portable mode (see below) - Async save via
Config.SaveAsync()
- Every instance writes the same
igconfig.json, and closing a taskbar group closes them all at once, so a plainFile.WriteAllTextAsyncloses the race with a sharing violation. All JSON writes therefore stage into<path>.<pid>.tmpand rename over the target, guarded by a per-pathSemaphoreSlim(two windows of one process) plus a bounded retry. File.Move(overwrite: true)is only atomic while no one holds the target for writing. Held, it degrades into an in-place copy, and a concurrent reader then sees a truncated file. That is whyOpenReadSharedasks forFileShare.Read | FileShare.Delete:Deletelets the rename proceed under an open handle, and withholdingWriteis what keeps the swap a rename. Measured over ~166k reads:ReadWritegave 878 truncated reads,Readgave 0.File.Replaceis not the fix, despite being the usual advice: it leaves~RF*.TMPlitter, and the target name briefly does not exist mid-call, which makes a concurrent reader and a concurrent writer fail withFileNotFoundException.Config.SaveAsyncnever throws: it returnsfalseand recordsConfig.SavingException, because it is reached fromasync voidclose handlers and a fire-and-forget save inSettingsWindow.OnClosing, where an escaping exception is an unhandled-exception dialog on a window that is already closing. Every path the user explicitly triggered still reports the failure (ModalWindow.ShowSettingsSaveErrorAsync, or a throw out ofIG_ApplySettings); only the two close paths stay silent, andQuickSetupWindowadditionally refuses to restart, since the restart would reload the unwritten file and discard every choice.- Last writer wins is unchanged and intended: each instance persists its own whole
Config.
- A
.igportablemarker file (Const.PORTABLE_MARKER_FILE) in the startup dir moves the whole config dir there:BHelper.ConfigPathreturnsBasePathinstead of%LocalAppData%\ImageGlass, soigconfig.json,_cache,_logs,_plugins,_lang,_themesall live next to the exe and the folder can be relocated without losing settings. ConfigModeonly answers which mode (IsPortable, resolved once per process on first access);BHelper.ConfigPathstays the single accessor that turns that into a path, so every existingConfigDir()caller follows automatically. Never expose a second config-path property, and never re-read the marker at a new call site.- The marker must be resolved before anything touches the config dir, so
App.InitializeAppInstanceforces it (trace markInitInstance:portableMode) ahead ofLicenseService.LoadActiveandConfig.Load. - A marker in a non-writable startup dir is fatal, never a fallback.
ConfigMode.PortableErrorholds the raw exception from a single create-probe (a per-process temp file, never the marker itself),App.OnFrameworkInitializationCompletedshows it (real message +GetExceptionDetails) and quits before creating the main window, andConfig.SaveAsyncrefuses to write. Falling back to%LocalAppData%would hide the portable settings behind a second config. ConfigDir()swallows directory-creation failures on purpose: a read-only config dir must not throw out of a path getter, or startup crashes before it can report the real problem.- Shipped by the ZIP packer only (
__assets/win/script-pack-win-zip.ps1,-NoPortableto omit). Never add it to__assets/__app: the MSIX payload folder is read-only, so a packaged build would refuse to start.
- Same shared pipeline as the sideload MSIX (Pro, download-now/install-on-click, sha256), with artifacts
linux-<arch>-appimageandlinux-<arch>-flatpak. The tarball stays check-only. - AppImage: two renames in the image's own folder, never an in-place write. The running session reads its FUSE mount through the old inode, so a truncating write corrupts it. The path is kept, so launchers and associations still resolve. Supported only when that folder is writable.
- The relaunch is also a probe. If the new process exits non-zero within
RELAUNCH_PROBE_MS, the old image is renamed back. An AppImage runs on the host glibc, so a release that raises the floor would otherwise leave an install that cannot even report the failure. A session started with--appimage-extract-and-runrelaunches withAPPIMAGE_EXTRACT_AND_RUN=1, or a FUSE-less host fails a healthy build. - Flatpak: bundle installs only. A bundle's origin (
imageglass-origin) has no URL, soflatpak updateanswers "Nothing to do."; the new.flatpakgoes throughflatpak install --bundleon the host instead. An install from a remote with a URL (Flathub, or the dev installflatpak-builder --installmakes) stays check-only: a bundle over it keeps that origin but deploys a commit the remote lacks, and the nextflatpak updatecan downgrade it. - Host
flatpakcommands target the installation the app runs from, read from/.flatpak-infoapp-path(--systemfor/var/lib/flatpak, else--userplusFLATPAK_USER_DIR), and need--talk-name=org.freedesktop.Flatpak. Never pass--noninteractive: it also suppresses the polkit prompt a system installation needs. Exit code 0 proves nothing (Nothing to do.is 0), so success means the deployed commit changed. - The new instance must start on the host (
flatpak-spawn --host flatpak run); a child inside the sandbox dies with it. Both formats releaseCore.AppInstancefirst, or the new process hands its launch to the exiting one, and they clear the pending update before relaunching, or the old instance's close-time save re-arms it. - The install-while-alive helpers (
RunInstallThenExitAsync,RelaunchAsync,ForgetInstalledUpdateAsync,RunCommandAsync) live in the baseUpdateProvider, shared with macOS.
- Same shared pipeline, artifact
mac-<arch>-dmg(only arm64 is published, so an Intel build stays check-only). Supported only when running as<name>.app/Contents/MacOS/<exe>with the bundle and its folder passingaccess(W_OK): a loose dev binary, a Gatekeeper-translocated copy, the DMG volume itself, or a non-admin's/Applicationsstay check-only. - The DMG is mounted privately (
hdiutil attach -nobrowse -readonly -mountpoint $TMPDIR/β¦), its root.appisditto'd beside the running bundle, then swapped in by two renames, never copied over: this session keeps reading its files through the renamed bundle, and the path (Dock, Finder, associations) is unchanged. A renamed bundle still validates, so the hidden.<name>.app.<pid>.newsibling is checked in place. - The staged copy must satisfy the running app's own designated requirement (
MacCodeSignApi, Security.framework with thecodesign --verify --deep --strictflags): same identifier, Developer ID, same team.HttpClientdownloads carry no quarantine, so Gatekeeper never assesses the new app; this check stands in for it. An ad-hoc dev build has no team to pin and only demands a valid signature. A rejected package is discarded. - The relaunch starts the new binary directly and doubles as the probe (
RELAUNCH_PROBE_MS); an early non-zero exit renames the old bundle back.IsMeteredConnectionis not implemented on macOS (alwaysfalse).
- Effects are written only in gl-transitions GLSL (
vec4 transition(vec2 uv)withgetFromColor/getToColor/progress/ratio), built-ins included. SkSL is a backend detail:GlTransitionsAdaptertranslates GLSL to anSKRuntimeEffect(GPU through Avalonia's Skia lease, CPU raster without aGRContext, AOT-safe since the source is a string). Avalonia plans to move from Skia to Impeller, so never let SkSL leak into an effect file; an Impeller port replaces the adapter, not the effects. - The adapter's inputs are a frozen contract: only add, never rename or remove, or every shipped and user effect breaks. On top of gl-transitions it adds
resolution(logical px) andnavigationDirection(1 forward, -1 backward); it is notdirection, which real gl-transitions effects already declare as a parameter.PhotoRenderersets an input only if the shader declares it, so a new input is backward compatible. The adapter also renames a barehalf, a plain GLSL name that SkSL reserves as a type; add any other SkSL-only keyword the same way if an effect trips over it.ToSkSLnormalizes line endings before any regex: gitautocrlfchecks effect files out as CRLF, a multiline$matches only before, and the default-value regex once silently skipped every CRLF file, so Wipe/Dissolve/Circle ran with their parameters at 0 (only in published builds, whose payload came from the CRLF working tree). - No effect is compiled in. An effect is a
*.igtransition.glslfile (id = the name before that suffix; any other file is ignored); only Fade, Circle, Dissolve, Wipe and Push ship, in__assets/__app/_transitions. The rest live in__assets/transitions(not packaged) for download from https://imageglass.org/effects, the "Get more effectsβ¦" link.TransitionEffectsreads the config dir_transitionsfirst, then the base dir one, and the first file of an id wins, so a user file overrides a shipped one. - After any SkiaSharp upgrade, check every shipped effect by hand (select it in Settings, then navigate): a broken effect never crashes the app, it silently stops playing, and Settings only shows compile errors, not an effect that compiles but renders wrong.
- Only
AppAPIProvider.ViewByStep__creates aTransitionRequest(skipped whileIsQuickBrowsing); it travels inPhotoLoadingOptions.Transition, andSetPhotoAsyncmust callBeginTransitionbeforeUnloadPhoto, because the old frame is recorded as anSKPicturewhose native refs keep the old images alive after unload. - The viewer holds the old frame until the new photo has something to draw (
MAX_TRANSITION_HOLD_MS), which also hides the preview flash.PhotoRenderer.RenderTransitionthen renders both sides (image layer only; the checkerboard stays the viewer's own layer beneath) into per-frame offscreen surfaces and blends them through the shader; per-frame surfaces keep every GPU object inside the render call, never across threads. - Every path must complete the request (
TransitionRequest.Complete): the slideshow awaitsCompletionbefore counting the next interval (SlideshowProvider.WaitForAdvanceAsync, bounded byMAX_ADVANCE_WAIT_MS). A new navigation snaps the running transition, and one still holding hands its old frame over (TakeFromFrame). - A mirror (projector) plays the same transition through its own viewport.
BeginTransitionraisesTransitionStartinginside the source lock, beforeUnloadPhoto, so each mirror records its own old frame (CaptureMirrorFrame) while the old images still exist, then runs its own clock. It plays a copy of the request, because only the source's request may tell the slideshow the effect ended. A mirror's_transitionis guarded by the source's lock (TransitionLock), the one its renderer draws under; a second lock there would deadlock against the render thread.
- Full screen is destructive: it writes the hidden toolbar/gallery and clears frameless/window fit straight into
Config. So the layout to come back to lives in oneWindowLayoutSnapshot(AppAPIProvider._preFullScreenLayout), captured byMainWindow.CaptureWindowLayout()before anything else in the enter branch runs. - Invariant:
Config.ShowToolbar/ShowGallery/EnableFrameless/EnableWindowFit/EnableMainWindowMaximized/MainWindowBoundsalways describe the windowed layout;EnableFullScreenis the one orthogonal flag.SaveConfigOnClosingAsyncenforces it by persistingCore.API.PreFullScreenLayoutinstead of the live values whenever a session ends in full screen. - Startup must enter through
IG_ToggleFullScreen(true), never a rawWindowState = FullScreen: the raw assignment captures nothing (so leaving full screen restored hardcoded defaults) and skips theShowToolbarInFullscreen/ShowGalleryInFullscreenhide policy. Full screen is also checked before window fit, since both can now be saved astrue. - Any new path that reaches
WindowState.FullScreenmust capture the snapshot (seeStartSlideshow__) and null it out when it leaves (seeStopSlideshow__), or the close-time save persists a stale layout. - The close handler reads
RestorableWindowState, notWindowState: closing a minimized window would otherwise recordEnableFullScreen/EnableMainWindowMaximizedas false. - Leaving full screen defers the window-fit recompute through
Dispatcher.UIThread.Post, becausePhControl.IsContentVisibleposts the real visibility change andApplyWindowFitModemeasuresToolbar.Bounds/Gallery.Bounds.
- Tier 1: Current photo in viewer (always loaded)
- Tier 2: Neighboring photos preloaded via
PhotoManager.RequestCacheAround() - Tier 3: LRU eviction when memory budget exhausted
- Spiral pattern: right-1, left-1, right-2, left-2, ... to balance browsing directions
- A decoded photo must never be reachable only through
_cachedIndexes.RunCacheAroundAsyncregisters an index the momentLoadAsyncreturns, before the cancel check, because a photo that is decoded but untracked escapes bothEstimateCachedMemoryand eviction, and is then never freed for the process lifetime. Rapid navigation cancels a pass on every step, so this is the common path, not the rare one; it once held an entire 80-photo folder (3.6 GB) against a 1000 MB budget. - Eviction is authoritative over the whole list, not over the tracked set.
UnloadPhotosOutside(keepIndexes, excludePhoto)walks every item and unloads anyPhotoState.Loadedphoto outside the keep set, whatever decoded it, so the pass self-heals regardless of how a photo became loaded.centerIndexandCurrentIndexare always kept (the viewer owns the shown photo).ClearCache(excludePhoto)is the same sweep with an empty keep set, which is what makes a plugin unload safe: an orphaned photo still holding a plugin buffer would otherwise outliveNativeLibrary.Free. - The budget accumulates from the spiral, not from
_cachedIndexes. The pass seedsusedMemorywith the current photo alone and adds each already-decoded photo as the spiral re-visits it; seeding from the tracked set double-counts every re-adopted photo and breaks the loop early. - A
LoadAsyncthat returns without raisingLoadedis a blank viewer, not a no-op.SetPhotoAsyncdisposes the old image up front, and nothing else re-invalidates, so a silent return leaves the photo black until the user navigates away and back. Hence: loads are serialized perPhotoby_loadGate(the prefetch pass and the viewer both load the same file, and cancelling the one in flight is what produced the silent return); a cache hit dispatchesLoadedthroughDispatchLoadedAsyncinstead of just returning;_cancelEpochstill drops a load cancelled while queued;ViewerControl.RecoverIfNothingRenderedAsyncis the backstop for every remaining path, andPhotoRenderer.ReturnFirstDrawClaimhands back a first-draw claim whose frame never rendered. UnloadPhotosOutside(..., keepCurrent: true)re-readsCurrentIndexper item, because the sweep is long enough for the user to navigate onto an index the keep set was built without.ClearCachedeliberately leaves it off; it must be able to free every photo before a plugin unload.- The pass also color-manages each neighbour ahead of its view (
Photo.PrepareDisplayFrameAsync, keyed by aDisplayColorPassholding every input of the pass), so a cached view skips the HDR tone map and the monitor-profile conversion; the budget pays for the extra frame (Photo.DisplayFrameBytes). The viewer'sTakeDisplayFrameAsyncalso claims the frame, after which the viewer may free it, so no cache pass reads it again; both run under the photo's_displayFrameGate, whichOnDisposingholds while it frees the bitmap. Any new background reader ofPhoto.Bitmapneeds that gate, and multi-frame photos are skipped because a page switch frees the frame.ViewPhotoAsynccancels the running pass first, so a navigation's load never competes with the old neighbourhood.
FileSearchProvider.EnumerateFileEntriescapturesFileInfo(size, timestamps, attributes) during enumeration into aFileSearchEntry, andPhotoManager.Add(IEnumerable<FileSearchEntry>)buildsPhoto/PhotoMetadatafrom it, so no per-file re-stat. On Windows those fields come free fromWIN32_FIND_DATA; on Unix they cost onestat, still fewer than before.PhotoMetadata(FileSearchEntry)deliberately skipsSetFilePath__(which re-stats). It is a partial fill:IsOutdated()stays true until a codec loads real image metadata, so the capture defers the codec metadata load rather than replacing it.- Enumeration emits
FileInfo.FullName, i.e. absolute paths, andPhotoManager.IndexOfis an exact-stringConcurrentDictionarylookup (OrdinalIgnoreCase). Every path enteringStartLoadingFilesmust therefore pass throughBHelper.ResolvePathor the init photo never resolves to a list index (gallery shows nothing selected, navigation starts from -1). FileSearchingEventArgs.Resultsis a materializedIReadOnlyList, and filtering/sorting now run on the background thread instead of lazily on the UI thread duringAdd.- The Win32 override publishes progress through
Dispatcher.UIThread.Postwith a token re-check inside the posted lambda, which is what serializes a stale batch againstPhotoManager.Clear(). The base provider (Linux/macOS) still invokesprogressFndirectly on the worker, so that race remains open there.
- The list has three possible sources, tried in order by
Win32FileSearchProvider.SearchAsync: the foreground view captured at launch (IShellProvider.ForegroundShell, whenCanUseForegroundShell()allows it), then, withEnableExplorerSortOrder, an opening view that shows the folder (EggShell.FindOpeningView(dir, includeDesktop: true)), then plain enumeration sorted byImageLoadingOrder. A view only decides which files are listed and in what order:FindFiles_WithShellstill enumerates the folder for metadata and drops folders, hidden files and unsupported extensions. CanUseForegroundShell()gates the foreground view. A search result (asearch-ms:path or a saved.search-ms) always uses it, since that list exists nowhere else; a plain folder only when it is the opened file's own folder andEnableExplorerSortOrderis on. The foreground window is read once inApp.OnFrameworkInitializationCompleted(and again for a single dropped file), before the main window shows, so a launch from a terminal or script sees that window, not the file manager.- ImageGlass only ever sees EggShell's
ShellAppView:GetTabViewPath()andGetTabViewItems()(full paths in view order;nullwhen unreadable, which falls back to a plain search of that folder). File Explorer and the desktop areExplorerView; each supported third-party file manager is an internal EggShell class behindIShellApp. Support for another file manager goes into EggShell (oneIShellApp+ view registered inEggShell._shellApps), never into ImageGlass. - Third-party file managers have no folder view in the Explorer window list, so EggShell reads each one through its own app-specific interface. That lookup is not free: some of them answer through a helper process, which costs tens of milliseconds per query.
- Views wrap cross-process COM proxies, so use them on the UI thread: step 1 and the per-folder search post
FindFiles_WithShellto the UI thread, and the step-2 lookup runs insideDispatcher.UIThread.InvokeAsync. - A shell failure must never fault
SearchAsync.StartLoadingFilesdiscards its task, so an exception there becomes an empty photo list plus an unobserved-task dialog; a third-party file manager whose shell browser answersQueryActiveShellViewwithE_NOTIMPLcaused exactly that. The step-2 lookup catches everything and falls back to the plain search, and EggShell's view methods catch every exception: a third-party shell can fail with any HRESULT, and the generated COM stubs map the common ones to non-COMExceptiontypes (E_NOTIMPL->NotImplementedException,E_NOINTERFACE->InvalidCastException). - EggShell is a separate repo shipped as the
D2Phap.EggShell-x64/-ARM64packages (pinned inDirectory.Packages.props), so an EggShell API change compiles in ImageGlass only once the new package is published.
- Tiers in order, all skipped when
useCacheis false: in-memoryGalleryThumbnail,ThumbnailDiskCache,IPhotoPreviewProvider.TryGetCachedThumbnailAsync(platform cache), thenGetThumbnailAsync(decodes). - Both cache tiers run before
LoadMetadataAsync; that ordering is the whole point, since neither may read the source file.ThumbnailDiskCache.TryGetAsynctherefore validates against theMetadata.FileLastWriteTimeUtccaptured at enumeration, not a fresh stat, so an out-of-band edit is corrected by the file watcher rather than by the cache check. _galleryThumbnailRequestSizekeys the in-memory thumbnail to the size it was produced for, so a DPI orConfig.ThumbnailSizechange reloads instead of serving a stale size.- Shrink whatever a cache returns to
thumbSizeviaSkiaCodec.ScaleDownbeforeToWritableBitmap. The Windows Shell hands back whole cache tiers (96/256/768/1920), and retaining one costs MBs of gallery memory per photo. Keep the original cached image as the size authority forIsPreviewLargeEnoughand the too-small check. - Never nest a process-wide gate inside this call. The caller already holds a
_thumbnailThrottleLockslot, so a second semaphore parks threads while they hold a slot and collapses the gallery to one photo at a time. - The throttle is sized by the cache budget, not the core count:
clamp(CacheMaxMemoryInMb / MB_PER_THUMBNAIL_SLOT, 4, clamp(ProcessorCount-1, 4, 16)), lazily so it reads the loaded config. A cache miss decodes the full image before shrinking it, so each slot can transiently hold one full-resolution bitmap; CPU-only sizing let 16 concurrent 4K decodes outweigh the entire photo-cache budget on a many-core machine. TryGetCachedThumbnailAsyncmust not decode: Win32 implements it withSIIGBF_INCACHEONLY, and the base returnsnull, so Linux/macOS have only the disk tier. PassskipPlatformCachedown toGetThumbnailAsync/GetPreviewAsyncwhen the caller already probed, or the same shell query runs twice per photo.GalleryThumbnailis assigned on the UI thread (ShowGalleryThumbnailAsync) because the compiled binding writesImage.Sourceon whichever thread raisesPropertyChanged.
- The display profile is applied at two points; never let both hit the same pixels:
- Decode-time (Magick only):
MagickCodec.ProcessMagickImage__()bakes it viaTransformColorSpace; runs only whenMagickCodecAdapterdecodes (Skia decode applies no profile). - Viewer-time (Skia):
ViewerControl.ApplySkiaColorSpaceAsync()(HDR tone-map + SDR ICC), applied inHandlePhotoLoadedAsync(). The pass itself isDisplayColorPass.Apply(), which the cache pass also runs ahead of time, so a cached view usually just takes the prepared frame (see "Photo Caching Strategy").
- Decode-time (Magick only):
- CMYK profiles:
SKColorSpace.CreateIcc()returnsnullfor CMYK βCore.IsDestColorProfileSupported=falseβSkiaCodecAdapter.CanDecoderefuses β Magick decodes.ProcessMagickImage__must never output CMYK pixels (they render inverted): castrefImgM.ColorSpace = ColorSpace.sRGB(keeps the print-like tint; do not ICC round-trip, it over-brightens). - Codec-selection cache:
Core.UpdateDestColorProfile()callsCodecRegistry.InvalidateSelectionCaches()and always firesColorProfileChanged. Without the invalidation, a CMYK choice leaves.jpgstuck on Magick ("sticky downgrade") and every later profile double-applies (brighter/over-saturated until restart). - On change:
Core_ColorProfileChanged()re-decodes the current photo viaSetPhotoAsync(photo, { ResetZoom = false, UseCache = false })β re-applies cleanly while keeping zoom/pan; never transforms_imgSourcein place.ColorProfileis intentionally NOT inSettingsViewModel.reloadPhoto(a generic reload would reset zoom). - Monitor change vs settings change:
UpdateDestColorProfile(requiresPhotoReload)carries the intent throughDestColorProfileChangedEventArgs. The monitor-profile provider passesfalse(dragging the window between monitors must not flash the viewer, matching theSettings_CurrentMonitorProfile_Descriptionnote); the settings page uses the defaulttrue. The profile still updates for later loads either way.
- Each transfer function means something different by
1.0, andEncodingWhiteNits()is the only place that knows it: Skia decodes PQ and HLG against BT.2408 reference white (linear1.0= 203 nits, so PQ code 1.0 reads back 49.26 = 10000/203),ScRgb= 80 nits (IEC 61966-2-2, display-referred),Linear/None= diffuse white (scene-referred EXR / Radiance HDR). After the scalevis alwaysnits / ReferenceWhiteNits, which is the cross-check: the same scene as PQ and as scRGB must land on the samev. - The PQ/HLG anchor is a SkiaSharp 4 convention, and reverting it silently over-exposes 49x. SkiaSharp 3.x decoded PQ to absolute luminance (linear
1.0= 10000 nits), which is whyEncodingWhiteNitsonce had aPqPeakNitsarm; 4.x moved to Chrome's reference-white-relative model, visible in the named transfer function itself (SKColorSpaceTransferFn.Pqis the marker formG=-5 A=203, whereAis reference white in nits). Never reintroduce a per-transfer-function absolute anchor without re-measuring the decoder. - WIC infers scRGB for every float and fixed-point pixel format, so anything the WIC codec plugin returns as
RgbaFloat16isHdrTransferFunction.ScRgb, neverLinear. Tagging itLinearreads the image 203/80 = 2.54x too bright, which shows up as washed out with lifted blacks.IGHdrTransferFn.ScRgb= 5 arrived in plugin ABI 1.1.1; plugins gate on thehostAbiVersionpassed toig_plugin_get_apiand fall back toLinearbelow1_001_000, because an older host maps an unknown value toNoneand skips tone mapping entirely. ReferenceWhiteToneMap(BT2408) is a global roll-off, not a knee, on purpose. Reference white lands near0.5linear (188/255) and the curve reaches 1.0 only at its white level, which is the file's declared content peak (see below), or 6x reference white when the file declares none. BT.2408 the spec does say reference white maps to SDR white, and doing that clips the top quarter of a real grade: a 1164-nit sample has 29% of pixels above reference white, and a knee at 0.9 renders its p75 at 252/255. The low landing is headroom, not a bug.Reinhard(knee 0.7) andACES(knee 0.5) are identity below their knees and clip that content much sooner.- The tone curve's white level is the file's declared peak, not a guess.
MagickCodec.DetectHdrInfostep 10 fillsPhotoMetadata.ContentPeakNitsfrom the container's HDR10 metadata (ISOBMFFclliMaxCLL, elsemdcvmastering max; PNG spells the chunkcLLi, not the spec'scLLI, and uses 0.0001-nit units where ISOBMFF uses whole nits), andComputeToneCurveWhiteLevelturns it intopeak / ReferenceWhiteNitsclamped to 1..24. A declared 10000 is rejected, not honoured: it is the PQ container ceiling encoders emit when they do not know the real peak, and trusting it holds back 24x of headroom for content that is not there. Only BT2408 consumes it; Reinhard/ACES stay knee-based.HighlightCompressionnow means extra headroom past the declared peak (x (1 + 3c)), for a grade brighter than its own metadata claims. ReferenceWhiteNitsrising makes the image darker, and that is correct, not inverted. It is the normalization divisor (ComputeNormScale), i.e. source-side HDR reference white per BT.2408, so declaring a brighter level as white necessarily renders everything below it darker. The confusion is that "paper white" at the display end (Windows SDR content brightness) brightens as it rises. Do not "fix" the direction; the label saysReference whiteand the tooltip states the direction.- The two tone-map loops run a
Vector128body (four pixels per step) and the original scalar loop on the rest of the row, and the two must stay op-for-op identical, NaN and -0 included (Clamp01mirrorsMath.Clamp), or the last pixels of each row differ from the rest. Verify a change with an old-vs-new harness, not by eye. Do not add aVector256path or raiseIlcInstructionSetfor it: the default NativeAOT target never acceleratesVector256, and x86-64-v3 measured no gain while locking out CPUs without AVX2. - Avalonia presents SDR only, so a desktop in HDR mode makes MS Photos structurally better looking than any tone-map setting can be. Check
advancedColorEnabledviaDisplayConfigGetDeviceInfobefore chasing it, and never use a GDI screen capture of an HDR desktop as ground truth for another app (it is faithful for ImageGlass's own SDR output).
See the ig-app-print skill for the full contract; the invariants worth knowing here:
- One renderer for everything that prints.
PrintPageRenderer.DrawPageAsyncdraws a page in points (1/72 in) onto any canvas: the preview bitmap, a PDF page (PdfPrintWriter,SKDocument.CreatePdf), and each Windows GDI cell raster. Never draw a print any other way, or the preview stops being what prints. - Layout is pure and in points (
PrintLayoutEngine.Paginate). Auto orientation breaks ties by prints per page, then paper per print, then prints that stand upright; without the last key, landscape photos on "4 per page" went onto a turned portrait page. Every quarter turn is counter-clockwise (auto-rotate in a cell, and a landscape page turned onto portrait paper), as IPP "landscape" turns. - "Current state" is the viewer's.
ViewerControl.CaptureImageState()leases the shown image with its edits recipe (orientation, invert, channels, HDR tone mapping);PrintSessionuses those pixels for the shown frame whenHasExactColorTagand not a preview, andPhotoFrameReaderwithSkipDisplayProfilefor every other frame. Output is always 8-bit sRGB; the display profile applies only to the preview bitmap. PrintSessionimages are opaque on white, the paper they print on, so a PDF stores them as JPEG q95 (PdfWriteOptions.EncodingQuality); lossless made a 1.5 MB photo a 5.8 MB PDF. They come in power-of-two buckets under a 256 MB LRU, and every surface checks theint.MaxValuebyte ceiling.- Providers never lay out.
IPrintProvider+PrintProviderBaseown Save as PDF (ig:pdf) on every OS. Windows prints through GDI (Win32GdiPrintJob): each cell a raster at its image's own density (150 dpi floor, 300 for photos, 600 for vectors), sent in 32 MB bands by an STA thread that owns the DC. Linux sends a PDF job to CUPS (CupsApi,print-scaling=none, portrait pages only) and "system dialog" is the XDG print portal (XdgPrintPortal, the PDF as a descriptor). macOS sends the PDF throughPMPrinterPrintWithFile(MacPrintCoreApi) and opens PDFKit's print panel. - macOS: PrintCore drops what CUPS needs. Two-sided and grayscale reach the job only as the CUPS options
sides/print-color-modeon the print settings (PMSetDuplexnever does, and a queue may default to two-sided); the state comes from CUPSprinter-state-reasons(PrintCore calls an offline printer idle); the PPD opens only with the typePMPPDDescriptionType(any other string, "PPD" included, is paramErr). "Use the system dialogβ¦" opens PDFKit's panel on the window's printer, paper, orientation and copies, and a cancelled panel keeps the Print window (ShowSystemDialogAsyncreturns whether the dialog took the job). - Linux: one scheduler connection per CUPS operation, and the portal's D-Bus connection kept until it answers.
cupsLocalizeDestMediarefusesCUPS_HTTP_DEFAULT(every paper name fell back to its PWG name), and xdg-desktop-portal closes the requests of a caller that leaves the bus (a cancel in its dialog still closed the Print window); the window counts that dialog as a job while it is open. A job carries the destination's own options (a CUPS instance's) under the window's, aslpdoes. Metric or inches comes fromLC_MEASUREMENTthere: the app pins its culture to invariant, whichRegionInfo.CurrentRegionfollows off Windows. - Windows measures printable areas lazily (
IPrintProvider.MeasurePaperAsync): aCreateICper paper costs ~20 ms and Microsoft Print to PDF lists 84 papers, so capabilities measure only the default paper and mark the restIsPrintableAreaMeasured = false. The GDI job places everything by the real device geometry, so an estimate never misplaces output. - Completion says "Sent to {printer}" for every system printer, a file printer included: the spooler writes the file after
EndDoc, so only the app's own Save as PDF may say "Saved". A cancelled job's output file is deleted afterAbortDocwith retries, since the spooler opens it with the first page and still holds it, and only afterStartDocsucceeded, so a failed open never deletes a file the user chose to overwrite. - Captions are outlines (
SKFont.GetTextPath), so a PDF embeds no font, and they are split into per-script runs (CaptionFonts): one fallback font for a whole caption printed Hangul as boxes next to Japanese. - "Add a printer" opens the OS's own settings (
IPrintProvider.OpenAddPrinterSettingsAsync:ms-settings:printers, macOS Printers & Scanners, on Linux the desktop's printer panel, else the CUPS web page), and from then on the window lists printers again on every activation, choosing a newly added one. That refresh keeps the chosenPrinterInfoinstance and never re-selects it: the view drops stale capability and status replies byReferenceEquals(_printer, printer), and re-selecting would discard the driver'sPlatformState.
- Comments: Explain why, not what; only add if needed. Write one line. Two only when genuinely unavoidable, never three; that ceiling covers XML doc tags (
<param>,<summary>) exactly as much as//and<!-- -->. If the reasoning does not fit on one line, it belongs in the commit message or the PR, not in the source. - XML documentation comments: For C# classes, methods, and public properties in infrastructure / coordination code (plugins, tools, host bridges, process managers, IPC handlers, similar files), keep XML docs present and current.
- XML summary format: Never use single-line XML summaries like
/// <summary>Text</summary>. Always use the multi-line form:/// <summary> /// Text /// </summary>
- Long/complex methods: Add brief inline comments for the main implementation phases so the control flow is easy to scan.
- Async/Await: Use
ConfigureAwait(false)in library code; omit in UI entry points - Timeouts: Use
CancellationTokenSource.CancelAfter()for time-based cancellation - Cancellation: Always check
token.IsCancellationRequestedin loops; throw on cancellation
- Reuse UI components: when building UI, always check and reuse the existing controls in
ImageGlass.Lib/UI/(e.g.PhButton,PhTextBox,PhTextBlockinUI/BaseControls/) instead of raw Avalonia controls; use the app's style resources viaResx/ResxId(Common/Types/Resx.cs) rather than hardcoding colors/brushes. See the Designing UI section for the full controls/resources/icons/fonts inventory. - Platform-conditional visibility: hide/show controls per platform with the XAML
OnPlatformmarkup extension directly onIsVisible, not withOperatingSystem.IsWindows()in code-behind. Example:IsVisible="{OnPlatform False, Windows=True, x:TypeArguments=x:Boolean}"(seeUI/Toolbar/ToolbarControl.axaml). - Compiled bindings:
AvaloniaUseCompiledBindingsByDefault = true(type-safe, zero-runtime cost). Always write{CompiledBinding ...}explicitly in XAML β never{Binding ...}β including in styles,ControlThemes, andDataTemplates. Compiled bindings need anx:DataTypein scope; for a self-binding to an untyped collection (e.g. aDataValidationErrorserror template) setx:DataTypeon theDataTemplate(e.g.coll:IEnumerableviaxmlns:coll="using:System.Collections"). Element/ancestor/TemplatedParentbindings (#name,$parent[Type],RelativeSource={RelativeSource TemplatedParent}) infer their type and need nox:DataType. - Attached behaviors: Prefer to UI trigger patterns for event handling
- Threading: Use
Dispatcher.UIThread.Post()orDispatcher.UIThread.InvokeAsync()for cross-thread updates - Resources: XAML/PNG/ICO in
Assets/, referenced viaavares://protocol - Gestures: Accumulate pointer events before expensive calculations; use
PhPanGestureRecognizerandPhPinchGestureRecognizer - Animations: Use
TopLevel.GetTopLevel(this)?.RequestAnimationFrame(callback)for frame-rate-independent animations synced to the render loop; compute delta from theTimeSpantimestamp parameter; request the next frame at the end of each callback to continue the loop (seeViewerControl_Animation.cs,NavButtonsOverlay.cs)
- Always dispose: SKImage, SKPaint, SKCanvas, SKMatrix (use try/finally or
using) - No pooling in hot paths: Allocation is fast; premature pooling hurts readability
- Pixel formats:
SKColorType.Rgba8888for sRGB; considerColorSpacefor ICC - Bitmap to image: use
SkiaCodec.ToSKImageNoCopy()when the bitmap is finished (shares pixels); plainToSKImage()copies the whole buffer - Full-image color conversion: draw through
SkiaCodec.TryDrawInBands()(parallel row bands, straight into the destination bitmap); a Skia CPU draw is single-threaded, so oneSKSurfacedraw plusSnapshotis several times slower - Size ceiling: check
width * height * bytesPerPixelagainstint.MaxValuebefore allocating any full-image buffer - Filtering:
SKFilterQuality.Highfor thumbnails;Mediumfor interactive zoom - Mipmap strategy: Precompute at load time; cache tiles on-demand; preserve zoom-aware LRU
A cancelled gallery scroll has crashed the app twice, as 0xc0000374 (BlockNotBusy DOUBLE_FREE) and later as 0xc0000005, both in Magick.Native-*.dll.
- Never
PingthenReadinto the sameMagickImage.Pingallocates a native image, and reading into that same wrapper leaves a second one to be freed twice. Probe with a throwawayusing var, orDispose()before re-reading (MagickCodec.DecodeImageAsyncdoes the latter). - Dispose the
MagickImageon every failure path, including early returns andcatch. An abandoned partially-read image handed to the finalizer is what turns the above into a delayed crash that surfaces at an unrelated allocation, pointing nowhere near the read. - Cancelling a Magick
ReadAsyncwas a hard process kill in 14.15.0-14.17.0, so the floor is 14.17.1 (upstream #2084). 14.15.0 rewrote the file overload to stream through a reverse-P/Invoke callback; a firing token killed the pump, the callback returned-1, and libjpeg read that as an unsignedbytes_in_bufferand walked off the heap. The same race could instead strand the decode thread in_readDone.Wait()forever. 14.17.0 fixed only the access violation (natively), 14.17.1 fixed the deadlock. Never lower this floor to pick up an older Magick.NET. - Applies to any path a fast gallery scroll can cancel:
QuickDecodeAsyncis reached fromPhotoPreviewProvider.GetThumbnailAsync, whose token is cancelled on every container recycle.
- Mipmap caching: Use
MipmapTileCachefor images > 8192Γ8192; reuse instance across frames - Gesture recognizers: Accumulate points in
PhPanGestureRecognizerandPhPinchGestureRecognizerbefore expensive math - File searching: Async + debounce in
PhotoManager_FileWatcher.cs; useIFileSearchProviderfor platform-specific optimizations - Photo preloading: Use spiral pattern in
PhotoManager_Caching.RunCacheAroundAsync()to balance memory and responsiveness - PNG writes through Magick: call
MagickCodec.SetPngCompressionLevelnext to everyQualityassignment. Magick's PNG writer readsQualityas the zlib level (quality / 10), so the usual 80-100 meant level 8-9: ~9-18 s for a 12 MP photo, against ~2.5 s at the capped level 6, for files only ~5% smaller.
| File/Folder | Purpose |
|---|---|
Core.cs, Core_Events.cs |
Global event hub and singleton access; service provider slots |
App.xaml.cs |
Avalonia app lifecycle, theme/lang initialization |
ImageGlass.Win32/Program.cs |
Entry point, service registration, AOT bootstrap |
PhotoManager.cs + PhotoManager_*.cs |
Photo collection, file search, caching (LRU), file watching |
ImageGlass.Win32/Common/ServiceProviders/Win32FileSearchProvider.cs |
Explorer sort order: the list from the foreground or an opening file manager view (EggShell ShellAppView), else plain enumeration |
ViewerControl.cs + ViewerControl_*.cs |
Image rendering, zoom/pan, selection, animation, nav buttons |
UI/Viewer/Renderer/MipmapTileCache.cs |
Tiled mipmap cache with LRU eviction |
Common/Photoing/Codecs/SkiaCodecs/HdrToneMapper.cs |
HDR-to-SDR tone mapping; per-transfer-function 1.0 anchors in EncodingWhiteNits (PQ/HLG = 203 nits, scRGB = 80 nits); Vector128 loops that must match their scalar tails bit for bit |
Common/Photoing/Codecs/SkiaCodecs/DisplayColorPass.cs |
The viewer's whole color pass (HDR tone map, then monitor profile) as a value-comparable record; shared by the viewer and the cache pass's prepared display frames |
Common/Printing/ + Windows/Print/ |
Printing: layout engine, page renderer, PDF writer, PrintSession, and the Print window; each platform's PrintProvider spools (see "Printing") |
Common/ServiceProviders/ |
Interface contracts + shared providers for cross-platform features |
ImageGlass.Win32/Common/ServiceProviders/ |
Win32 implementations of service providers |
ImageGlass.Linux/Common/ServiceProviders/ |
Linux implementations of service providers |
ImageGlass.Mac/Common/ServiceProviders/ |
macOS implementations of service providers |
Common/ServiceProviders/AppAPIs/FeatureManager.cs |
Feature lock (static Config.LockedFeatures API names, admin-only): IsLocked, IsZoomLocked/IsPanLocked, HideLockedMenuItems |
Common/Types/ConfigMode.cs |
Portable-mode detection (.igportable marker in the startup dir) consumed by BHelper.ConfigPath; an unwritable folder is a fatal startup error |
Settings/Config_Static.cs (AdminLockedConfigs/IsConfigLocked) + Windows/Settings/ |
Admin settings-lock: disables + refuses to save settings defined in igconfig.admin.json (Pro only; read by ReadAdminConfigDocument() from the startup dir, else the config dir) |
Common/AppThemes/ |
Theme loading, color management (AppThemeColors, IgThemeColors) |
Common/Localization/Lang.cs |
Translation key registry |
Common/Types/Resx.cs |
Themed resource registry (ResxId); resolve via {DynamicResource} / Resx.Get. Also hosts icon helpers (ResxIconId + GetIcon) and platform stock icons (StockIconId + GetStockIcon / GetDefaultWindowIcon) |
Common/Types/Const.cs |
App constants: icon sizes, FONT_CODE, FONT_SIZE_* |
Common/Extensions/, Common/BHelper/, Common/Types/JsonTypeConverters/ |
Shared extensions, helpers, AOT-safe JSON converters (check before writing new) |
UI/BaseControls/ |
Reusable Ph* controls (PhButton, PhTextBox, etc.) |
UI/Styles/ |
App-wide XAML styles + resource dictionaries (incl. IconResources.axaml) |
Directory.Packages.props |
Central package version management (Avalonia 12.1.x, SkiaSharp 4.152.x, Magick.NET 14.x, etc.). SkiaSharp is transitive (Avalonia.Skia asks for 3.x), so it needs CentralPackageTransitivePinningEnabled plus explicit SkiaSharp.NativeAssets.* pins |
- No auto-generated code edits: Skip
/obj/,*.g.cs, generated Win32 P/Invoke (NativeMethods.g.cs) - Event naming: Use
TEventHandler<TSender, TArgs>for type-safe events (defined inCommon/Types/TEventHandler.cs) - Weak event subscriptions: Prefer
IDisposableunsubscribe over weak events for clarity - Config JSON: Add custom converters in
JsonTypeConverters/folder if new types need serialization - Cross-thread calls: Always check
IsDisposedbefore invoking on disposed ViewModels/Services - Horizontal code splits: Many large classes split into partial files; search by concern (e.g.,
PhotoManager_*.cs) - Lock usage: Always use
Lockfor critical sections; avoid nested locks to prevent deadlock - Resource cleanup: Use try/finally or
usingfor allSKObjectallocations; dispose tiles inMipmapTileCacheon eviction
- Tools/CodeSigning/sign_publish_files_x64.bat (repo-level): Legacy v9 code signing script; documents publication binaries but does not apply to
v10output paths without modification. - AOT Publishing: Use
dotnet publish ImageGlass.Win32 -c Releaseto generate trimmed, self-contained executable. - NativeMethods.g.cs: Auto-generated by CsWin32 from
NativeMethods.json; do not edit manually.
Scripts in __assets/<win|mac|linux>/, VS Code tasks pack-*, output in __artifacts/bundle/. See the ig-app-packing skill for the full contract; the invariants worth knowing here:
- Version:
Directory.Build.propsis the only place to bump (IgVersion,IgReleaseType,IgBundleShortVersion,IgBundleBuild).Directory.Build.targetsbakes it intoAppBuildInfo.g.cs, so packing a stale publish dir ships old code under a new version. The msstore MSIX uses<Major>.<Minor>.<IgBundleBuild>.0(the Store reserves the 4th part); the sideload MSIX and the MSI useIgVersionverbatim. - Windows (
script-pack-win-msix.ps1,script-pack-win-zip.ps1): two MSIX flavours (msstore: unsigned, Store re-signs, virtualized; signed sideload:-Sign -UnvirtualizedResources), plus the portable ZIP that writes.igportableunless-NoPortable. Both scripts publish a fresh AOT build themselves. - macOS (
script-pack-mac-arm64-app.sh->-dmg.sh):Contents/MacOSmay hold only Mach-O files, so bundled data is staged intoContents/Resources/and symlinked back orcodesignfails. The DMG is Developer ID signed, notarized, and stapled. - Linux (
script-pack-linux-x64-flatpak.sh,script-pack-linux-x64-appimage.sh): the Flatpak manifest installs a prebuilt tarball, so the GitHub release must exist before Flathub submission, and--disable-cacheis mandatory or the bundle ships the previous binary. The AppImage stages an AppDir with the payload underusr/lib/imageglass/(mirroring the Flatpak's/app/imageglass/, soBHelper.BaseDir()behaves identically in both) and a generatedAppRun; unlike Flatpak it runs against the host glibc and host libraries. NativeAOT links against the build machine's glibc (a plain 24.04 publish needed 2.38, #2484), so both Linux scripts publish with-p:SysRootagainst a pinned Ubuntu 20.04 sysroot (script-linux-x64-sysroot.sh, sha256-checked.debs cached in__artifacts/tools/) and fail when a shipped ELF needs more than its glibc 2.31.LinkNative's only inputs are the object files, so aSysRootchange alone never relinks; the scripts delete the old linked binary first. Both share onemetainfo.xml, in__assets/linux/flatpak/. The AppImage also embedsgh-releases-zsyncupdate information (taglatestfor stable,latest-allwhenIgReleaseTypeis non-empty orIgUpdateChannelis notstable, so an rc/beta still rolls onto the stable superseding it) and emits a.zsyncthat must be uploaded to the same release β itsURL:is relative, and an image advertising an update with no.zsyncfails every check.zsyncmakewrites into the CWD, not beside its input, so appimagetool is run from__artifacts/bundle/. __assets/__app/is shared payload;_ext_iconsis Windows-only and is stripped for macOS, Linux, and the msstore MSIX..igportablemust never live there (a read-only MSIX payload would refuse to start).
- PhotoLoading hangs? Check
_cancelPreviewin ViewerControl; may be a codec timeout - A photo shows black during fast navigation, and is fine on the next visit? The load ended without raising
Loaded(see "ALoadAsyncthat returns without raisingLoaded"), so the viewer holds no source at all; "fine the second time" is the tell, since the photo is decoded and the fast path renders it. Trace with--ig-photo-traceand look for aviewer:set-photowith no followingrender:first-draw, plusviewer:recover*,load:queued-cancelandload:cache-hit. Full screen makes it visible because the gallery is hidden there, soPhoto.GalleryThumbnailis null and no preview covers the gap. - Memory leak? Verify disposal of
SKImage,SKBitmap,SKSurface, andPhDisposablesubclasses; profile with large images - Theme not updating? Ensure
Core.ThemeChangedis invoked and subscribers listen - Gesture not working? Check
PhPanGestureRecognizer,PhPinchGestureRecognizerinZoomAndPan/; verify point accumulation - Nav buttons not showing? Check
Config.EnableNavigationButtonsbinding,NavButtonsOverlay.Backgroundmust beBrushes.Transparentfor hit-testing, andEnableSelectiondisables nav buttons - Color wrong after switching profiles (brighter/over-saturated, persists until restart)? The codec-selection cache is stuck on Magick (double profile application); ensure
Core.UpdateDestColorProfile()callsCodecRegistry.InvalidateSelectionCaches(). CMYK profile showing inverted/negative?ProcessMagickImage__must cast a CMYK result toColorSpace.sRGB. - A cached HDR or color-managed photo still pauses before it shows? The prepared display frame was not used. With
--ig-photo-trace, a used one logsviewer:display-frameandviewer:color-managedlands ~0 ms afterviewer:set-photo; without it the pass ran on demand because an HDR option, the monitor profile or the HDR switch changed since the cache pass (expected, the frame was stale), the budget had no room for it, or the photo is multi-frame.cache:display-frameshows each prepare and its time. - HDR image looks washed out or blown out, or two viewers disagree on its brightness? That is a normalization bug, not a color one:
EncodingWhiteNits()anchors1.0per transfer function, and scRGB is 80 nits rather than the 203-nit reference white PQ/HLG use. Before judging a curve change by eye, dump the source luminance percentiles, and checkConfig.ToolSettings["Tool_HdrToneMapper"].Modefirst, since a hand-tested build may be runningACES(knee at 0.5, clips a real HDR photo from p75 up) rather than theBT2408default. - Admin-locked setting still editable or saved? The admin settings-lock (
igconfig.admin.jsonkeys βConfig.AdminLockedConfigs/IsConfigLocked) enforces at three points, all required:SettingsViewModel.CommitAsync(skip locked ids),Config.ApplyCliOverrides(skip locked ids), and the settings UI (SettingsRegistry.DisableLockedControlsforBind*controls +SettingsPageView.DisableIfLockedfor composite editors). Capture runs inConfig.LoadAdminPolicies()independently of the user-config read (a corruptigconfig.jsonmust not empty the lock set). Plugins page is UI-disable-only (PluginTrustapplies live viaPluginTrustPolicy, never staged). - Whole admin layer ignored? It is Pro-gated in
ReadAdminConfigDocument(), soCore.AppLicensemust be loaded beforeConfig.Load()(App.axaml.cs). Also check the lookup order: startup dir wins, config dir is only a fallback, and the two files are never merged together. igconfig.default.jsonignored? Both template layers are Pro-only: it is gated inReadDefaultConfigDocument()exactly as the admin file is inReadAdminConfigDocument(), with the same license-before-load ordering and the same startup-dir-then-config-dir lookup. Classic keeps only the developer defaults underigconfig.json.LockedFeaturesset inigconfig.jsondoes nothing? Intended: it is not aConfigIdand not aConfigproperty, so every user-writable layer (user file,igconfig.default.json,-p:CLI,IG_ApplySettings) ignores it and a stale key is dropped on the next save.Config.LoadAdminPolicies()reads it fromigconfig.admin.jsonalone, which is already Pro-gated byReadAdminConfigDocument(). Never re-add it as aConfigId: a user-writable layer could then unlock a feature an admin locked.- Locked feature (
LockedFeatures) still triggerable? OnlyAppAPIProvider.RunApiAsync(both overloads) and the hotkey handler are auto-gated byFeatureManager.IsLocked. Any path that skips them must self-guard: context-menu items (bound viaGetApiCommand) go through theLockAwareApiCommandwrapper; viewer wheel/drag/touch zoom-pan self-checksFeatureManager.IsZoomLocked()/IsPanLocked(). A new input path or a direct command execution without one of these is a bypass. - "Unable to allocate pixels for the bitmap" on a huge image? Not an out-of-memory problem, so do not chase RAM or fragmentation. Skia refuses any pixel buffer over
int.MaxValuebytes; the decode must shrink to fit first (GetDecodableImageInfoon the Skia path, the in-place resize inFromMagickon the Magick path). A new code path that allocates a full-image buffer without that check reintroduces the crash. - Huge image opens smaller than the file? Expected:
Photo.DecodeScale < 1and the status bar shows the reduction.Photo.Metadata.Width/Heightkeep the true size; everything else follows the decoded size. - Memory balloons only when a codec plugin is enabled? Plugin pixel buffers are native memory the GC never sees, so
NativeCodecProxy.WrapPluginBufferAsImagemust pairPluginPixelBufferRelease.TrackNativeMemorywith the release, and the cache budget must readPhoto.BytesPerPixel(a plugin frame can be 8 bytes/px, not 4). - Plugin-owned format shows a garbage gallery thumbnail (thin line, blank) while the viewer renders it fine? A content-sniffing built-in decoder (
SKCodec.Create, Magick) succeeded with absurd dimensions instead of failing, and that satisfiesIsPreviewLargeEnough(longest side only), so the plugin is never asked. Every preview/thumbnail source must gate onCodecRegistry.IsDecodingExtensionOwnedByPlugin(viaPhotoPreviewProvider.IsPluginOwnedFormat); trace with--ig-photo-trace(preview:*= which source won,thumb:preview/thumb:codec/thumb:decode= whether the slow path ran). - File type icons work in a debug run but never from the MSIX? Not a path or virtualization bug: registry writes DO reach the real HKCU on the unvirtualized sideload flavour. A package that declares
windows.fileTypeAssociationowns the icon of every type it claims and outranks the classicDefaultIcon. Confirm withAssocQueryString(ASSOCSTR_DEFAULTICON, ".png"): an@{<PackageFullName>?ms-resource://...}result means the manifest is winning. The sideload flavour therefore declares no association at all; the Store flavour declares one per format with its ownuap:Logo. Blank icon in the Open With list instead? Every MSIX execution alias is a 0-byte reparse point, soLaunchCommandExemust register the real exe (seeig-app-packing). - AppImage exits immediately (
version 'GLIBC_2.xx' not found), orlibgomp.so.1: cannot open shared object file? An AppImage links against the host glibc, unlike the Flatpak, which brings its own runtime. The floor is glibc 2.29 (Ubuntu 20.04+), set by the prebuiltMagick.Native; the pack script refuses anything above the sysroot's 2.31 and names the symbols forcing it. A floor above that means the binary was linked without the sysroot.libgompis aDT_NEEDEDofMagick.Native-*.so(which has noRUNPATH), bundled inusr/lib/fallback/and added toLD_LIBRARY_PATHbyAppRunonly when the host has none β an unconditional entry would shadow the host's own glibc-matched copy. Never bundlelibGL/libX11/libfontconfig: they are coupled to the host's drivers and font config. - AppImage cannot open a file passed as a relative path, or Save As defaults into
/tmp/.mount_*? Both depend on the cwd (BHelper.ResolvePathends inPath.GetFullPath), soAppRunpins it to$OWD, the caller's dir that the runtime exports in mount mode (extract-and-run leaves it unset, hence the-n/-dguard). Measured on type2-runtime75849dc, all three launch modes already preserve the cwd, so thatcdis a no-op guard against a runtime that does not β do not remove it and do not assume it is what makes relative paths work.AppRunmust also never exportTMPDIR(AppInstance's lock lives there, and an unwritable path is swallowed, so every launch silently claims "first instance") orXDG_DATA_HOME(it would orphan the settings shared with the tarball install). - App does not come back after a restart (Quick Setup, Pro activation) in an AppImage?
Environment.ProcessPathis the binary inside the mount, which is unmounted the moment the exiting process dies. Relaunch throughBHelper.AppRelaunchPath($APPIMAGEwhen set, elseAppExePath); a new relaunch site usingAppExePathreintroduces it. - Settings not staying with the app folder (or the app quits at startup with "Cannot use portable mode")? Portable mode is driven by the
.igportablemarker in the startup dir (ConfigMode). The marker must exist next to the exe AND that folder must be writable; an unwritable folder is a hard stop by design, not a fallback to%LocalAppData%. The ZIP packer writes the marker; the MSIX must never carry it. - A path shown for an app-owned folder cannot be opened ("Unable to find /app/imageglass"), or a file under the app dir is suddenly not found? Two platform indirections hide the real location from the process: Flatpak mounts the install dir at
/app, and MSIX may redirect%LocalAppData%into the package container.BHelper.GetRealPlatformPath()is the single translator to the path the OS and the user see β use it for anything displayed or handed outside the process (BasePath,GetRealPlatformConfigDir,Lang.DisplayFilePath,IgTheme.DisplayFolderPath,XdgPortal,ApplyFlatpakHostSpawn), andIShellProvider.GetActualPathis its per-platform half. A path used for I/O keeps the process form, so a type that needs both exposes aDisplay*twin (see those two) rather than mapping the stored value.BHelper.BasePathis therefore always the full, real dir of the binary; inside the sandbox that path is NOT readable, raw or via/run/host, even with--filesystem=host. Every read goes throughBHelper.BaseDir(), which maps back to the mount βPath.Combine(BasePath, x)for I/O is the bug. Off Flatpak/MSIX every mapping is identity, so Windows/macOS behave exactly as before. Never add a second base-path accessor. - A Flatpak build is missing
_lang,default.webpor another asset the tarball does contain? The manifest'sbuild-commandscopy the payload as a whole fromdest: payload; a re-introduced explicit file list silently drops every asset added to__assets/__appafterwards. - App vanishes with no error dialog (no in-app exception, nothing logged)? That is a native crash, so
App.UIThread_UnhandledExceptionnever runs. Do not hunt for a managed exception. Read the real fault first:Get-WinEvent -FilterHashtable @{LogName='Application'}filtered toApplication Errorgives the exception code (0xc0000374= heap corruption,0xc0000005= access violation). Then bucket it withcdb.exe -z <dump> -c ".lastevent; !analyze -v; q"(WinDbg installs viawinget install Microsoft.WinDbg;cdb.exesits in the package'samd64folder). Dumps land in%LocalAppData%\CrashDumps.!analyze -vnames the faulting module and whether it was a double free, which is usually the whole answer.dotnet-dump analyze <dump> -c "clrstack -all"then shows which managed call was in flight on that thread. - App vanishes on macOS with
EXC_CRASH (SIGABRT)/abort() calledon a.NET TP Worker? That is NativeAOTFailFastfrom a managed exception that escaped a background thread β usuallyasync void, whoseAsyncVoidMethodBuilder.SetExceptionrethrows with noSynchronizationContext. Do not chase native heap corruption. Symbolicate before theorising: crash reports are~/Library/Logs/DiagnosticReports/ImageGlass-*.ips, andImageGlass.Mac/bin/<Platform>/Release/net11.0/osx-arm64/native/ImageGlass.dSYMmatches whendwarfdump --uuidequals the report's UUID. Thenatos -o <dSYM>/Contents/Resources/DWARF/ImageGlass -arch arm64 -l <load addr> <frame addrs>names the exact method β the frame underAsyncVoidMethodBuilder__SetExceptionis the culprit. - An
async voidoutside a UI event handler is a crash, not a bug. On the UI threadDispatcher.UIThread.UnhandledExceptioncatches it; on any worker it kills the process silently. Everyasync voidreachable from a worker (Photo.OnDisposing/Unload,GalleryItem.LoadThumbnail, file-search callbacks) must wrap its whole body intry/catch (Exception).AppDomain.CurrentDomain.UnhandledExceptioncannot save it: the process is torn down as soon as the handler returns, so aDispatcher.Postthere never renders. - An integrated external tool (ExifGlass) opens but never shows the current photo, and does not follow navigation? The IPC socket is unreachable, not the tool. On Linux a tool is commonly a Flatpak app (the seeded ExifGlass registration runs
flatpak run), and every Flatpak gets a private/tmp, so the defaultNamedPipeServerStreamsocket at/tmp/CoreFxPipe_*is invisible to it.ToolProcessManager.CreatePipeName()therefore keys offBHelper.OS == Linux, notIsFlatpakSandbox: the tool's reachability is what matters, not whether ImageGlass itself is sandboxed.~/.cache/ImageGlass/toolsworks because the tool's manifest grants--filesystem=host. Keying it offIsFlatpakSandboxsilently breaks every non-Flatpak Linux build (AppImage, tarball,dotnet run) while working under Flatpak. - Works on Windows but crashes on macOS/Linux in the file-search path? Only
Win32FileSearchProvideroverridesSearchAsyncto publish throughDispatcher.UIThread.Postwith a token re-check; the base provider invokesprogressFnstraight from itsTask.Runworker. So a search callback that touchesCore.Photos.Items(bound to the gallery) or any control runs off-thread on macOS/Linux only. Marshal the whole callback body, not just theAdd. - App starts on Linux but no window ever appears β no error, no crash, nothing logged? The main window is gated on
_taskUi, and_taskUi.TrySetResult()is the last line ofApplyThemePackAsync, so anything that skips that method hangs the show.App.OnFrameworkInitializationCompletedawaits_taskUi.Taskbeforedesktop.MainWindow = MainWindow, so the process stays alive with its event loop idle and the window created but never mapped. Diagnose withxwininfo -root -tree | grep 'ImageGlass 10"'thenxwininfo -id <id> | grep 'Map State':IsUnMapped(and nomutter-x11-framesparent) means created-but-never-shown, and Avalonia builds the X window in theWindowconstructor but maps it only onShow(). Never leave_taskUicompletable on one path only βApplyUIConfigsAsyncsets it in afinallyfor exactly this reason. - Linux dark mode:
PlatformSettings.GetColorValues()is a provisionalLightat startup, andColorValuesChangedfires only when the resolved value differs. Avalonia resolves the theme asynchronously fromorg.freedesktop.portal.Settings, soGetColorValues()returnsLightat t=0 whatever the desktop is set to, and the event lands ~20-34ms later only on a dark desktop. On a light/default desktop it never fires at all, which is why waiting for it unconditionally hung startup.LINUX_SYSTEM_THEME_GRACE_MSbounds that wait: high enough that the event wins the race (so the pack loads once), low enough that a light desktop does not pay it in full. Dropping it below ~20ms is not a correctness bug but makes the event always lose, costing a redundant disk theme load plus a spuriousCore.OnThemeChanged()on every dark launch. - Gallery thumbnails load twice per item, or a wrong-size thumbnail flashes then gets replaced?
PhVirtualizingUniformPanel.GetOrCreateElementsetsDataContextbeforeAddInternalChild, so a brand-newGalleryItemis still detached when itsDataContextPropertyhandler runs,TopLevel.GetTopLevel(this)is null, andDpisilently falls back to1. Gate that handler onIsLoaded:OnLoadedcovers the first attach, and recycled containers stay loaded (RecycleElementonly setsIsVisible = false, it never removes the child) so the handler remains their only trigger. - Gallery shows nothing selected after opening a file (and navigation starts from -1)? The init photo path did not match the enumerated form. Enumeration emits absolute
FileInfo.FullNameandIndexOfis an exact-string lookup, so a relative launch path such asdotnet run --project ImageGlass.Win32 -- pics\a.jpgmisses unless it went throughBHelper.ResolvePath. - Opened a photo from a file manager but the list ignores its order? Make ImageGlass's own order differ (
-p:ImageLoadingOrder=FileSize) and read thei/Nindex in the window title to see which source won. The file manager must be the foreground window at launch, since that is when it is captured; a plain folder also needsEnableExplorerSortOrderand the opened file's own folder, and a third-party file manager is followed only if EggShell supports it. See "Explorer sort order & the foreground shell". - No slideshow notification sound?
BHelper.PlayNotificationSoundAsync()plays the bundledAssets/Sounds/notification.wav, never a system beep. Windows/macOS use NetCoreAudio (winmm MCI /afplay); Linux deliberately does not, because NetCoreAudio hardcodesaplay, which neither the Flatpak runtime nor an alsa-utils-less distro has β and since it shells out through/bin/bash, the missing binary exits 127 without throwing, so nothing reaches thecatch.PlayLinuxSoundAsyncinstead probespaplay/pw-play/aplay/ffplay, keeping the first that exits 0 (a player may exist yet fail for want of a sound server). Flatpak additionally needs--socket=pulseaudioinfinish-args, without which every player fails. - Window comes back the wrong size (or the gallery/toolbar reappears) after leaving full screen? The pre-fullscreen
WindowLayoutSnapshotwas never captured, or the close handler persisted the live full screen values over it. See "Full screen & the windowed layout". - Projector tiles or window fit stop short of a Linux monitor's edge (a gap at the bottom of a secondary monitor)? Avalonia's X11
Screen.WorkingAreais the screen clipped by_NET_WORKAREA, one rectangle for the whole desktop, which mutter shrinks to avoid a panel on any monitor: a bottom panel on a shorter laptop screen cuts the same strip off every taller neighbour. Never readScreen.WorkingAreadirectly; usescreen.GetActualWorkingArea()(Screen_Exts), which asksIShellProvider.GetScreenWorkingArea. Linux answers from the per-monitor_GTK_WORKAREAS_D<n>(LinuxScreenApi, a second X connection kept open because window fit asks on every zoom step) and falls back to Avalonia's value where the window manager does not publish it. Comparexprop -root _NET_WORKAREA _GTK_WORKAREAS_D0againstxrandr --listmonitors. - A hotkey in
igconfig.jsonchanges by itself, or the whole config fails to load?Hotkeyhas two texts and they are not interchangeable:KeyStringis the platform display text (KeyGesture.ToString("p"), which printsBackas "Backspace" andMetaas "Win"/"β"),InvariantKeyStringis the only one that may be persisted. Never persist the display text:KeyGesture.Parsecannot read it back, and it reads a digit string as the enum value ("1" ->Key.Cancel).Hotkey.ParseFromis the sole reverse ofToInvariantString, accepts the display spellings too, and never throws;JsonHotkeyArrayConverterdrops an entry it cannot parse so one bad string cannot failConfig.Load. - "The process cannot access the file 'igconfig.json'" when several instances close together? Every instance saves the same file, so a write must go through
BHelper.WriteAllTextSharedAsync(stage + rename + retry) and a read throughBHelper.OpenReadShared; a newFile.WriteAllText/File.OpenReadon a config-dir file reintroduces it. See "Concurrent file writes". - Serialization fails? Validate JSON converter exists in
Common/Types/JsonTypeConverters/ - Cache not evicting? Check
MipmapTileCache.MAX_CACHED_TILES(100) and LRU promotion logic - AOT trimming errors? Review trimmer warnings; add
[DynamicallyAccessedMembers]annotations or custom converters
- Cross-platform? Define interface in
Common/ServiceProviders/; implement in each platform'sCommon/ServiceProviders/(Win32, Linux, Mac) and register viaCore.APIor service slots - User-facing string? Add to
Lang.csenum, then reference viaLang.GetString(LangId.KeyName) - New codec? Inherit from codec base (SkiaCodec or MagickCodec); register in
PhotoManager - UI control? Inherit from
PhControlorPhWindow; usePhReactivefor ViewModels - Settings? Add property to
Config.cs; if complex JSON, create converter inJsonTypeConverters/ - Async operation with cancellation? Accept
CancellationToken ct, pass to subtasks, callct.ThrowIfCancellationRequested() - Memory-critical? Test with large images (8192Γ8192+) and profile cache behavior
- Threaded work? Use
Lockfor shared state; avoid blocking UI thread; prefer async/await over Thread