drawnui-react 0.1.0-preview.40 → 0.1.0-preview.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +57 -0
  2. package/SKIPPED.md +2 -2
  3. package/dist/controls/SkiaEditor.js +5 -4
  4. package/dist/controls/SkiaImage.d.ts +5 -0
  5. package/dist/controls/SkiaImage.js +32 -5
  6. package/dist/controls/SkiaLabel.d.ts +17 -2
  7. package/dist/controls/SkiaLabel.js +38 -12
  8. package/dist/controls/SkiaLabelFps.d.ts +0 -3
  9. package/dist/controls/SkiaLabelFps.js +1 -11
  10. package/dist/controls/SkiaLayout.js +33 -2
  11. package/dist/controls/SkiaScroll.d.ts +17 -0
  12. package/dist/controls/SkiaScroll.js +51 -6
  13. package/dist/controls/SkiaShell.d.ts +282 -0
  14. package/dist/controls/SkiaShell.js +972 -0
  15. package/dist/controls/SkiaSprite.js +5 -1
  16. package/dist/core/Accessibility.d.ts +12 -0
  17. package/dist/core/Accessibility.js +62 -14
  18. package/dist/core/Canvas.d.ts +50 -8
  19. package/dist/core/Canvas.js +126 -25
  20. package/dist/core/DesignerActions.d.ts +32 -0
  21. package/dist/core/DesignerActions.js +68 -0
  22. package/dist/core/Gestures.d.ts +1 -0
  23. package/dist/core/Props.d.ts +11 -0
  24. package/dist/core/Props.js +44 -0
  25. package/dist/core/SkiaControl.d.ts +26 -3
  26. package/dist/core/SkiaControl.js +64 -13
  27. package/dist/core/SkiaEffect.d.ts +12 -1
  28. package/dist/core/SkiaEffect.js +35 -8
  29. package/dist/core/SkiaImageManager.d.ts +100 -18
  30. package/dist/core/SkiaImageManager.js +309 -64
  31. package/dist/core/Styles.js +7 -1
  32. package/dist/core/Super.d.ts +2 -0
  33. package/dist/core/Super.js +2 -0
  34. package/dist/index.d.ts +2 -0
  35. package/dist/index.js +2 -0
  36. package/dist/react/SkiaShell.d.ts +8 -74
  37. package/dist/react/SkiaShell.js +163 -514
  38. package/dist/react/index.d.ts +24 -1
  39. package/dist/react/index.js +32 -5
  40. package/dist/react/reconciler.d.ts +12 -0
  41. package/dist/react/reconciler.js +22 -46
  42. package/package.json +24 -2
@@ -0,0 +1,11 @@
1
+ /** A declared set of property values: names as the C# properties (the JSX props of a control). */
2
+ export type ControlProps = Record<string, unknown>;
3
+ /**
4
+ * Assigns the changed values of `next` straight onto the control (same names as the C# properties), as the React
5
+ * renderer does with JSX props; a value `prev` had and `next` lacks goes back to the control's default. Handler values
6
+ * (functions) are swapped without invalidating. Then the control is invalidated as little as the change needs: a size
7
+ * change re-measures, a look change redraws, a transform change only repaints the composition.
8
+ */
9
+ export declare function ApplyProps(inst: {
10
+ Update(): void;
11
+ }, prev: ControlProps | null, next: ControlProps): void;
@@ -0,0 +1,44 @@
1
+ import { SkiaControl } from "./SkiaControl";
2
+ /** Not properties of the control: React's own keys. */
3
+ const SKIP = new Set(["children", "key", "ref"]);
4
+ /** Props that change how the subtree is composited, not what it contains: repaint, keep caches (DrawnUi RedrawCanvas). */
5
+ const REPAINT_ONLY = new Set(["TranslationX", "TranslationY", "TranslationZ", "Rotation", "RotationX", "RotationY", "RotationZ", "ScaleX", "ScaleY", "Scale", "SkewX", "SkewY", "AnchorX", "AnchorY", "Opacity"]);
6
+ /** Props that change only how a control looks, never its size (C# NeedDraw): an ImageComposite above redraws only its area. */
7
+ const isDrawOnly = (k) => k.endsWith("Color") || k === "FillGradient" || k === "StrokeGradient";
8
+ /**
9
+ * Assigns the changed values of `next` straight onto the control (same names as the C# properties), as the React
10
+ * renderer does with JSX props; a value `prev` had and `next` lacks goes back to the control's default. Handler values
11
+ * (functions) are swapped without invalidating. Then the control is invalidated as little as the change needs: a size
12
+ * change re-measures, a look change redraws, a transform change only repaints the composition.
13
+ */
14
+ export function ApplyProps(inst, prev, next) {
15
+ let changed = false, repaint = false, layout = false;
16
+ for (const k in next) {
17
+ if (SKIP.has(k) || (prev && prev[k] === next[k]))
18
+ continue;
19
+ inst[k] = next[k];
20
+ if (typeof next[k] === "function")
21
+ continue;
22
+ if (REPAINT_ONLY.has(k))
23
+ repaint = true;
24
+ else {
25
+ changed = true;
26
+ if (!isDrawOnly(k))
27
+ layout = true;
28
+ }
29
+ }
30
+ if (prev)
31
+ for (const k in prev)
32
+ if (!SKIP.has(k) && !(k in next)) {
33
+ inst[k] = new inst.constructor()[k];
34
+ changed = layout = true;
35
+ }
36
+ if (changed && prev) {
37
+ if (layout || !(inst instanceof SkiaControl))
38
+ inst.Update();
39
+ else
40
+ inst.UpdateDraw();
41
+ }
42
+ else if (repaint && prev)
43
+ inst.RepaintComposition?.();
44
+ }
@@ -215,6 +215,12 @@ export declare class SkiaControl {
215
215
  private OutsideClip;
216
216
  /** Drawn bounds in canvas pixels including transforms and effects margins (C# GetTransformedDirtyBounds). */
217
217
  GetTransformedDirtyBounds(): SKRect;
218
+ /**
219
+ * Where the control will be drawn next, from its current transform values: a translation set since the last render is
220
+ * already in (a composite parent erases and clips to this area before the child renders again).
221
+ */
222
+ GetCurrentDirtyBounds(): SKRect;
223
+ private MapBounds;
218
224
  /** Current cache, if any. */
219
225
  RenderObject?: CachedObject;
220
226
  private cacheDirty;
@@ -318,6 +324,12 @@ export declare class SkiaControl {
318
324
  * `Children` list drops only these, so a control's own parts keep their place.
319
325
  */
320
326
  IsChildrenItem: boolean;
327
+ /**
328
+ * C# UpdateNonStop (fluent): keeps frames coming while this control is on a canvas, for visuals that change by
329
+ * themselves (a time-driven shader, a clock drawn in code). An endless no-op animator, as C#; it waits for the canvas
330
+ * when the control is not on one yet and stops when the control is disposed. It holds the canvas at full frame rate.
331
+ */
332
+ UpdateNonStop(): this;
321
333
  AddSubView(_control: SkiaControl): void;
322
334
  InsertSubView(_index: number, control: SkiaControl): void;
323
335
  RemoveSubView(_control: SkiaControl): void;
@@ -489,6 +501,11 @@ export declare class SkiaControl {
489
501
  protected static SmartMax(a: number, b: number): number;
490
502
  /** DrawnUi SmartMin: smaller of two sizes, an infinite one loses. */
491
503
  protected static SmartMin(a: number, b: number): number;
504
+ /**
505
+ * Center (as DrawnUI for Rust and .NET): the box centered in the whole space, then moved by the full margin difference
506
+ * (start minus end), kept inside the space when it fits.
507
+ */
508
+ private static Centered;
492
509
  private static Align;
493
510
  /** Called after DrawingRect changed; layouts arrange children here. */
494
511
  protected OnLayoutChanged(): void;
@@ -642,10 +659,12 @@ export declare class SkiaControl {
642
659
  private static DeepArea;
643
660
  /**
644
661
  * DrawnUi IsParentIndependent: this control's size never changes the layout around it, so its own invalidation
645
- * stops here (ancestors composite again, nothing above re-measures). The parent re-measures it on draw when
646
- * NeedMeasure is set. Used by SkiaScroll for its scroll bars.
662
+ * stops here (ancestors composite again, nothing above re-measures). It measures itself again in its last slot when it
663
+ * draws with NeedMeasure set. Used by SkiaScroll for its scroll bars and by SkiaLabelFps.
647
664
  */
648
665
  IsParentIndependent: boolean;
666
+ /** The slot its parent last arranged it in (a parent-independent control measures itself again there). */
667
+ private arrangedIn?;
649
668
  /** Size or content may have changed: this control and all ancestors remeasure and re-record. */
650
669
  InvalidateMeasure(): void;
651
670
  /** Hit rect in pixels (no transforms in this port, so it is DrawingRect). */
@@ -682,7 +701,11 @@ export declare class SkiaControl {
682
701
  AnimateAsync(callback: (value: number) => void, onCancel?: () => void, ms?: number, easing?: Easing, cancel?: AbortSignal): Promise<void>;
683
702
  /** callback(start..end) over ms. */
684
703
  AnimateRangeAsync(callback: (value: number) => void, start: number, end: number, ms?: number, easing?: Easing, cancel?: AbortSignal): Promise<void>;
685
- /** One running animation per kind, like the per-property CancellationTokenSources in C#. */
704
+ /**
705
+ * One running animation per kind, like the per-property CancellationTokenSources in C#. A replaced animation rejects
706
+ * with an AbortError for code that awaits it, and is quiet otherwise (as a cancelled, unobserved Task in .NET): no
707
+ * "Uncaught (in promise)" in the console for fire-and-forget calls.
708
+ */
686
709
  private RunOwnAnimation;
687
710
  FadeToAsync(end: number, ms?: number, easing?: Easing, cancel?: AbortSignal): Promise<void>;
688
711
  ScaleToAsync(x: number, y: number, ms?: number, easing?: Easing, cancel?: AbortSignal): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { Super } from "./Super";
2
2
  import { SkiaStyles } from "./Styles";
3
3
  import { Colors, SKRect, ScaledSize, Thickness } from "./Types";
4
- import { RippleAnimator, SkiaValueAnimator } from "./Animators";
4
+ import { ActionOnTickAnimator, RippleAnimator, SkiaValueAnimator } from "./Animators";
5
5
  import { Easing } from "./Easing";
6
6
  import { AccessibilityModals, Aria } from "./Accessibility";
7
7
  import { ControlTappedEventArgs, GestureEventProcessingInfo, SKPoint, SkiaGesturesInfo, SkiaGesturesParameters, TouchActionEventArgs } from "./Gestures";
@@ -273,8 +273,14 @@ export class SkiaControl {
273
273
  return canvas.quickReject(q);
274
274
  }
275
275
  /** Drawn bounds in canvas pixels including transforms and effects margins (C# GetTransformedDirtyBounds). */
276
- GetTransformedDirtyBounds() {
277
- const r = this.ExpandedCacheRect(this.RenderingScale), m = this.RenderTransformMatrix;
276
+ GetTransformedDirtyBounds() { return this.MapBounds(this.RenderTransformMatrix); }
277
+ /**
278
+ * Where the control will be drawn next, from its current transform values: a translation set since the last render is
279
+ * already in (a composite parent erases and clips to this area before the child renders again).
280
+ */
281
+ GetCurrentDirtyBounds() { return this.MapBounds(this.CurrentMatrix(this.RenderingScale)); }
282
+ MapBounds(m) {
283
+ const r = this.ExpandedCacheRect(this.RenderingScale);
278
284
  if (!m)
279
285
  return r;
280
286
  const pts = Super.CK.Matrix.mapPoints(m, [r.Left, r.Top, r.Right, r.Top, r.Right, r.Bottom, r.Left, r.Bottom]);
@@ -449,6 +455,12 @@ export class SkiaControl {
449
455
  * `Children` list drops only these, so a control's own parts keep their place.
450
456
  */
451
457
  IsChildrenItem = false;
458
+ /**
459
+ * C# UpdateNonStop (fluent): keeps frames coming while this control is on a canvas, for visuals that change by
460
+ * themselves (a time-driven shader, a clock drawn in code). An endless no-op animator, as C#; it waits for the canvas
461
+ * when the control is not on one yet and stops when the control is disposed. It holds the canvas at full frame rate.
462
+ */
463
+ UpdateNonStop() { new ActionOnTickAnimator(this, () => { }).Start(); return this; }
452
464
  AddSubView(_control) { throw new Error(`DrawnUi: ${this.constructor.name} cannot host children`); }
453
465
  InsertSubView(_index, control) { this.AddSubView(control); }
454
466
  RemoveSubView(_control) { }
@@ -550,6 +562,7 @@ export class SkiaControl {
550
562
  }
551
563
  /** Places MeasuredSize inside destination per Margin + Horizontal/VerticalOptions -> DrawingRect. */
552
564
  Arrange(destination, _widthRequest, _heightRequest, scale) {
565
+ this.arrangedIn = destination;
553
566
  const m = this.Margin;
554
567
  const availL = destination.Left + m.Left * scale;
555
568
  const availT = destination.Top + m.Top * scale;
@@ -564,12 +577,20 @@ export class SkiaControl {
564
577
  availW = Math.ceil(availW * this.HorizontalFillRatio);
565
578
  if (this.VerticalFillRatio !== 1)
566
579
  availH = Math.ceil(availH * this.VerticalFillRatio);
567
- const w = this.HorizontalOptions === "Fill" ? availW : Math.min(availW, this.MeasuredSize.Pixels.Width - m.HorizontalThickness * scale);
568
- const h = this.VerticalOptions === "Fill" ? availH : Math.min(availH, this.MeasuredSize.Pixels.Height - m.VerticalThickness * scale);
580
+ // Fill stretches only an axis without a size request: with one, the requested size stays at the start (as DrawnUI for
581
+ // Rust and .NET; with LockRatio a single request sizes both axes)
582
+ const fillX = this.HorizontalOptions === "Fill" && this.WidthRequest < 0 && !(this.LockRatio !== 0 && this.HeightRequest >= 0);
583
+ const fillY = this.VerticalOptions === "Fill" && this.HeightRequest < 0 && !(this.LockRatio !== 0 && this.WidthRequest >= 0);
584
+ const w = fillX ? availW : Math.min(availW, this.MeasuredSize.Pixels.Width - m.HorizontalThickness * scale);
585
+ const h = fillY ? availH : Math.min(availH, this.MeasuredSize.Pixels.Height - m.VerticalThickness * scale);
569
586
  // Alignment happens inside the ORIGINAL box (Center/End of a capped control still center/end in the parent).
570
587
  const fullW = destination.Width - m.HorizontalThickness * scale, fullH = destination.Height - m.VerticalThickness * scale;
571
- const x = availL + SkiaControl.Align(this.HorizontalOptions, fullW, w);
572
- const y = availT + SkiaControl.Align(this.VerticalOptions, fullH, h);
588
+ const x = this.HorizontalOptions === "Center"
589
+ ? SkiaControl.Centered(destination.Left, destination.Width, w, (m.Left - m.Right) * scale)
590
+ : availL + SkiaControl.Align(this.HorizontalOptions, fullW, w);
591
+ const y = this.VerticalOptions === "Center"
592
+ ? SkiaControl.Centered(destination.Top, destination.Height, h, (m.Top - m.Bottom) * scale)
593
+ : availT + SkiaControl.Align(this.VerticalOptions, fullH, h);
573
594
  const old = this.DrawingRect;
574
595
  this.DrawingRect = SKRect.Create(x, y, w, h);
575
596
  this.FollowMatrix(old);
@@ -831,6 +852,16 @@ export class SkiaControl {
831
852
  return b;
832
853
  return a;
833
854
  }
855
+ /**
856
+ * Center (as DrawnUI for Rust and .NET): the box centered in the whole space, then moved by the full margin difference
857
+ * (start minus end), kept inside the space when it fits.
858
+ */
859
+ static Centered(start, space, size, shift) {
860
+ let at = start + (space - size) / 2 + shift;
861
+ if (size <= space)
862
+ at = Math.min(Math.max(at, start), start + space - size);
863
+ return at;
864
+ }
834
865
  static Align(o, avail, size) {
835
866
  if (o === "Center")
836
867
  return (avail - size) / 2;
@@ -881,6 +912,13 @@ export class SkiaControl {
881
912
  Render(ctx) {
882
913
  if (!this.IsVisible || this.Opacity <= 0 || this.IsDisposed)
883
914
  return;
915
+ // parent-independent: its own change stopped at it (the parent does not lay out again), so it measures itself again
916
+ // in the slot it was given, before it draws (C# IsParentIndependent)
917
+ const slot = this.arrangedIn;
918
+ if (this.IsParentIndependent && this.NeedMeasure && slot) {
919
+ this.Measure(slot.Width, slot.Height, ctx.Scale);
920
+ this.Arrange(slot, this.WidthRequest, this.HeightRequest, ctx.Scale);
921
+ }
884
922
  const canvas = ctx.Context.Canvas;
885
923
  const applyOpacity = this.Opacity < 1;
886
924
  // C# Left/Top: a cached control is blitted at an offset, no matrix and no save/restore around the subtree
@@ -1064,6 +1102,9 @@ export class SkiaControl {
1064
1102
  // includes what shadows/effects paint outside the box; image caches on whole pixels
1065
1103
  const r = cacheType === "Operations" ? this.ExpandedCacheRect(ctx.Scale) : this.AlignedCacheRect(ctx.Scale);
1066
1104
  const w = Math.max(1, Math.round(r.Width)), h = Math.max(1, Math.round(r.Height));
1105
+ // clean from here on: a change made while the content records (a child shows a sibling as it paints, an event raised
1106
+ // as a control draws) leaves the cache stale, and the next frame records it again
1107
+ this.cacheDirty = false;
1067
1108
  if (cacheType === "ImageDoubleBuffered") {
1068
1109
  // keep the previous frame as the fallback until the new cache exists
1069
1110
  if (this.RenderObject) {
@@ -1094,11 +1135,13 @@ export class SkiaControl {
1094
1135
  else {
1095
1136
  const main = ctx.Context.Surface;
1096
1137
  if (!main) {
1138
+ this.cacheDirty = true;
1097
1139
  this.PaintContent(ctx);
1098
1140
  return;
1099
1141
  } // no surface to derive from (e.g. recording): draw live
1100
1142
  const offscreen = main.makeSurface({ ...main.imageInfo(), width: w, height: h });
1101
1143
  if (!offscreen) {
1144
+ this.cacheDirty = true;
1102
1145
  if (!this.RenderObjectPrevious)
1103
1146
  this.PaintContent(ctx);
1104
1147
  return;
@@ -1112,7 +1155,6 @@ export class SkiaControl {
1112
1155
  this.RenderObject = new CachedObject(cacheType, r, ctx.Scale, undefined, image);
1113
1156
  this.RenderObject.Epoch = this.Superview?.GpuEpoch ?? 0;
1114
1157
  }
1115
- this.cacheDirty = false;
1116
1158
  }
1117
1159
  /**
1118
1160
  * C# ImageComposite (SetupRenderingWithComposition + CreateRenderingObject reuse): the offscreen surface survives
@@ -1185,7 +1227,7 @@ export class SkiaControl {
1185
1227
  const dirty = new Set();
1186
1228
  const rects = [...areas];
1187
1229
  const boundsOf = (c) => {
1188
- const out = [c.GetTransformedDirtyBounds()];
1230
+ const out = [c.GetCurrentDirtyBounds()]; // where it goes, from its current values, and where it was
1189
1231
  if (c.lastCompositeBounds)
1190
1232
  out.push(new SKRect(c.lastCompositeBounds.Left + offset.X, c.lastCompositeBounds.Top + offset.Y, c.lastCompositeBounds.Right + offset.X, c.lastCompositeBounds.Bottom + offset.Y));
1191
1233
  return out;
@@ -1615,10 +1657,12 @@ export class SkiaControl {
1615
1657
  }
1616
1658
  /**
1617
1659
  * DrawnUi IsParentIndependent: this control's size never changes the layout around it, so its own invalidation
1618
- * stops here (ancestors composite again, nothing above re-measures). The parent re-measures it on draw when
1619
- * NeedMeasure is set. Used by SkiaScroll for its scroll bars.
1660
+ * stops here (ancestors composite again, nothing above re-measures). It measures itself again in its last slot when it
1661
+ * draws with NeedMeasure set. Used by SkiaScroll for its scroll bars and by SkiaLabelFps.
1620
1662
  */
1621
1663
  IsParentIndependent = false;
1664
+ /** The slot its parent last arranged it in (a parent-independent control measures itself again there). */
1665
+ arrangedIn;
1622
1666
  /** Size or content may have changed: this control and all ancestors remeasure and re-record. */
1623
1667
  InvalidateMeasure() {
1624
1668
  this.NeedMeasure = true;
@@ -1802,14 +1846,21 @@ export class SkiaControl {
1802
1846
  AnimateRangeAsync(callback, start, end, ms = 250, easing = Easing.Linear, cancel) {
1803
1847
  return this.AnimateAsync((v) => callback(start + (end - start) * v), undefined, ms, easing, cancel);
1804
1848
  }
1805
- /** One running animation per kind, like the per-property CancellationTokenSources in C#. */
1849
+ /**
1850
+ * One running animation per kind, like the per-property CancellationTokenSources in C#. A replaced animation rejects
1851
+ * with an AbortError for code that awaits it, and is quiet otherwise (as a cancelled, unobserved Task in .NET): no
1852
+ * "Uncaught (in promise)" in the console for fire-and-forget calls.
1853
+ */
1806
1854
  RunOwnAnimation(kind, run, cancel) {
1807
1855
  this.ownAnimations.get(kind)?.abort();
1808
1856
  const controller = new AbortController();
1809
1857
  this.ownAnimations.set(kind, controller);
1810
1858
  cancel?.addEventListener("abort", () => controller.abort(), { once: true });
1811
- return run(controller.signal).finally(() => { if (this.ownAnimations.get(kind) === controller)
1859
+ const done = run(controller.signal).finally(() => { if (this.ownAnimations.get(kind) === controller)
1812
1860
  this.ownAnimations.delete(kind); });
1861
+ done.catch((e) => { if (e?.name !== "AbortError")
1862
+ throw e; }); // only the abort is quiet
1863
+ return done;
1813
1864
  }
1814
1865
  FadeToAsync(end, ms = 250, easing = Easing.Linear, cancel) {
1815
1866
  const start = this.Opacity;
@@ -59,6 +59,14 @@ export declare function IsPostRendererEffect(e: SkiaEffect): e is SkiaEffect & I
59
59
  * skipped, declared texture children that are not supplied sample transparent.
60
60
  */
61
61
  export declare class SkiaShaderEffect extends SkiaEffect implements IPostRendererEffect {
62
+ /**
63
+ * The clock origin of every shader's iTime: the page time (ms) of the first shader frame, one for all effects so
64
+ * they stay in step (C# ShaderTimeOriginNanos). iTime is a float32 on the GPU: counted from the page load, a tab open
65
+ * for days would move it in visible steps (0.125 s after 18 days).
66
+ */
67
+ static ShaderTimeOrigin?: number;
68
+ /** Seconds since the first shader frame for a page time in ms, taken in double before the GPU's float (C# GetShaderTime). */
69
+ static GetShaderTime(nowMs: number): number;
62
70
  /** Url of the .sksl file (fetched once, compiled once per text). */
63
71
  get ShaderSource(): string;
64
72
  set ShaderSource(v: string);
@@ -79,7 +87,7 @@ export declare class SkiaShaderEffect extends SkiaEffect implements IPostRendere
79
87
  MipmapMode: SkiaMipmapMode;
80
88
  /** Tile mode of the input textures. */
81
89
  TileMode: ShaderTileMode;
82
- /** Set every Render from the frame time (seconds); can be driven manually. */
90
+ /** Set every Render: seconds since the first shader frame (GetShaderTime); can be driven manually. */
83
91
  TimeSeconds: number;
84
92
  /** Shadertoy iMouse.xy, pixels relative to the control. */
85
93
  MouseCurrent: {
@@ -182,6 +190,9 @@ export declare class ShaderDoubleTexturesEffect extends SkiaShaderEffect {
182
190
  set PrimarySource(v: string);
183
191
  get SecondarySource(): string;
184
192
  set SecondarySource(v: string);
193
+ /** The textures it draws are held while it draws them (SkiaImageManager.Hold / Free). */
194
+ private HoldPrimary;
195
+ private HoldSecondary;
185
196
  private controlFrom?;
186
197
  private controlTo?;
187
198
  private primarySource;
@@ -45,6 +45,17 @@ const sourceCache = new Map();
45
45
  * skipped, declared texture children that are not supplied sample transparent.
46
46
  */
47
47
  export class SkiaShaderEffect extends SkiaEffect {
48
+ /**
49
+ * The clock origin of every shader's iTime: the page time (ms) of the first shader frame, one for all effects so
50
+ * they stay in step (C# ShaderTimeOriginNanos). iTime is a float32 on the GPU: counted from the page load, a tab open
51
+ * for days would move it in visible steps (0.125 s after 18 days).
52
+ */
53
+ static ShaderTimeOrigin;
54
+ /** Seconds since the first shader frame for a page time in ms, taken in double before the GPU's float (C# GetShaderTime). */
55
+ static GetShaderTime(nowMs) {
56
+ SkiaShaderEffect.ShaderTimeOrigin ??= nowMs;
57
+ return (nowMs - SkiaShaderEffect.ShaderTimeOrigin) / 1000;
58
+ }
48
59
  /** Url of the .sksl file (fetched once, compiled once per text). */
49
60
  get ShaderSource() { return this.shaderSource; }
50
61
  set ShaderSource(v) { if (this.shaderSource !== v) {
@@ -74,7 +85,7 @@ export class SkiaShaderEffect extends SkiaEffect {
74
85
  MipmapMode = "None";
75
86
  /** Tile mode of the input textures. */
76
87
  TileMode = "Clamp";
77
- /** Set every Render from the frame time (seconds); can be driven manually. */
88
+ /** Set every Render: seconds since the first shader frame (GetShaderTime); can be driven manually. */
78
89
  TimeSeconds = 0;
79
90
  /** Shadertoy iMouse.xy, pixels relative to the control. */
80
91
  MouseCurrent = { X: 0, Y: 0 };
@@ -380,7 +391,7 @@ export class SkiaShaderEffect extends SkiaEffect {
380
391
  }
381
392
  /** IPostRendererEffect: draws the shader over ctx.Destination (C# Render). */
382
393
  Render(ctx) {
383
- this.TimeSeconds = performance.now() / 1000;
394
+ this.TimeSeconds = SkiaShaderEffect.GetShaderTime(performance.now());
384
395
  const texture = this.GetPrimaryTexture(ctx, ctx.Destination);
385
396
  const built = this.CreateShader(ctx, texture);
386
397
  if (!built)
@@ -423,15 +434,18 @@ export class ShaderDoubleTexturesEffect extends SkiaShaderEffect {
423
434
  get PrimarySource() { return this.primarySource; }
424
435
  set PrimarySource(v) { if (this.primarySource !== v) {
425
436
  this.primarySource = v;
426
- this.primaryImage = undefined;
427
- this.LoadTexture(v, (i) => { this.primaryImage = i; this.Update(); });
437
+ this.HoldPrimary(undefined);
438
+ this.LoadTexture(v, (i) => { this.HoldPrimary(i); this.Update(); });
428
439
  } }
429
440
  get SecondarySource() { return this.secondarySource; }
430
441
  set SecondarySource(v) { if (this.secondarySource !== v) {
431
442
  this.secondarySource = v;
432
- this.secondaryImage = undefined;
433
- this.LoadTexture(v, (i) => { this.secondaryImage = i; this.secondary?.delete(); this.secondary = undefined; this.Update(); });
443
+ this.HoldSecondary(undefined);
444
+ this.LoadTexture(v, (i) => { this.HoldSecondary(i); this.secondary?.delete(); this.secondary = undefined; this.Update(); });
434
445
  } }
446
+ /** The textures it draws are held while it draws them (SkiaImageManager.Hold / Free). */
447
+ HoldPrimary(i) { const old = this.primaryImage; this.primaryImage = i; SkiaImageManager.Instance.Hold(i); SkiaImageManager.Instance.Free(old); }
448
+ HoldSecondary(i) { const old = this.secondaryImage; this.secondaryImage = i; SkiaImageManager.Instance.Hold(i); SkiaImageManager.Instance.Free(old); }
435
449
  controlFrom;
436
450
  controlTo;
437
451
  primarySource = "";
@@ -444,8 +458,18 @@ export class ShaderDoubleTexturesEffect extends SkiaShaderEffect {
444
458
  LoadTexture(url, done) {
445
459
  if (!url)
446
460
  return;
447
- SkiaImageManager.Instance.LoadImageAsync(url).then((i) => { if (url === this.primarySource || url === this.secondarySource)
448
- done(i); }).catch((e) => this.SendError(String(e)));
461
+ SkiaImageManager.Instance.LoadImageManagedAsync(url).then((i) => {
462
+ if (!i) {
463
+ this.SendError(`DrawnUi: cannot load image '${url}'`);
464
+ return;
465
+ }
466
+ if (url !== this.primarySource && url !== this.secondarySource) {
467
+ SkiaImageManager.Instance.Hold(i);
468
+ SkiaImageManager.Instance.Free(i);
469
+ return;
470
+ }
471
+ done(i);
472
+ });
449
473
  }
450
474
  /** C# Resize*LoadedBitmap: the file texture spans the parent box. */
451
475
  Resized(ctx, source, slot) {
@@ -520,6 +544,9 @@ export class ShaderDoubleTexturesEffect extends SkiaShaderEffect {
520
544
  this.resizedSecondary = undefined;
521
545
  this.controlFrom = undefined;
522
546
  this.controlTo = undefined;
547
+ this.primarySource = this.secondarySource = "";
548
+ this.HoldPrimary(undefined);
549
+ this.HoldSecondary(undefined);
523
550
  super.OnDisposing();
524
551
  }
525
552
  }
@@ -2,42 +2,124 @@ import type { Image } from "canvaskit-wasm";
2
2
  /** C# LoadPriority: order of the managed load queue. */
3
3
  export type LoadPriority = "Low" | "Normal" | "High";
4
4
  /**
5
- * Mirrors DrawnUi SkiaImageManager: loads + decodes image sources once and shares the decoded CanvasKit Image
6
- * between all SkiaImage instances using the same source (`ReuseBitmaps`). `LoadImageManagedAsync` goes through the
7
- * priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight, C# semaphore of 5; the same
8
- * source requested twice is fetched once), `LoadImageAsync` loads directly. `PreloadImages` warms the cache,
9
- * `CancelAll` drops what is still queued. Sources are URLs (absolute, or relative to the page like "images/photo.jpg").
5
+ * Mirrors DrawnUi SkiaImageManager (DrawnUi.Net): loads and decodes image sources, keeps the decoded images in a cache
6
+ * by source for `CacheLongevitySecs`, and shares one decoded image between every control on the same source
7
+ * (`ReuseBitmaps`; off, each caller gets a copy of its own of the one cached copy). `LoadImageManagedAsync` caches and
8
+ * goes through the priority queue (High > Normal > Low, at most `MaxParallelLoads` fetches in flight; the same source
9
+ * requested twice is fetched once); `LoadImageAsync` is a direct load that does not touch the cache. The cache keeps
10
+ * at most `CacheBudgetMb` megabytes of decoded pixels: over it, images no control holds go, the one held longest ago first
11
+ * (as DrawnUI for Rust's image cache); images a control holds never go. Keys are case-insensitive and local paths
12
+ * normalized (backslashes, a leading slash). Sources are URLs (absolute, or relative to the page like
13
+ * "images/photo.jpg").
14
+ *
15
+ * Ownership: CanvasKit images must be deleted by hand. The manager deletes an image it made once no holder draws it
16
+ * and the cache no longer keeps it; a control holds the image it shows (`Hold`) and lets it go (`Free`). Removing an
17
+ * entry from the cache (`RemoveFromCache`, `ClearCache`, expiry, the budget) never deletes an image a control holds.
10
18
  */
11
19
  export declare class SkiaImageManager {
12
20
  static readonly Instance: SkiaImageManager;
13
- /** Keep decoded images for reuse across controls (DrawnUi ReuseBitmaps). */
21
+ /** Share one decoded image between every control on the same source (DrawnUi ReuseBitmaps, on by default). */
14
22
  static ReuseBitmaps: boolean;
23
+ /** Use the cache at all (DrawnUi UseCache): off, every load fetches and decodes again. */
24
+ static UseCache: boolean;
25
+ /** Seconds a cached image is kept before the next load fetches it again (DrawnUi, 30 minutes). */
26
+ static CacheLongevitySecs: number;
27
+ /**
28
+ * Most megabytes of decoded pixels the cache keeps (DrawnUi CacheBudgetMb, 128 as DrawnUI for Rust; 0 or less = no
29
+ * limit). Images a control holds never go for it.
30
+ */
31
+ static CacheBudgetMb: number;
15
32
  /** Fetches in flight at once through the managed queue (C# CreateSemaphoreForLocalFiles: 5). */
16
33
  static MaxParallelLoads: number;
17
- /** C# CanReload: raised when a queued load failed so the caller may retry later. */
18
- CanReload?: (source: string, error: Error) => void;
34
+ /** Retry a failed load (DrawnUi EnableHttpRetry): up to HttpRetryMaxAttempts more times, 100, 200, 400 ms apart. */
35
+ static EnableHttpRetry: boolean;
36
+ static HttpRetryMaxAttempts: number;
37
+ /** Base address of relative sources (DrawnUi HttpBaseAddress); unset, they resolve against the page. */
38
+ static HttpBaseAddress?: string;
39
+ /**
40
+ * C# CanReload: raised when a load failed (with its source and why) so the caller may retry later, and when
41
+ * `IsLoadingLocked` is turned off (no arguments).
42
+ */
43
+ CanReload?: (source?: string, error?: Error) => void;
19
44
  private readonly cache;
20
- private readonly pending;
45
+ /** Every image the manager made and still tracks: cached ones and the copies it handed out. */
46
+ private readonly owned;
47
+ private readonly inflight;
21
48
  private readonly queue;
22
49
  private readonly waiting;
50
+ private readonly registered;
23
51
  private running;
52
+ private used;
53
+ private tick;
54
+ private locked;
55
+ private unlocked;
56
+ private unlock?;
24
57
  /** Queue diagnostics. */
25
58
  get QueuedCount(): number;
26
59
  get RunningCount(): number;
27
- /** Cached decoded image, if loaded already (C# GetFromCache). */
28
- GetFromCache(source: string): Image | undefined;
29
- /** Direct load without the queue (C# LoadImageAsync); cached and de-duplicated. Rejects on network/decode failure. */
30
- LoadImageAsync(source: string, signal?: AbortSignal): Promise<Image>;
60
+ /** Megabytes of decoded pixels the cache holds now (DrawnUi CacheMemoryMb). */
61
+ get CacheMemoryMb(): number;
62
+ /** The browser says it has no network. */
63
+ get IsOffline(): boolean;
64
+ /** While true, managed loads wait (DrawnUi IsLoadingLocked); turning it off lets them go and raises CanReload. */
65
+ get IsLoadingLocked(): boolean;
66
+ set IsLoadingLocked(value: boolean);
67
+ /** Registers a source under a name of its own (DrawnUi RegisterImage): loading `alias` loads `source`. */
68
+ RegisterImage(alias: string, source?: string): void;
69
+ /** Cache key: case-insensitive, a local path with forward slashes and no leading slash (DrawnUi GetCacheKey). */
70
+ static Key(source: string): string;
71
+ /** A holder (a control) draws this image now: it is not deleted until let go. Images the manager did not make are ignored. */
72
+ Hold(image: Image | undefined): void;
73
+ /** The holder no longer draws it: an image no holder draws and the cache does not keep is deleted. */
74
+ Free(image: Image | undefined): void;
75
+ /** Deletes an image nobody keeps any more. */
76
+ private Forget;
77
+ private Track;
78
+ /** A copy of an image of its own (ReuseBitmaps off), tracked so its holder frees it. */
79
+ private Copy;
80
+ /** What a caller gets of a cached image: the shared one, or a copy of its own (ReuseBitmaps off). */
81
+ private HandOut;
82
+ /** Puts an image in the cache for `cacheLongevitySecs` (DrawnUi AddToCache); false when cached already or caching is off. */
83
+ AddToCache(uri: string, image: Image, cacheLongevitySecs?: number): boolean;
84
+ /** Replaces the cached image of a source (DrawnUi UpdateInCache, minutes as .NET). */
85
+ UpdateInCache(uri: string, image: Image, cacheLongevityMinutes: number): void;
86
+ /** Drops the image from the cache, so the next load reads it again (DrawnUi RemoveFromCache); false when it was not cached. */
87
+ RemoveFromCache(uri: string): boolean;
88
+ /** Drops every cached image; images controls still show stay until they let them go. */
89
+ ClearCache(): void;
90
+ /** RemoveFromCache(source) or ClearCache(). */
91
+ Clear(source?: string): void;
92
+ private Drop;
93
+ private CleanupExpired;
94
+ /** Over the budget: the cached images no holder draws go, the one held longest ago first (DrawnUI for Rust trim). */
95
+ Trim(): void;
96
+ /** The cached image of a source, or undefined (DrawnUi GetFromCache): the shared one, or a copy (ReuseBitmaps off). */
97
+ GetFromCache(url: string): Image | undefined;
98
+ /** The cached image itself, whatever ReuseBitmaps says (DrawnUi GetFromCacheInternal). */
99
+ GetFromCacheInternal(url: string): Image | undefined;
100
+ /** The address a source is fetched from: its registered file, against HttpBaseAddress, stamped (Super.ResolveAssetUrl). */
101
+ private Address;
102
+ /** Fetches and decodes a source, retried when it fails (EnableHttpRetry); undefined when it could not be loaded. */
31
103
  private Fetch;
32
- /** Queued load (C# LoadImageManagedAsync): cached images resolve at once, the rest wait their turn by priority. */
33
- LoadImageManagedAsync(source: string, signal?: AbortSignal, priority?: LoadPriority): Promise<Image>;
104
+ /**
105
+ * Direct load without the queue and the cache (C# LoadImageAsync): a new image the caller owns (delete it, or hand it
106
+ * to a control that holds it); undefined when it could not be loaded.
107
+ */
108
+ LoadImageAsync(source: string, signal?: AbortSignal): Promise<Image | undefined>;
109
+ /**
110
+ * Queued, cached load (C# LoadImageManagedAsync): a cached image resolves at once, the rest wait their turn by priority;
111
+ * one fetch serves every request of the same source. Resolves to the shared image (ReuseBitmaps) or a copy of its own,
112
+ * undefined when it could not be loaded (CanReload hears why).
113
+ */
114
+ LoadImageManagedAsync(source: string, signal?: AbortSignal, priority?: LoadPriority): Promise<Image | undefined>;
115
+ private Enqueue;
116
+ /** A fresh image goes into the cache; the cached one (an equal source loaded meanwhile) wins. */
117
+ private Cached;
34
118
  private Pump;
35
119
  /** C# PreloadImage: warms the cache for one source; failures are ignored. */
36
120
  PreloadImage(source: string, priority?: LoadPriority): Promise<void>;
37
121
  /** Warms the cache so first paint of these images is instant (DrawnUi PreloadImages). Failures are ignored. */
38
122
  PreloadImages(sources: string[], priority?: LoadPriority): Promise<void>;
39
- /** Drops everything still waiting in the queue (C# CancelAll); loads already in flight finish. */
123
+ /** Drops everything still waiting in the queue (C# CancelAll): those loads resolve to nothing; loads in flight finish. */
40
124
  CancelAll(): void;
41
- /** Drops a cached image (or everything) — decoded images hold GPU/WASM memory. */
42
- Clear(source?: string): void;
43
125
  }