From 3d02a3999e08a733a23c0c1c7e00aac233a99d06 Mon Sep 17 00:00:00 2001 From: FedyaLight Date: Thu, 5 Nov 2026 15:16:43 +0300 Subject: [PATCH 1/2] Fix cross-browser reading sync and add resync and side margins --- docs/displays.md | 20 +++++- docs/platforms.md | 7 +- tests/README.md | 4 +- tests/synchronization.mjs | 147 ++++++++++++++++++++++++++++++++++++++ web/js/controller.js | 70 ++++++++++++++++-- web/js/display-profile.js | 5 +- web/js/prompter.js | 9 ++- web/js/session.js | 6 +- web/js/stage.js | 5 ++ web/js/store.js | 6 ++ web/js/ui.js | 1 + web/locales/messages.json | 24 +++++++ 12 files changed, 287 insertions(+), 17 deletions(-) create mode 100644 tests/synchronization.mjs diff --git a/docs/displays.md b/docs/displays.md index dcefbec..4475b95 100644 --- a/docs/displays.md +++ b/docs/displays.md @@ -10,9 +10,16 @@ messages over the existing WebRTC transport. **Leading teleprompter** chooses the screen that owns the scrolling position and pace. Other screens follow its passage, including their own line wrapping. The protocol carries the words at adjacent source line starts and progress between -them; followers interpolate those word positions in their layout. Matching -viewports and layout settings preserve exact pixels. Different font sizes or -margins use the word anchor even when the screen dimensions are identical. +them; followers and controller previews interpolate those word positions in +their layout. Exact pixels are reused only when the viewport, settings and +measured word positions match. Differences in browser font metrics and line +wrapping use the word anchor even when the screen dimensions are identical. + +The **Synchronize screens** button (two curved arrows below the preview) asks +the leading screen for a fresh measurement and aligns the controller and other +screens to its current passage. It preserves playback, speed and voice mode. +Confirmation appears after the connected screens acknowledge synchronization; +if a screen cannot respond, check the connection and retry. Play/pause, speed, section jumps, pedal scrolling and seeking from any reader control the shared session. The controller resolves sections once against the @@ -58,6 +65,13 @@ horizontal/vertical mirroring. Omitted overrides inherit the shared controller settings. **Use shared settings** removes overrides while retaining the name. An explicit left/right margin takes precedence over the symmetric side margin. +Shared **Advanced → Margins → Left margin / Right margin** controls adjust the +two sides independently, as percentages of screen width. They are saved in +settings profiles and portable backups. Initially both inherit **Side margins**; +double-click a side's displayed value to restore inheritance. A display's own +symmetric margin overrides the shared horizontal margins, and its explicit +left/right overrides take precedence over that. + The reader URL includes `?screen=…`, a stable display identifier distinct from its network connection ID. Keep/bookmark this link to reopen the same display profile. Profiles are saved on the reader and operator, survive reload and are diff --git a/docs/platforms.md b/docs/platforms.md index d31b958..eb31967 100644 --- a/docs/platforms.md +++ b/docs/platforms.md @@ -78,8 +78,11 @@ A reader greeting includes viewport, script version (`sid`), `session` and receive targeted `settings`, `script`/`scriptPart`, then `session` with `to/tag/state`. They wait for the complete matching script before restoring. `state.sync` acknowledges the tag, blocking stale preview state until then. -Equal viewports use exact pixels; different viewports use word and line offsets. -Playback, countdown, speed and voice index resume. +Equal viewports, layout settings and measured geometry (`geometry`) use exact +pixels; otherwise readers and previews use word and line anchors. Playback, +countdown, speed and voice index resume. A targeted `resync` request obtains a +fresh `resynced` snapshot from the leading reader; the controller restores its +preview and sends tagged sessions to followers, waiting for their acknowledgments. Reader taps apply play/pause and send that absolute command to the controller, so multiple controllers cannot toggle it twice. Quick mirror changes diff --git a/tests/README.md b/tests/README.md index ee81235..5a3b4f7 100644 --- a/tests/README.md +++ b/tests/README.md @@ -20,7 +20,7 @@ In another terminal: ```sh npm install --prefix work/testing playwright peer@1.0.2 -work/testing/node_modules/.bin/playwright install chromium +work/testing/node_modules/.bin/playwright install chromium webkit EFIR_URL=http://localhost:18765 node tests/relay.mjs EFIR_URL=http://localhost:18765 EFIR_LAN_URL=http://YOUR_WIFI_IP:18765 \ node tests/browser.mjs @@ -29,6 +29,7 @@ EFIR_URL=http://localhost:18765 EFIR_LAN_URL=http://YOUR_WIFI_IP:18765 \ EFIR_URL=http://localhost:18765 node tests/layout.mjs EFIR_URL=http://localhost:18765 node tests/remotes.mjs EFIR_URL=http://localhost:18765 node tests/displays.mjs +EFIR_URL=http://localhost:18765 node tests/synchronization.mjs node tests/hosting.mjs ``` @@ -42,6 +43,7 @@ On macOS, `http://0.0.0.0:18765` can provide an insecure Chromium context for | `hosting.mjs` | Static hosting without marker, real PeerJS broker, delayed cross-profile WebRTC, established link during broker loss | | `performance.mjs` | Three-screen frame, storage, transport and main-thread activity; hidden Gamepad and reduced-motion/offscreen demo lifecycle | | `displays.mjs` | Three readers with different wraps, format shading, actual preview geometry, targeted calibration, duplicate links, seeking, reload, rotation, leader failover and stale preview recovery | +| `synchronization.mjs` | Chromium/WebKit passage alignment with accumulated layout differences, manual synchronization, independent shared margins and profile/backup persistence; optionally set `EFIR_SCRIPT` to a local TXT file | | `remotes.mjs` | Held key edges, modified keys, button learning, saved mappings, editing/dialog guards, nudge release, browser Gamepad signals | | `layout.mjs` | Six UI languages, light/dark, narrow/landscape/tablet/desktop, dialogs, icon-only exit and fullscreen labels | diff --git a/tests/synchronization.mjs b/tests/synchronization.mjs new file mode 100644 index 0000000..11303e6 --- /dev/null +++ b/tests/synchronization.mjs @@ -0,0 +1,147 @@ +// Browser-engine layout differences must not accumulate into a different passage. +import { chromium, webkit } from '../work/testing/node_modules/playwright/index.mjs'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; + +const base = process.env.EFIR_URL || 'http://localhost:18765'; +const chrome = await chromium.launch(), safari = await webkit.launch(); +const errors = []; +const wait = async (fn, message, ms = 10000) => { + const end = Date.now() + ms; + while (Date.now() < end) { if (await fn()) return; await new Promise(r => setTimeout(r, 60)); } + throw new Error(message); +}; +const script = process.env.EFIR_SCRIPT ? await readFile(process.env.EFIR_SCRIPT, 'utf8') + : Array.from({ length: 100 }, (_, i) => `Scene ${i + 1}. The camera follows the speaker across the room.\nThe operator checks the reading screen before starting the next take.\nA short pause gives everyone enough time to prepare.`).join('\n\n'); +const geometry = page => page.locator('.stage').first().evaluate(stage => ({ + max: stage.querySelector('.text').offsetHeight - stage.offsetHeight, + marker: parseFloat(stage.style.getPropertyValue('--my')), + tops: [...stage.querySelectorAll('.w')].map(w => w.offsetTop + w.offsetHeight / 2), +})); +const wordY = (page, i, selector = '.stage') => page.locator(selector).first().evaluate((stage, i) => { + const word = stage.querySelector(`.w[data-i="${i}"]`); + const offset = new DOMMatrix(getComputedStyle(stage.querySelector('.scroller')).transform).m42; + return word.offsetTop + word.offsetHeight / 2 + offset - parseFloat(stage.style.getPropertyValue('--my')); +}, i); +const pads = page => page.locator('.text').first().evaluate(el => { + const style = getComputedStyle(el); return [parseFloat(style.paddingLeft), parseFloat(style.paddingRight)]; +}); +const hasPads = async (page, left, right) => { const values = await pads(page); return Math.abs(values[0] - left) < .02 && Math.abs(values[1] - right) < .02; }; +// Compare the passage at the reading line without importing sync code. +const passage = page => page.locator('.stage').first().evaluate(stage => { + const y = parseFloat(stage.style.getPropertyValue('--my')) - new DOMMatrix(getComputedStyle(stage.querySelector('.scroller')).transform).m42; + const words = [...stage.querySelectorAll('.w')]; + const lines = words.filter((w, i) => !i || w.offsetTop !== words[i - 1].offsetTop); + let k = lines.findIndex(w => w.offsetTop + w.offsetHeight / 2 > y); + if (k < 0) k = lines.length - 1; + const a = lines[Math.max(0, k - 1)], b = lines[k]; + const ay = a.offsetTop + a.offsetHeight / 2, by = b.offsetTop + b.offsetHeight / 2; + return Number(a.dataset.i) + (by > ay ? (y - ay) / (by - ay) : 0) * (Number(b.dataset.i) - Number(a.dataset.i)); +}); +async function range(ctl, key, value) { + const input = ctl.locator(`[data-k="${key}"] input`); + await input.fill(String(value)); await input.dispatchEvent('input'); +} +async function scrub(ctl, fraction) { + const box = await ctl.locator('.scrub-track').boundingBox(); + await ctl.mouse.click(box.x + fraction * box.width, box.y + box.height / 2); +} +try { + const ctl = await chrome.newPage({ locale: 'ru-RU', viewport: { width: 1500, height: 1000 } }); + let dropResyncReplies = false; + await ctl.routeWebSocket('**/ws*', route => { + const server = route.connectToServer(); + server.onMessage(message => { + if (dropResyncReplies && JSON.parse(String(message)).t === 'resynced') return; + route.send(message); + }); + }); + await ctl.addInitScript(() => { window.efirNative = { version: 1, platform: 'mac', role: 'controller', capabilities: {}, postMessage() {} }; }); + const phone = await safari.newPage({ locale: 'ru-RU', viewport: { width: 844, height: 390 } }); + for (const p of [ctl, phone]) p.on('pageerror', e => errors.push(e.message)); + await ctl.goto(base + '/#/c/SYNC'); await phone.goto(base + '/?screen=phone#/p/SYNC'); + await ctl.locator('.ctl.has-prompter').waitFor(); + await ctl.locator('button[data-view="edit"]').first().click(); + await ctl.locator('.ed-text').fill(script); + await ctl.locator('button[data-view="live"]').first().click(); + await range(ctl, 'fontSize', 64); + await ctl.locator('[data-k="countdown"] [data-v="0"]').click(); + await wait(async () => (await phone.locator('.text').innerText()).includes(script.trim().split('\n').at(-1)), 'script reaches WebKit'); + await Promise.all([ctl.evaluate(() => document.fonts.ready), phone.evaluate(() => document.fonts.ready)]); + // The generated fixture exercises accumulated metric drift deterministically. + // A supplied script uses its natural Chromium/WebKit wrapping differences. + if (!process.env.EFIR_SCRIPT) { + await phone.addStyleTag({ content: '.text p { margin-bottom: calc(var(--paragraph-gap) + 1px); }' }); + await phone.setViewportSize({ width: 846, height: 390 }); + await phone.waitForFunction(() => document.querySelector('.stage').offsetWidth === 846); + await phone.setViewportSize({ width: 844, height: 390 }); + await wait(async () => await ctl.locator('.stage').first().evaluate(el => el.offsetWidth) === 844, 'reader geometry returns to the same viewport'); + } + const [c, p] = await Promise.all([geometry(ctl), geometry(phone)]); + const common = c.tops.map((top, i) => i).filter(i => i > 0 && i < c.tops.length * .85 && i > c.tops.length * .3 + && c.tops[i] !== c.tops[i - 1] && p.tops[i] !== p.tops[i - 1]); + const i = common.sort((a, b) => Math.abs(c.tops[b] - p.tops[b]) - Math.abs(c.tops[a] - p.tops[a]))[0]; + assert.ok(Math.abs(c.tops[i] - p.tops[i]) > 30, 'fixture has accumulated measured layout drift'); + await scrub(ctl, (c.tops[i] - c.marker) / c.max); + await wait(async () => Math.abs(await wordY(phone, i)) < 2 && Math.abs(await wordY(ctl, i)) < 2, + 'a late-script seek must put the same word at both reading lines'); + + // The operator can repair a stale preview without moving the reader. + await ctl.addStyleTag({ content: '.preview-primary .text p { margin-bottom: calc(var(--paragraph-gap) + 2px); }' }); + const beforeSync = await wordY(phone, i); + await ctl.getByRole('button', { name: 'Синхронизировать экраны', exact: true }).click(); + await wait(async () => (await ctl.locator('#toasts').textContent()).includes('Экраны синхронизированы'), 'manual sync acknowledged'); + assert.ok(Math.abs(await wordY(phone, i) - beforeSync) < 2, 'manual sync preserves the reader passage'); + assert.ok(Math.abs(await wordY(ctl, i) - beforeSync) < 2, 'manual sync repairs the preview immediately'); + + const follower = await chrome.newPage({ locale: 'ru-RU', viewport: { width: 500, height: 900 } }); + follower.on('pageerror', e => errors.push(e.message)); + await follower.goto(base + '/?screen=follower#/p/SYNC'); + await follower.locator('.prompter.has-script.has-ctl').waitFor(); + await ctl.locator('.speed-range').fill('6'); await ctl.locator('.speed-range').dispatchEvent('input'); + await ctl.locator('[data-a="toggle"]').click(); + await phone.locator('.prompter.playing').waitFor(); + for (let sample = 0; sample < 5; sample++) { + await new Promise(r => setTimeout(r, 1500)); + if (sample === 1) { + await ctl.locator('[data-a="sync"]').click(); + await wait(async () => await ctl.locator('[data-a="sync"]').getAttribute('aria-busy') === 'false', 'all readers acknowledge sync during playback'); + } + const positions = await Promise.all([passage(ctl), passage(phone), passage(follower)]); + assert.ok(Math.max(...positions) - Math.min(...positions) < 10, 'playback keeps all browser engines at the same passage: ' + positions); + assert.equal(await phone.locator('.prompter.playing').count(), 1, 'sync preserves playback'); + } + await ctl.locator('[data-a="toggle"]').click(); + await follower.close(); + + await ctl.locator('.settings-more').evaluate(el => el.open = true); + await ctl.locator('[data-g="margins"]').evaluate(el => el.open = true); + await range(ctl, 'leftPad', 3); await range(ctl, 'rightPad', 17); + await wait(() => hasPads(phone, 25.32, 143.48), 'independent margins reach reader'); + await ctl.locator('[data-a="profile-save"]').click(); + await ctl.getByRole('textbox', { name: 'Название профиля' }).fill('Asymmetric'); + await ctl.locator('.profile-form button').click(); + await range(ctl, 'leftPad', 10); await range(ctl, 'rightPad', 10); + const saved = await ctl.locator('.profile-select option').filter({ hasText: 'Asymmetric' }).getAttribute('value'); + await ctl.locator('.profile-select').selectOption(saved); + await wait(() => hasPads(phone, 25.32, 143.48), 'profile restores independent margins'); + await ctl.reload(); await ctl.locator('.ctl.has-prompter').waitFor(); + assert.equal(await ctl.locator('[data-k="leftPad"] input').inputValue(), '3'); + assert.equal(await ctl.locator('[data-k="rightPad"] input').inputValue(), '17'); + const backup = await ctl.evaluate(async () => (await import('./js/store.js')).store.backup()); + await ctl.evaluate(async backup => { const { store } = await import('./js/store.js'); store.restoreBackup(backup); }, backup); + await ctl.reload(); await ctl.locator('.ctl.has-prompter').waitFor(); + assert.equal(await ctl.locator('[data-k="rightPad"] input').inputValue(), '17', 'backup retains optional numeric margins'); + await ctl.locator('[data-k="leftPad"] output').dblclick(); + await range(ctl, 'sidePad', 12); + await wait(() => hasPads(phone, 101.28, 143.48), 'reset side inherits symmetric margin while the other side stays independent'); + dropResyncReplies = true; + await ctl.locator('[data-a="sync"]').click(); + await wait(async () => (await ctl.locator('#toasts').textContent()).includes('Не удалось синхронизировать экраны'), 'a lost reply reports a failed synchronization'); + dropResyncReplies = false; + assert.equal(await ctl.locator('[data-a="sync"]').isEnabled(), true, 'synchronization can be retried after a timeout'); + await ctl.locator('[data-a="sync"]').click(); + await wait(async () => (await ctl.locator('#toasts').textContent()).includes('Экраны синхронизированы'), 'synchronization succeeds on retry'); + assert.deepEqual(errors, []); + console.log(JSON.stringify({ result: 'PASS', measuredDrift: c.tops[i] - p.tops[i], checked: ['Chromium/WebKit word alignment', 'late seek', 'manual sync', 'three-screen playback', 'sync during playback', 'independent margins', 'profile/reload/backup', 'symmetric inheritance', 'lost sync reply/timeout/retry'] })); +} finally { await chrome.close(); await safari.close(); } diff --git a/web/js/controller.js b/web/js/controller.js index 8fa02e2..fbc3852 100644 --- a/web/js/controller.js +++ b/web/js/controller.js @@ -18,7 +18,7 @@ import { relayout } from './prompter.js'; import { mountLanHelp } from './lan.js'; import { icon, toast, qrSvg, modal, closeModals, loadScript, roomUrl, copyText } from './ui.js'; -const LAYOUT_KEYS = ['fontSize', 'fontFamily', 'fontWeight', 'lineHeight', 'letterSpacing', 'uppercase', 'sidePad', 'topPad', 'bottomPad', 'markerPos', 'align']; +const LAYOUT_KEYS = ['fontSize', 'fontFamily', 'fontWeight', 'lineHeight', 'letterSpacing', 'uppercase', 'sidePad', 'leftPad', 'rightPad', 'topPad', 'bottomPad', 'markerPos', 'align']; const FORMATS = [ { id: '1600x1000', label: '16:10 · монитор', w: 1600, h: 1000 }, @@ -56,6 +56,8 @@ const GROUPS = [ ] }, { id: 'margins', title: 'Поля', items: [ ['sidePad', 'range', { label: 'По бокам', min: 0, max: 35, step: 0.5, unit: '%' }], + ['leftPad', 'range', { label: 'Левое поле', min: 0, max: 35, step: 0.5, unit: '%' }], + ['rightPad', 'range', { label: 'Правое поле', min: 0, max: 35, step: 0.5, unit: '%' }], ['topPad', 'range', { label: 'Сверху до текста', min: 0, max: 100, step: 1, unit: '%' }], ['bottomPad', 'range', { label: 'Снизу после текста', min: 0, max: 150, step: 1, unit: '%' }], ] }, @@ -124,6 +126,7 @@ export function mountController(root, code) { let compareFormats = localStorage.getItem('efir.compareFormats') !== 'false'; let preferredScreen = localStorage.getItem('efir.leadingScreen'); const pendingSync = new Map(), readiness = new Map(); + let resync = null, resyncTimer = 0; const readerActions = platform.has('showPrompter') ? `
@@ -183,6 +186,7 @@ export function mountController(root, code) {
+ @@ -315,6 +319,7 @@ export function mountController(root, code) { select.value = primary || ''; select.disabled = !ps.length; $('[data-a="display"]').disabled = !selected; + refreshSyncButton(); refreshPrimaryPreview(); } function refreshPrimaryPreview() { @@ -347,6 +352,7 @@ export function mountController(root, code) { $('.pm-all').onchange = e => { allScreens = e.target.checked; localStorage.setItem('efir.allScreens', allScreens); fitPreview(); }; $('.pm-compare').onchange = e => { compareFormats = e.target.checked; localStorage.setItem('efir.compareFormats', compareFormats); fitPreview(); }; $('.pm-screen').onchange = e => { + cancelResync(); primary = e.target.value; remote = latest.get(primary) || null; const peer = room.peersOf('prompter').find(p => p.id === primary); preferredScreen = screenId(peer); localStorage.setItem('efir.leadingScreen', preferredScreen); @@ -363,6 +369,7 @@ export function mountController(root, code) { function profileFor(peer) { return cleanDisplayProfile(profiles[screenId(peer)] || peer?.hello?.profile); } function updateDisplay(peer, profile) { if (!peer) return; + cancelResync(); const id = screenId(peer); profiles[id] = cleanDisplayProfile(profile); store.saveDisplayProfile(id, profiles[id]); room.send('display', { to: peer.id, profile: profiles[id] }); relayout(stage, engine, fitPreview); renderStatus(); frames?.request(); @@ -377,7 +384,7 @@ export function mountController(root, code) { const prev = primary; primary = (available.find(p => screenId(p) === preferredScreen) || available[0])?.id || null; remote = latest.get(primary) || null; - if (prev !== primary) { relayout(stage, engine, fitPreview); if (remote) restoreSession(stage, engine, remote); configureFollowers(); frames?.request(); } + if (prev !== primary) { cancelResync(); relayout(stage, engine, fitPreview); if (remote) restoreSession(stage, engine, remote); configureFollowers(); frames?.request(); } } function renderStatus() { @@ -437,6 +444,7 @@ export function mountController(root, code) { room.addEventListener('leave', (e) => { if (e.detail.role === 'prompter') { pendingSync.delete(e.detail.id); readiness.delete(e.detail.id); latest.delete(e.detail.id); seen.delete(e.detail.id); + finishResync(); if (e.detail.id === primary) { primary = null; pickPrimary(); fitPreview(); toast(t('Суфлёр отключился')); } } fitPreview(); renderStatus(); @@ -446,6 +454,24 @@ export function mountController(root, code) { room.addEventListener('message', (e) => { const m = e.detail; if (m.role !== 'prompter') return; + if (m.t === 'resynced') { + if (!resync || resync.leader !== primary || m.from !== primary || m.request !== resync.tag || m.state?.sid !== cur.id + ':' + cur.updated) return; + stage.invalidate(); fitPreview(); + remote = { ...m.state, from: m.from }; + restoreSession(stage, engine, remote); + tracker.setPosition(engine.voiceIdx); + holdUntil = seekHold = 0; + commandTag = ''; + resync.confirming = true; + for (const peer of room.peersOf('prompter')) { + if (peer.id === primary) continue; + pendingSync.set(peer.id, resync.tag); + room.send('session', { to: peer.id, tag: resync.tag, state: remote }); + } + configureFollowers(); frames?.request(); + finishResync(); + return; + } if (m.t === 'control') { if (m.c === 'seek' && m.state?.sid === cur.id + ':' + cur.updated) seekRemote(sessionPosition(stage, m.state), !!m.smooth); else if (m.c === 'nudge' && Number.isFinite(m.lines)) cmd('nudge', { v: m.lines * stage.s.fontSize * stage.s.lineHeight }); @@ -464,6 +490,7 @@ export function mountController(root, code) { if (pendingSync.has(m.from)) { if (pendingSync.get(m.from) !== m.sync) return; pendingSync.delete(m.from); + finishResync(); } const peer = room.peersOf('prompter').find(p => p.id === m.from); if (!peer) return; @@ -498,9 +525,9 @@ export function mountController(root, code) { const link = room.linkInfo(); const lat = link && link.rtt != null ? link.rtt / 2000 : 0.01; const ahead = m.playing && m.cd <= 0 && m.mode !== 'voice' ? stage.pxPerSec(m.speed) * lat : 0; - const target = m.pos + ahead; + const target = stage.clamp(sessionPosition(stage, m) + ahead); const d = target - engine.pos; - if (Math.abs(d) > stage.h * 0.4) engine.pos = target; + if (!engine.moving || Math.abs(d) > stage.h * 0.4) engine.pos = target; else engine.pos += d * 0.35; if (engine.target != null && Math.abs(engine.target - target) < 2) engine.target = null; } @@ -520,7 +547,34 @@ export function mountController(root, code) { } // Commands + function refreshSyncButton() { + const button = $('[data-a="sync"]'); + button.disabled = !primary || !!resync; + button.setAttribute('aria-busy', String(!!resync)); + } + function cancelResync() { + clearTimeout(resyncTimer); + if (resync) for (const [peer, tag] of pendingSync) { if (tag === resync.tag) pendingSync.delete(peer); } + resync = null; refreshSyncButton(); + } + function finishResync() { + if (!resync?.confirming || [...pendingSync.values()].includes(resync.tag)) return; + cancelResync(); toast(t('Экраны синхронизированы'), 'ok'); + } + function synchronize() { + if (!primary || resync) return; + flushSeek(); + resync = { tag: uid(), leader: primary, confirming: false }; + refreshSyncButton(); + // Ask the reader for a fresh measurement, rather than pushing a possibly + // drifting preview position back to the person currently reading. + for (const peer of room.peersOf('prompter')) room.send('settings', { s: settings, profile: profileFor(peer), to: peer.id }); + sendScript(); + room.send('resync', { to: primary, request: resync.tag }); + resyncTimer = setTimeout(() => { cancelResync(); toast(t('Не удалось синхронизировать экраны — проверьте соединение'), 'bad'); }, 6000); + } function cmd(c, m = {}) { + cancelResync(); sessionEstablished = true; if ((c === 'toggle' || c === 'pause') && engine.mode === 'voice') { voiceToggle(); return; } if (c === 'toggle') c = engine.playing ? 'pause' : 'play'; @@ -557,6 +611,7 @@ export function mountController(root, code) { function positionState(pos) { return captureSession(stage, { pos, snapshot: () => ({ ...engine.snapshot(), pos }) }, cur.id + ':' + cur.updated); } let seekSendT = 0, seekPending = null; function seekRemote(p, smooth = false) { + cancelResync(); sessionEstablished = true; seekLocal(p, smooth); const cp = stage.clamp(p); @@ -637,6 +692,7 @@ export function mountController(root, code) { else if (a === 'read') platform.send('showPrompter'); else if (a === 'mirror') set('mirrorH', !settings.mirrorH); else if (a === 'display') configureDisplay(room.peersOf('prompter').find(p => p.id === primary)); + else if (a === 'sync') synchronize(); else if (a === 'window') openWindow(); else if (a === 'keys') openKeys(); else if (a === 'new') addScript(newScript(), true); @@ -941,6 +997,7 @@ export function mountController(root, code) { // Settings let sendSetT = 0, sendSetPending = false; function commitSettings(layout) { + cancelResync(); store.saveSettings(settings); if (layout) relayout(stage, engine, () => stage.setSettings(displaySettings(settings, profileFor(room.peersOf('prompter').find(p => p.id === primary))))); else stage.setSettings(displaySettings(settings, profileFor(room.peersOf('prompter').find(p => p.id === primary)))); @@ -991,7 +1048,7 @@ export function mountController(root, code) { refreshControls(); } function renderItem([k, type, o]) { - const def = DEFAULTS[k]; + const def = DEFAULTS[k] ?? settings.sidePad; switch (type) { case 'range': return `
@@ -1019,7 +1076,7 @@ export function mountController(root, code) { GROUPS.forEach(g => g.items.forEach(([k, type, o]) => { const row = body.querySelector(`[data-k="${k}"]`); if (!row) return; - const v = settings[k]; + const v = settings[k] ?? settings.sidePad; if (type === 'orient') { row.querySelectorAll('[data-v]').forEach(b => b.classList.toggle('on', b.dataset.v === `${+settings.mirrorH}-${+settings.mirrorV}`)); return; } if (type === 'range') { const inp = row.querySelector('input'); @@ -1200,6 +1257,7 @@ export function mountController(root, code) { views.destroy(); frames.destroy(); stage.destroy(); previewObserver.disconnect(); clearInterval(freshnessTimer); + clearTimeout(resyncTimer); clearTimeout(edTimer); clearTimeout(saveTimer); document.removeEventListener('visibilitychange', saveBeforeHide); platform.events.removeEventListener('visible', saveBeforeHide); diff --git a/web/js/display-profile.js b/web/js/display-profile.js index f6037f3..394ad2d 100644 --- a/web/js/display-profile.js +++ b/web/js/display-profile.js @@ -18,7 +18,10 @@ export function cleanDisplayProfile(value) { return result; } export function displaySettings(settings, profile) { - return { ...settings, ...cleanDisplayProfile(profile).overrides }; + const overrides = cleanDisplayProfile(profile).overrides; + // A display's symmetric override replaces the shared horizontal margins; + // its own explicit left/right overrides still take precedence. + return { ...settings, ...(overrides.sidePad != null ? { leftPad: null, rightPad: null } : {}), ...overrides }; } // Geometry, not color/mirror, decides whether a pixel position can be reused. export function layoutSignature(settings) { diff --git a/web/js/prompter.js b/web/js/prompter.js index 74b56dc..a7f2574 100644 --- a/web/js/prompter.js +++ b/web/js/prompter.js @@ -198,6 +198,12 @@ export function mountPrompter(root, code) { pendingSession = m; applySession(); break; + case 'resync': + stage.invalidate(); stage.measure(); + room.send('resynced', { to: m.from, request: m.request, + state: { ...captureSession(stage, engine, script ? script.id + ':' + script.updated : null), voiceState } }); + sendState(true); frames?.request(); + break; case 'cmd': command(m.c, m); break; } }); @@ -477,8 +483,9 @@ export function mountPrompter(root, code) { let lastSent = 0, prevSig = '', stateFlush = 0; function sendState(force = false) { if (!room.peersOf('controller').length || !platform.visible) return; + stage.measure(); const now = performance.now(); - const sig = `${engine.pos.toFixed(1)}|${engine.playing}|${engine.speed}|${Math.ceil(engine.cd)}|${engine.mode}|${engine.voiceIdx}|${voiceState}|${stage.w}x${stage.h}|${stage.max}|${stage.layout}|${commandTag}|${JSON.stringify(profile)}|${script?.id}:${script?.updated}|${syncTag}`; + const sig = `${engine.pos.toFixed(1)}|${engine.playing}|${engine.speed}|${Math.ceil(engine.cd)}|${engine.mode}|${engine.voiceIdx}|${voiceState}|${stage.w}x${stage.h}|${stage.geometry}|${stage.layout}|${commandTag}|${JSON.stringify(profile)}|${script?.id}:${script?.updated}|${syncTag}`; if (!force && sig === prevSig) return; if (!force && now - lastSent < 33) { if (!stateFlush) stateFlush = setTimeout(() => { stateFlush = 0; sendState(); }, 33 - (now - lastSent)); diff --git a/web/js/session.js b/web/js/session.js index edceb46..b4ed3fa 100644 --- a/web/js/session.js +++ b/web/js/session.js @@ -1,5 +1,5 @@ // Restore positions by word and line offset across different screen sizes. -// Equal sizes preserve exact pixels. +// Equal measured layouts preserve exact pixels, including across browsers. export function captureSession(stage, engine, sid) { stage.measure(); const word = stage.wordAt(engine.pos); @@ -11,7 +11,7 @@ export function captureSession(stage, engine, sid) { const a = lines[lo] ?? 0, b = lines[lo + 1] ?? a; const ay = stage.tops?.[a] ?? stage.markerY, by = stage.tops?.[b] ?? ay; const f = (y - ay) / (by > ay ? by - ay : stage.s.fontSize * stage.s.lineHeight); - return { ...engine.snapshot(), sid, atStart: engine.pos < .01, atEnd: stage.max > 0 && engine.pos >= stage.max, layout: stage.layout, anchor: { a, b, f }, vw: stage.w, vh: stage.h, word, + return { ...engine.snapshot(), sid, atStart: engine.pos < .01, atEnd: stage.max > 0 && engine.pos >= stage.max, layout: stage.layout, geometry: stage.geometry, anchor: { a, b, f }, vw: stage.w, vh: stage.h, word, offset: (engine.pos + stage.markerY - top) / (stage.s.fontSize * stage.s.lineHeight) }; } @@ -21,7 +21,7 @@ export function sessionPosition(stage, state) { stage.measure(); if (state.atStart) return 0; if (state.atEnd) return stage.max; - if (state.vw === stage.w && state.vh === stage.h && (!state.layout || state.layout === stage.layout)) return stage.clamp(Number.isFinite(state.pos) ? state.pos : 0); + if (state.vw === stage.w && state.vh === stage.h && state.layout === stage.layout && state.geometry === stage.geometry) return stage.clamp(Number.isFinite(state.pos) ? state.pos : 0); const anchor = state.anchor; if (anchor && Number.isInteger(anchor.a) && Number.isInteger(anchor.b) && Number.isFinite(anchor.f)) { const last = stage.words.length - 1; diff --git a/web/js/stage.js b/web/js/stage.js index a47f1b0..b308fc1 100644 --- a/web/js/stage.js +++ b/web/js/stage.js @@ -226,9 +226,14 @@ export class Stage { this.tops[i] = e.offsetTop + e.offsetHeight / 2; } this.lines = []; + // Settings and viewport dimensions alone do not guarantee equal wrapping + // in WebKit and Chromium. Cache the measured word geometry with the layout. + let hash = 2166136261; for (let i = 0; i < n; i++) { if (!i || Math.abs(this.tops[i] - this.tops[i - 1]) > 1) this.lines.push(i); + hash = Math.imul(hash ^ Math.round(this.tops[i] * 2), 16777619); } + this.geometry = `${n}:${this.max}:${hash >>> 0}`; this.secTops = [...this.text.querySelectorAll('.sec')].map(e => e.offsetTop); } diff --git a/web/js/store.js b/web/js/store.js index d77aebf..e99a2ba 100644 --- a/web/js/store.js +++ b/web/js/store.js @@ -15,6 +15,8 @@ export const DEFAULTS = { uppercase: false, align: 'left', sidePad: 8, // Percent of screen width. + leftPad: null, // Null inherits the symmetric side margin. + rightPad: null, topPad: 40, // Percent of screen height before the text. bottomPad: 70, // Percent of screen height after the text. theme: 'studio', @@ -219,6 +221,10 @@ function cleanSettings(value) { if (!value || typeof value !== 'object') return result; for (const [key, def] of Object.entries(DEFAULTS)) { const v = value[key]; + if (key === 'leftPad' || key === 'rightPad') { + if (Number.isFinite(v)) result[key] = Math.max(0, Math.min(35, v)); + continue; + } if (typeof v !== typeof def) continue; if (typeof def === 'number') { if (Number.isFinite(v)) result[key] = v; } else if (typeof def === 'boolean') result[key] = v; diff --git a/web/js/ui.js b/web/js/ui.js index 8afc3e5..74ba777 100644 --- a/web/js/ui.js +++ b/web/js/ui.js @@ -5,6 +5,7 @@ import { platform } from './platform.js'; const P = { star: '', refresh: '', + sync: '', arrow: '', back: '', bolt: '', diff --git a/web/locales/messages.json b/web/locales/messages.json index bb2efb7..5ef25fb 100644 --- a/web/locales/messages.json +++ b/web/locales/messages.json @@ -3400,6 +3400,30 @@ "在 GitHub 上加星", "GitHub पर स्टार दें", "أضف نجمة على GitHub" + ], + "Синхронизировать экраны": [ + "Синхронизировать экраны", + "Synchronize screens", + "Sincronizar pantallas", + "同步屏幕", + "स्क्रीन सिंक्रनाइज़ करें", + "مزامنة الشاشات" + ], + "Экраны синхронизированы": [ + "Экраны синхронизированы", + "Screens synchronized", + "Pantallas sincronizadas", + "屏幕已同步", + "स्क्रीन सिंक्रनाइज़ हो गई हैं", + "تمت مزامنة الشاشات" + ], + "Не удалось синхронизировать экраны — проверьте соединение": [ + "Не удалось синхронизировать экраны — проверьте соединение", + "Could not synchronize screens — check the connection", + "No se pudieron sincronizar las pantallas — comprueba la conexión", + "无法同步屏幕,请检查连接", + "स्क्रीन सिंक्रनाइज़ नहीं हो सकीं — कनेक्शन जाँचें", + "تعذرت مزامنة الشاشات — تحقق من الاتصال" ] } } From f7ac015d3e5625c506847f88d8c6616f52579f3d Mon Sep 17 00:00:00 2001 From: FedyaLight Date: Thu, 5 Nov 2026 15:23:31 +0300 Subject: [PATCH 2/2] Prepare Efir 1.4.1 release --- android/app/build.gradle.kts | 4 +-- desktop/Cargo.lock | 2 +- desktop/Cargo.toml | 2 +- desktop/package-lock.json | 4 +-- desktop/package.json | 2 +- desktop/tauri.conf.json | 2 +- docs/releases/1.4.1.md | 53 ++++++++++++++++++++++++++++++ mac/Info.plist | 4 +-- mac/project.yml | 4 +-- tests/RustServerHarness/Cargo.lock | 2 +- 10 files changed, 66 insertions(+), 13 deletions(-) create mode 100644 docs/releases/1.4.1.md diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 2b973dd..7691c63 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -17,8 +17,8 @@ android { applicationId = "app.efir.android" minSdk = 26 targetSdk = 35 - versionCode = 7 - versionName = "1.4.0" + versionCode = 8 + versionName = "1.4.1" testInstrumentationRunner = "app.efir.android.EfirTestRunner" } sourceSets["main"].assets.srcDir(layout.buildDirectory.dir("generated/assets")) diff --git a/desktop/Cargo.lock b/desktop/Cargo.lock index 638510c..75f6f8b 100644 --- a/desktop/Cargo.lock +++ b/desktop/Cargo.lock @@ -1089,7 +1089,7 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" [[package]] name = "efir-desktop" -version = "1.4.0" +version = "1.4.1" dependencies = [ "axum", "cpal", diff --git a/desktop/Cargo.toml b/desktop/Cargo.toml index 24627e8..6abed0c 100644 --- a/desktop/Cargo.toml +++ b/desktop/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "efir-desktop" -version = "1.4.0" +version = "1.4.1" edition = "2021" license = "MIT" description = "Free teleprompter with remote control over local Wi-Fi" diff --git a/desktop/package-lock.json b/desktop/package-lock.json index e064a94..0fff5d3 100644 --- a/desktop/package-lock.json +++ b/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "efir-desktop", - "version": "1.4.0", + "version": "1.4.1", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "efir-desktop", - "version": "1.4.0", + "version": "1.4.1", "devDependencies": { "@tauri-apps/cli": "2.12.0" } diff --git a/desktop/package.json b/desktop/package.json index d8ce184..8fc6f63 100644 --- a/desktop/package.json +++ b/desktop/package.json @@ -1,6 +1,6 @@ { "name": "efir-desktop", - "version": "1.4.0", + "version": "1.4.1", "private": true, "scripts": { "dev": "tauri dev", diff --git a/desktop/tauri.conf.json b/desktop/tauri.conf.json index bf12c28..c9baec8 100644 --- a/desktop/tauri.conf.json +++ b/desktop/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "Efir", - "version": "1.4.0", + "version": "1.4.1", "identifier": "app.efir.desktop", "build": { "frontendDist": "bootstrap" diff --git a/docs/releases/1.4.1.md b/docs/releases/1.4.1.md new file mode 100644 index 0000000..ce45895 --- /dev/null +++ b/docs/releases/1.4.1.md @@ -0,0 +1,53 @@ +# Efir 1.4.1 + +## What's changed + +- Fix accumulated reading-position drift between phones and controller previews + when browsers wrap a long script differently. Exact pixel positions are reused + only when measured text geometry matches; other layouts follow word anchors. +- Add **Synchronize screens**, a two-arrow button below the preview. It aligns + the controller and connected screens to the leading reader's current passage + without restarting playback. Failed synchronization can be retried. +- Add independent **Left margin** and **Right margin** controls under + **Advanced → Margins**. Settings profiles and backups retain them. Initially + each side inherits **Side margins**; double-click its value to restore that + behavior. Individual screen overrides continue to take precedence. + +## Verification + +The reported long-script drift was reproduced between Chromium and WebKit. +Regression checks cover late-script seeking, three-screen playback, manual +synchronization while reading, lost replies and retry, and margin persistence. +Existing browser, display, remote, performance and relay checks passed; all +2,100 responsive layout checks passed across six languages. These checks use +isolated browser profiles and the production Swift relay; they do not replace +testing on physical phones. + +## Downloads and installation + +| Platform | File | Requirements | +| --- | --- | --- | +| macOS | `Efir-macOS.zip` | Apple Silicon or Intel, macOS 14+ | +| Windows | `Efir-Windows-x64.zip` | Windows 10/11 x64, Microsoft WebView2 Runtime | +| Linux x64 | `Efir-Linux-x64.deb` | Ubuntu 24.04+ or compatible dependencies | +| Linux ARM64 | `Efir-Linux-arm64.deb` | Ubuntu 24.04+ or compatible dependencies | +| Android | `Efir-Android.apk` | Android 8+ | + +Extract the entire Windows folder before launching `efir.exe`; keep `web/`, +`speech/` and the accompanying DLLs together. An NSIS installer is also provided. +Offline speech language models remain separate downloads. + +The macOS app is ad hoc signed and not notarized. Follow the documented +[macOS opening steps](../macos-distribution.md). Windows packages do not have +an Authenticode signature. + +Android 1.4.1 uses a new release signing certificate. Before upgrading an older +installation, export your scripts and settings, uninstall the old app, install +1.4.1 and restore the export. Future releases will reuse the new key, stored +outside the source checkout. + +Android certificate SHA-256: +`e85654fe8944ac49c6cc1d6e919106b76a1ae1e65044fe9a43225610050cd3bd`. + +`Efir-1.4.1-SHA256.txt` lists package checksums. Update the host application and +reload the connected reader pages so that the session uses the same version. diff --git a/mac/Info.plist b/mac/Info.plist index b05e424..21df3be 100644 --- a/mac/Info.plist +++ b/mac/Info.plist @@ -26,9 +26,9 @@ CFBundlePackageType APPL CFBundleShortVersionString - 1.4.0 + 1.4.1 CFBundleVersion - 7 + 8 NSAppTransportSecurity NSAllowsArbitraryLoadsInWebContent diff --git a/mac/project.yml b/mac/project.yml index 7aac062..7656869 100644 --- a/mac/project.yml +++ b/mac/project.yml @@ -33,8 +33,8 @@ targets: path: Info.plist properties: CFBundleDisplayName: Эфир - CFBundleShortVersionString: '1.4.0' - CFBundleVersion: '7' + CFBundleShortVersionString: '1.4.1' + CFBundleVersion: '8' CFBundleDevelopmentRegion: ru CFBundleLocalizations: ['ru', 'en', 'es', 'zh-Hans', 'hi', 'ar'] NSLocalNetworkUsageDescription: Эфир раздаёт суфлёр устройствам в вашей локальной сети. diff --git a/tests/RustServerHarness/Cargo.lock b/tests/RustServerHarness/Cargo.lock index 89a49ed..a45ff0e 100644 --- a/tests/RustServerHarness/Cargo.lock +++ b/tests/RustServerHarness/Cargo.lock @@ -177,7 +177,7 @@ dependencies = [ [[package]] name = "efir-desktop" -version = "1.4.0" +version = "1.4.1" dependencies = [ "axum", "futures-util",