File size: 9,973 Bytes
e079a73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
/**

 * Scene processing — validate → clamp → budget → wrap. Everything here is

 * generic; device variation enters only through the capabilities block and the

 * display profile, including its text normalization. Spec §5.

 *

 * Never rejects a frame: offending elements are dropped per-element and

 * reported via `dropped` / `degraded` (design doc §3.4.6; spec §4 refines the

 * design doc's image "reject" to per-element drop).

 */

import {TextMeasurer} from "../measurer/TextMeasurer"
import {TextWrapper} from "../wrapper/TextWrapper"
import type {DisplayProfile} from "../profiles/types"
import type {DiffableElement} from "./differ"
import type {SceneBox, SceneDisplayCapabilities, SceneElementInput, SceneTextStyle} from "./types"
import {processText, sourceLines} from "./text"
import type {SceneTextLayout} from "./types"
import {elementContentHash} from "./types"
import {sceneBudget} from "./budget"

export interface ProcessedScene {
  elements: DiffableElement[]
  degraded: boolean
  dropped: string[]
  textLayout?: Record<string, SceneTextLayout>
}

/** Reporting id for an element the app may not have named. */
function reportId(el: SceneElementInput, index: number): string {
  return el.id ?? `${el.type}[${index}]`
}

function clampBox(box: SceneBox, width: number, height: number): SceneBox | null {
  const x1 = Math.max(0, Math.floor(box.x))
  const y1 = Math.max(0, Math.floor(box.y))
  const x2 = Math.min(width, Math.floor(box.x) + Math.max(0, Math.floor(box.w)))
  const y2 = Math.min(height, Math.floor(box.y) + Math.max(0, Math.floor(box.h)))
  if (x2 <= x1 || y2 <= y1) return null
  return {x: x1, y: y1, w: x2 - x1, h: y2 - y1}
}

function boxShrunk(orig: SceneBox, clamped: SceneBox): boolean {
  return (
    clamped.x !== Math.floor(orig.x) ||
    clamped.y !== Math.floor(orig.y) ||
    clamped.w !== Math.floor(orig.w) ||
    clamped.h !== Math.floor(orig.h)
  )
}

/**

 * Line height for box-height→line-count math — ONLY when the profile declares

 * a calibrated `lineHeightPx`. Deriving one from full-canvas numbers proved

 * wrong on hardware (288/8=36px clipped the G2 nav instruction to one line;

 * the real container line height is smaller). Without calibration we return

 * null and the wrap step skips host-side height clipping entirely — text wraps

 * to the box WIDTH and the firmware clips vertically in-box, which is exactly

 * the legacy behavior.

 */
export function profileLineHeightPx(profile: DisplayProfile, _canvasHeight: number): number | null {
  return profile.lineHeightPx ?? null
}

/**

 * Process a raw scene against a device's capabilities + profile. Output is

 * diff-ready (text pre-wrapped, boxes clamped, content hashed) and reflects

 * exactly what will be sent — the diff baseline is post-processed by design

 * (spec §4).

 */
export function processScene(

  input: readonly SceneElementInput[],

  caps: SceneDisplayCapabilities,

  profile: DisplayProfile,

  includeTextLayout = false,

): ProcessedScene {
  const dropped: string[] = []
  let degraded = false
  const textLayout: Record<string, SceneTextLayout> = Object.create(null)

  const measurer = new TextMeasurer(profile)
  const wrapper = new TextWrapper(measurer)
  const lineHeight = profileLineHeightPx(profile, caps.height)

  // Validate + dedupe explicit ids (first occurrence wins; dupes are dev error).
  const seenIds = new Set<string>()
  const valid: {el: SceneElementInput; index: number}[] = []
  input.forEach((raw, index) => {
    if (!raw || typeof raw !== "object" || !raw.box) {
      dropped.push(reportId(raw ?? ({type: "text"} as SceneElementInput), index))
      degraded = true
      return
    }
    // Non-finite box numbers (NaN/±Infinity/non-number) would survive the
    // Math.* clamp below and poison the frame all the way to native ints.
    const b = raw.box
    if (![b.x, b.y, b.w, b.h].every((n) => typeof n === "number" && Number.isFinite(n))) {
      dropped.push(reportId(raw, index))
      degraded = true
      return
    }
    // Leading "~" is the differ's synthetic-id namespace — an app id there
    // would never match across frames (re-created every push). Normalize by
    // stripping; the rewrite is deterministic, so diffing stays stable.
    const el = raw.id?.startsWith("~") ? {...raw, id: raw.id.replace(/^~+/, "") || undefined} : raw
    if (el.id) {
      const key = `${el.type}:${el.id}`
      if (seenIds.has(key)) {
        dropped.push(reportId(el, index))
        degraded = true
        return
      }
      seenIds.add(key)
    }
    valid.push({el, index})
  })

  // Clamp + per-type limits, then budget in array order.
  let textBudget = caps.maxTextElements
  let imageBudget = caps.maxImageElements
  const out: DiffableElement[] = []
  const reserve = sceneBudget(profile)
  const append = (element: DiffableElement, index: number) => {
    if (reserve(element)) {
      out.push(element)
    } else {
      const id = element.id ?? `${element.type}[${index}]`
      dropped.push(id)
      delete textLayout[id]
      degraded = true
    }
  }

  for (const {el, index} of valid) {
    const clamped = clampBox(el.box, caps.width, caps.height)
    if (!clamped) {
      dropped.push(reportId(el, index))
      degraded = true
      continue
    }
    const shrunk = boxShrunk(el.box, clamped)
    if (shrunk) degraded = true

    if (el.type === "image") {
      // Images: a shrunk box can't be honored (we don't crop pixels host-side)
      // and per-image device limits are box-level (the firmware allocates the
      // component from the box). SGCs scale pixels to the box (phone-side
      // scaling — never on glasses).
      if (shrunk) {
        dropped.push(reportId(el, index))
        continue
      }
      if (caps.maxImagePx && (clamped.w > caps.maxImagePx.width || clamped.h > caps.maxImagePx.height)) {
        dropped.push(reportId(el, index))
        degraded = true
        continue
      }
      if (imageBudget <= 0) {
        dropped.push(reportId(el, index))
        degraded = true
        continue
      }
      imageBudget--
      append(
        {
          id: el.id,
          type: "image",
          box: clamped,
          data: el.data,
          contentHash: elementContentHash({type: "image", data: el.data}),
        },
        index,
      )
      continue
    }

    // text + rect share the text-container budget (design doc §3.4.6).
    if (textBudget <= 0) {
      dropped.push(reportId(el, index))
      degraded = true
      continue
    }
    textBudget--

    if (el.type === "rect") {
      append(
        {
          id: el.id,
          type: "rect",
          box: clamped,
          style: el.style,
          contentHash: elementContentHash({type: "rect", style: el.style}),
        },
        index,
      )
      continue
    }

    // Text: wrap on the phone into the (clamped) box. The box then carries
    // pre-wrapped text; firmware in-box wrap is a fallback, not the mechanism.
    // Height clipping only applies with a CALIBRATED line height — otherwise
    // the firmware clips vertically in-box (legacy behavior).
    const style: SceneTextStyle = el.style ?? {}
    if (style.maxLines !== undefined && (!Number.isFinite(style.maxLines) || style.maxLines < 1)) {
      dropped.push(reportId(el, index))
      degraded = true
      continue
    }
    if (style.maxLines !== undefined || style.textWindow || style.verticalAlign) {
      const processed = processText(el.text ?? "", clamped, style, profile)
      degraded ||= processed.degraded
      textLayout[reportId(el, index)] = processed.layout
      append(
        {
          id: el.id,
          type: "text",
          box: processed.box,
          text: processed.text,
          style: el.style,
          contentHash: elementContentHash({type: "text", text: processed.text, style: el.style}),
        },
        index,
      )
      continue
    }
    const maxLines = lineHeight ? Math.max(1, Math.floor(clamped.h / lineHeight)) : profile.maxLines
    const result = wrapper.wrap(el.text ?? "", {
      maxWidthPx: clamped.w,
      maxLines,
      ...(style.breakMode ? {breakMode: style.breakMode} : {}),
    })
    let lines = result.lines
    if (result.truncated) {
      degraded = true
      if (style.overflow === "ellipsis" && lines.length > 0) {
        // Trim the last line until it fits WITH the ellipsis appended —
        // otherwise the extra glyph can overflow the clamped box width.
        let last = lines[lines.length - 1]
        while (last.length > 0 && !measurer.fitsInWidth(`${last}…`, clamped.w)) {
          last = last.slice(0, -1)
        }
        // A box narrower than the ellipsis glyph itself gets an empty line —
        // never emit a line wider than the clamped box.
        const ellipsized = last.length > 0 || measurer.fitsInWidth("…", clamped.w) ? `${last}…` : ""
        lines = [...lines.slice(0, -1), ellipsized]
      }
    }
    if (includeTextLayout) {
      const all = sourceLines(el.text ?? "", clamped.w, style, profile)
      textLayout[reportId(el, index)] = {
        lines: all.slice(0, lines.length).map((line, i) => ({...line, text: lines[i]})),
        lineStarts: all.map((line) => line.start),
        capacity: maxLines,
        truncated: result.truncated,
      }
    }
    const wrappedText = lines.join("\n")
    append(
      {
        id: el.id,
        type: "text",
        box: clamped,
        text: wrappedText,
        style: el.style,
        contentHash: elementContentHash({type: "text", text: wrappedText, style: el.style}),
      },
      index,
    )
  }

  return {elements: out, degraded, dropped, ...(includeTextLayout ? {textLayout} : {})}
}