Skip to content

All your computers and your phone/iPhone, working as one desk. Screens, apps, files, clipboard, calls, texts, notifications, mouse and keyboard, shared between Mac, Windows, Linux , Android, Web and ios / ipados . Free and open source. No account, no cloud, and no shared network needed.

38.6 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// The phone in windows on this computer: its screen (mirror, with its sound), and phone apps each in a
// window of their own on a virtual display of the window's size (scrcpy new_display + flex, so
// resizing the window resizes the app). One scrcpy session per window (scrcpy.js); the window
// decodes the H.264 itself (phoneview-renderer.js) and sends touches, keys and scrolls back.
// Port of windows/phoneview.js: the desktop's own title bar (X11 and Wayland alike) with our toolbar
// under it, no Ctrl/Cmd swap.
//
// Events: 'change' — the window list changed; 'focus' — a phone window got or lost focus.
'use strict';

const path = require('path');
const { app, BrowserWindow, ipcMain, screen } = require('electron');
const { EventEmitter } = require('events');
const P = require('../shared/protocol.js');
const I18n = require('../shared/i18n.js');
const chat = require('../shared/phonechat');
const { Session, ACTION, TYPE } = require('./scrcpy');
const { NativeScreen } = require('../shared/nativescreen.js');
const { HevcToH264 } = require('../shared/hevc-h264.js'); // an iPhone's HEVC for a window that can't decode it
const IosUsbScreen = function (o) { return new (require('../shared/iosusb.js').IosUsbScreen)(o); }; // an iPhone on our own USB cable (iOS 27: picture and input), loaded when one is opened
const { uhidKey } = require('../shared/uhidkbd.js');
const { KeyState, ANDROID } = require('./android-keys');
const { MirrorSave } = require('../shared/mirror-save.js');

const T = P.T;
const NOTIFIED_MS = 60000; // how long a clicked notification waits for the unlock and wireless debugging
let nextId = 1;
let quitting = false; // a camera's window hides on close, but not on quit
app.on('before-quit', () => { quitting = true; });

class PhoneViews extends EventEmitter {
  constructor({ bridge, phone, getSettings, server, fileSend }) {
    super();
    Object.assign(this, { bridge, phone, getSettings, server, fileSend });
    this.views = new Map(); // id -> {id, kind, app, title, win, session, keys, size}
    bridge.views = this;
    this.on('change', () => bridge._tellPhone()); // its Screen and Camera pages follow the windows here
    this.notified = null; // {pkg, name, at, unlocked}: a clicked notification's app, waiting to open (openNotified)
    // The app in front on the phone, which its Accessibility says (the full app): Enter in a chat
    // app sends (shared/phonechat.js); a11y: the phone clicks Send itself.
    this.activeApp = '';
    this.a11y = false;
    server.on(`t:${T.PHONE_ACTIVE_APP}`, (m) => {
      if (!m || typeof m.pkg !== 'string') return;
      this.activeApp = m.pkg.slice(0, 200);
      this.a11y = true;
    });
    server.on('closed', () => {
      this.activeApp = '';
      this.a11y = false;
    });
    server.on(`t:${T.PHONE_AWAKE}`, (m) => this._awake(m));
    // The phone's own Show and Close (its Screen page): its screen in a window here (openScreen
    // decides how: wireless debugging, Wi-Fi first when on Bluetooth, or a popup saying what's
    // missing), or its windows here closed (not the hidden ones playing its sound).
    // The phone's own Camera page: its camera running here (the Camera tab's picture, the virtual
    // camera), back or front, or stopped.
    server.on(`t:${T.PHONE_CAMERA}`, (m) => {
      if (m && m.open === false) {
        for (const v of this.list()) if (v.kind === 'camera') this.close(v.id);
      } else this.openCamera({ facing: m && m.facing });
    });
    server.on(`t:${T.PHONE_MIRROR}`, (m) => {
      if (m && m.open === false) {
        for (const v of this.list()) this.close(v.id);
      } else this.openScreen();
    });
    bridge.on('change', () => this._openNotified());
    server.on('closed', () => { this.notified = null; });
    this.on('change', () => bridge._sound()); // a Native screen window with its sound takes the phone's own capture
    // The side rail's Screenshot and Record (shared/mirror-rail.js): copied and saved here.
    this.saver = new MirrorSave({
      electron: require('electron'),
      popup: (key, vars) => this.bridge.emit('popup', 'away', { key, vars }),
      name: () => (this.server.current && this.server.current.name) || this._i18n().t('Phone'),
    });
    ipcMain.on('phoneview:in', (e, m) => {
      const v = [...this.views.values()].find((x) => x.win && !x.win.isDestroyed() && x.win.webContents === e.sender);
      if (v && this.saver.handle(v.id, m)) return;
      if (v && m && typeof m === 'object') this._input(v, m);
    });
    // Files dropped on a phone window go to the phone (its Downloads).
    ipcMain.on('phoneview:drop', (e, paths) => {
      if (!Array.isArray(paths) || !paths.length || !this.server.current) return;
      const b = this.fileSend.sendBatch(paths.filter((p) => typeof p === 'string' && path.isAbsolute(p)).slice(0, 1000), 'send');
      if (b) this.bridge.emit('popup', 'away', `Sending ${b.name} to ${this.server.current.name}`);
    });
  }

  // The phone's sound on its own (no screen window): an audio-only session in a hidden window.
  sound(on) {
    const open = [...this.views.values()].find((v) => v.kind === 'sound');
    if (on && !open && this.bridge.serial) {
      this._open({ kind: 'sound', title: this._i18n().t('Phone sound'), titleKey: 'Phone sound', width: 200, height: 100, hidden: true, opts: { video: false, audio: true, control: false, audioSource: 'output' } });
    } else if (!on && open) this.close(open.id);
  }

  // The phone's microphone as a microphone here (Audio › Microphone, Android 11 or later): an
  // audio-only session capturing the phone's mic, in a hidden window that plays it into the
  // TwinDesk Microphone (Linux) or a virtual audio cable (phoneview-renderer.js picks it).
  mic(on, out = '') {
    const open = [...this.views.values()].find((v) => v.kind === 'mic' && !v.net);
    if (open && on && open.sink !== out) this.close(open.id); // another output picked: start again
    else if (open && on) return;
    if (on && this.bridge.serial) {
      this._open({ kind: 'mic', title: this._i18n().t('Phone microphone'), titleKey: 'Phone microphone', width: 200, height: 100, hidden: true, sink: out, opts: { video: false, audio: true, control: false, audioSource: 'mic' } });
    } else if (!on && open) this.close(open.id);
  }

  // The phone's sound captured by the phone itself (no wireless debugging, phone-bridge.js): a
  // hidden window with no adb session, fed what comes through the session.
  netSound(on) {
    const open = [...this.views.values()].find((v) => v.kind === 'netsound');
    if (on && !open) this._open({ kind: 'netsound', title: this._i18n().t('Phone sound'), titleKey: 'Phone sound', width: 200, height: 100, hidden: true });
    else if (!on && open) this.close(open.id);
  }

  // An iPhone's microphone (its app captures it, phone.mic.want): the same hidden window as the
  // Android one above, fed what comes through the session (netMicAudio) instead of an adb session.
  netMic(on, out = '') {
    const open = [...this.views.values()].find((v) => v.kind === 'mic' && v.net);
    if (open && on && open.sink !== out) this.close(open.id);
    else if (open && on) return;
    if (on) this._open({ kind: 'mic', net: true, title: this._i18n().t('Phone microphone'), titleKey: 'Phone microphone', width: 200, height: 100, hidden: true, sink: out });
    else if (open) this.close(open.id);
  }

  netMicAudio(m) {
    const p = { codec: 'pcm', p: Array.isArray(m.p) ? m.p.filter((x) => typeof x === 'string').slice(0, 20) : [] };
    for (const v of this.views.values()) if (v.kind === 'mic' && v.net) this._send(v, 'phoneview:netaudio', p);
  }

  netAudio(m) {
    const p = { codec: m.codec === 'pcm' ? 'pcm' : 'opus', p: Array.isArray(m.p) ? m.p.filter((x) => typeof x === 'string').slice(0, 10) : [] };
    for (const v of this.views.values()) if (v.kind === 'netsound' || (v.native && v.session && v.session.opts.audio)) this._send(v, 'phoneview:netaudio', p);
  }

  // A Native screen window (Mirroring › Native) that plays the phone's sound: phone-bridge.js asks
  // the phone for it (phone.sound.want).
  get nativeScreenSound() {
    return [...this.views.values()].some((v) => v.kind === 'screen' && v.native && v.session && !v.session.closed && v.session.opts.audio);
  }

  list() {
    return [...this.views.values()].filter((v) => v.kind !== 'sound' && v.kind !== 'netsound' && v.kind !== 'mic').map((v) => ({ id: v.id, kind: v.kind, app: v.app || null, title: v.title, facing: v.facing || null, torch: !!v.torch, quality: v.kind === 'camera' ? this.camMax || 1920 : undefined, screenOff: !!v.screenOff, native: !!v.native, shown: !!(v.win && !v.win.isDestroyed() && v.win.isVisible()), error: v.error || '' }));
  }

  get focused() {
    // Only a window that shows the phone (its picture came, its session runs): one that waits or
    // says why it closed has nothing to move in.
    return [...this.views.values()].some((v) => this._live(v) && v.win.isFocused());
  }

  _live(v) {
    return !!(v.win && !v.win.isDestroyed() && v.size && v.session && !v.session.closed);
  }

  // Multi-device: the pointer reached `side` of its screen; moving in a focused phone window never
  // crosses, so that side is held only when such a window reaches it (the pointer can be in the
  // window there). Anywhere else it crosses as always. Read from the windows, not the pointer: the
  // helper has the pointer by then. No side: any focused one.
  blocksEdge(side) {
    if (!side) return this.focused;
    return [...this.views.values()].some((v) => {
      if (!this._live(v) || !v.win.isFocused()) return false;
      const b = v.win.getBounds();
      // A native Wayland window doesn't know where it is (0,0 always): it can't be said to reach
      // the side, so the edge crosses as without the window (#356).
      if (process.env.XDG_SESSION_TYPE === 'wayland' && !b.x && !b.y) return false;
      const d = screen.getDisplayMatching(b).bounds;
      const near = 3;
      if (side === 'left') return b.x <= d.x + near;
      if (side === 'right') return b.x + b.width >= d.x + d.width - near;
      if (side === 'top') return b.y <= d.y + near;
      if (side === 'bottom') return b.y + b.height >= d.y + d.height - near;
      return false;
    });
  }

  // An iPhone whose USB cable is on a computer of the mesh (shared/ios-mesh.js cableFor), whichever
  // computer its app is connected to: its screen through that cable. False: none.
  openCable(phone, name) {
    const c = this.cableFor ? this.cableFor(phone) : null;
    if (!c) return false;
    if (c.relay) { this.openRelay({ ...c.relay, name }); return true; }
    const open = [...this.views.values()].find((v) => v.usb === c.udid);
    if (open) { open.win.show(); open.win.focus(); return true; }
    if (this.onUsbScreen) this.onUsbScreen(c.udid);
    const h = Math.min(860, screen.getPrimaryDisplay().workAreaSize.height - 80);
    this._open({ kind: 'screen', usb: c.udid, title: name || 'iPhone', titleKey: '', width: Math.round(h * 9 / 19.5), height: h, opts: { maxSize: 0, videoBitRate: 12000000, control: c.control } });
    return true;
  }

  // The session of the open window of the iPhone on our cable `udid` (shared/ios-cable.js shows it to the
  // mesh through it rather than opening a second stream), or null.
  usbSession(udid) {
    const v = [...this.views.values()].find((x) => x.usb === udid && x.session && !x.session.closed);
    return v ? v.session : null;
  }

  // A phone's screen through another computer (shared/phone-relay.js: an iPhone on its USB cable, an Android
  // phone connected to it): {host, id, os, name}. makeRelay(relay)
  // (main.js) makes its session. One window per iPhone: an open one comes to the front.
  openRelay(relay) {
    if (!relay || !relay.host || !relay.id || !this.makeRelay) return;
    const open = [...this.views.values()].find((v) => v.relay && v.relay.id === relay.id);
    if (open) return open.win.show(), open.win.focus();
    const h = Math.min(860, require('electron').screen.getPrimaryDisplay().workAreaSize.height - 80);
    this._open({ kind: 'screen', relay, title: relay.name || 'iPhone', titleKey: '', width: Math.round(h * 9 / 19.5), height: h, opts: {} });
  }

  openScreen() {
    const open = [...this.views.values()].find((v) => v.kind === 'screen');
    if (open) return open.win.show(), open.win.focus();
    const info = this.phone.info || {};
    const d = info.display || { w: 1080, h: 2400 };
    const work = screen.getPrimaryDisplay().workAreaSize;
    const h = Math.min(860, work.height - 80);
    const w = Math.round(h * Math.min(d.w, d.h) / Math.max(d.w, d.h));
    const name = (this.server.current && this.server.current.name) || this._i18n().t('Phone');
    const titleKey = (this.server.current && this.server.current.name) ? '' : 'Phone';
    // An iPhone whose USB cable is on a Mac of the mesh (shared/ios-links.js, main.js cableFor): its
    // screen through that Mac's cable (shared/phone-relay.js), not its Share Screen.
    const cur = this.server.current;
    const cable = cur && cur.os === 'ios' && this.cableFor ? this.cableFor(cur.deviceId) : null;
    if (cable && cable.relay) return this.openRelay({ ...cable.relay, name });
    if (cable && cable.udid) { // on our own cable
      if (this.onUsbScreen) this.onUsbScreen(cable.udid); // the background session gives way (one stream per device)
      return this._open({ kind: 'screen', usb: cable.udid, title: name, titleKey, width: w, height: h, opts: { maxSize: 0, videoBitRate: 12000000, control: cable.control } });
    }
    // Mirroring › Native (or Automatic without wireless debugging): the phone shares it itself.
    const native = this.bridge.mirrorVia === 'native';
    this._open({ kind: 'screen', native, title: name, titleKey, width: w, height: h, opts: this.bridge.sessionOpts('screen') });
  }

  // The phone's camera (Camera's switch, or the phone's Camera page; scrcpy's camera source, Android
  // 12 or later): facing 'back' or 'front'; the camera picks its best size up to 1920 on the long
  // side (a size it doesn't have would fail), at 30 fps. Its window opens hidden: the picture goes
  // to the Camera tab and the virtual camera (shared/vcam.js); show: the window too (Camera ›
  // Window), its light and zoom from the window's buttons. Closing the window only hides it. The other facing with it
  // running: the same window switches (_flip).
  openCamera(opts) {
    if (!this.cameraOn) return; // Camera is off here: the phone's Camera page says so (cameraState)
    opts = opts && typeof opts === 'object' ? opts : {};
    const want = opts.facing === 'front' || opts.facing === 'back' ? opts.facing : null;
    const open = [...this.views.values()].find((v) => v.kind === 'camera' && !v.ending);
    if ([1280, 1920, 3840].includes(opts.quality)) { // Camera › Quality: the long side (restarts a running one)
      const was = this.camMax || 1920;
      this.camMax = opts.quality;
      if (open && was !== opts.quality) this._flip(open, open.facing);
      this.emit('change');
      return;
    }
    if (open && opts.do) return this._camDo(open, opts.do);
    if (opts.do) return;
    if (open) {
      if (want && want !== open.facing) this._flip(open, want);
      if (opts.show) {
        open.win.show();
        open.win.focus();
      }
      return;
    }
    const facing = want || 'back';
    const titleName = (this.server.current && this.server.current.name) || '';
    const titleKey = titleName ? '{name} Camera' : 'Phone Camera';
    const name = this._i18n().t(titleKey, { name: titleName });
    const v = this._open({ kind: 'camera', title: name, titleKey, titleName, width: 854, height: 512, opts: this._cameraOpts(facing, opts.size), hidden: !opts.show });
    if (!v) return;
    v.facing = facing;
    this.emit('change'); // with its facing, for the tab and the phone
  }

  // Camera page's buttons for a running phone camera: its light and zoom (as its window's).
  _camDo(v, what) {
    const s = v.session;
    if (!s) return;
    if (what === 'torch') {
      v.torch = !v.torch;
      s.setTorch(v.torch);
      this._send(v, 'phoneview:opts', { torch: v.torch });
      this.emit('change');
    } else if (what === 'zoomIn') s.zoomIn();
    else if (what === 'zoomOut') s.zoomOut();
  }

  _cameraOpts(facing, size) {
    const cam = { videoSource: 'camera', cameraFacing: facing, cameraFps: 30, maxSize: this.camMax || 1920 };
    if (/^\d{2,5}x\d{2,5}$/.test(String(size || ''))) cam.cameraSize = size;
    return this.bridge.sessionOpts('camera', cam);
  }

  // Front or back in the same window: the phone lets go of one camera a moment after its session
  // ends, and a session started before that can't open the other (it ended, and its window with it).
  async _flip(v, facing) {
    v.facing = facing;
    v.error = '';
    const token = (v.flips = (v.flips || 0) + 1);
    const old = v.session;
    v.session = null; // first: its end isn't the window's
    if (old) old.stop();
    this.bridge._tellPhone();
    this.emit('change');
    for (let attempt = 0; attempt < 3; attempt++) {
      await new Promise((r) => setTimeout(r, 1200 + attempt * 1000));
      if (v.flips !== token || v.win.isDestroyed()) return;
      try {
        await this._start(v, this._cameraOpts(facing));
        return;
      } catch (e) {
        v.error = e.message;
      }
    }
    this.emit('change');
  }

  // For the phone's Camera page (phone-bridge.js): its camera here, which one, and the virtual camera.
  // The Camera tab's switch (settings.camera.on): off, no camera runs here.
  get cameraOn() {
    const c = this.getSettings().camera;
    return !c || c.on !== false;
  }

  cameraState() {
    if (!this.cameraOn) return { on: false, facing: null, error: 'Camera is off on this computer: turn it on in TwinDesk’s Camera tab there', virtual: false };
    const v = [...this.views.values()].find((x) => x.kind === 'camera' && !x.ending);
    return { on: !!v, facing: v ? v.facing : null, error: v ? v.error || '' : '', virtual: !!(this.vcam && this.vcam.ready) };
  }

  openApp(pkg, name) {
    const open = [...this.views.values()].find((v) => v.kind === 'app' && v.app === pkg);
    if (open) return open.win.show(), open.win.focus();
    const w = 412;
    const h = 860;
    // At least 2 pixels per point (sharp at 100% scaling); the dpi keeps 1 dp = 1 point, so the
    // app's text is as big as this computer's. The window's resizes use the same rule.
    const scale = Math.max(2, screen.getPrimaryDisplay().scaleFactor || 1);
    const [dw, dh] = require('../shared/appsize.js').appSize(w * scale, (h - 32) * scale); // a phone-like size (shared/appsize.js)
    const newDisplay = `${dw}x${dh}/${Math.round(160 * scale)}`;
    this._open({ kind: 'app', app: pkg, title: name || pkg, width: w, height: h, opts: this.bridge.sessionOpts('app', { newDisplay }) });
  }

  // A notification from the phone was clicked: wake it (unlocked: it answers at once), then open
  // the app once the phone is unlocked and wireless debugging is back (MIUI drops it while locked).
  openNotified(pkg, name) {
    if (!pkg || !this.server.current) return;
    const n = { pkg, name, at: Date.now(), unlocked: false, answered: false };
    this.notified = n;
    this.server.sendToClient({ t: T.PHONE_WAKE });
    // An older app doesn't answer: open it anyway.
    setTimeout(() => {
      if (this.notified !== n || n.answered) return;
      n.unlocked = true;
      this._openNotified();
    }, 2000);
  }

  _awake(m) {
    const n = this.notified;
    if (!n) return;
    n.answered = true;
    if (!m.unlocked) {
      const phone = (this.server.current && this.server.current.name) || 'the phone';
      return void (m.waiting && this.bridge.emit('popup', 'away', `Unlock ${phone} to open ${n.name || 'the app'}`));
    }
    n.unlocked = true;
    this._openNotified();
  }

  _openNotified() {
    const n = this.notified;
    if (!n || !n.unlocked) return;
    if (Date.now() - n.at > NOTIFIED_MS) return void (this.notified = null);
    const ble = this.server.current && this.server.current.transport === 'ble'; // Wi-Fi first: onNoAdb
    if ((this.bridge.state !== 'ready' || !this.bridge.serial) && !(ble && this.onNoAdb)) return;
    this.notified = null;
    const a = (this.phone.apps || []).find((x) => x.id === n.pkg);
    this.openApp(n.pkg, (a && a.name) || n.name);
  }

  // Mirroring's settings: the open phone screen window's Rotate and screen off ('rotate' | 'screenPower').
  screenAct(key) {
    if (key !== 'rotate' && key !== 'screenPower') return;
    const v = [...this.views.values()].find((x) => x.kind === 'screen' && !x.ending);
    if (!v) return;
    this._input(v, { t: 'nav', key });
    this.emit('change');
  }

  close(id) {
    const v = this.views.get(id);
    if (!v || !v.win || v.win.isDestroyed()) return;
    v.ending = true;
    v.win.close();
  }

  closeAll() {
    for (const v of [...this.views.values()]) this.close(v.id);
  }

  get screenWithSound() {
    return [...this.views.values()].some((v) => v.kind === 'screen' && v.session && v.session.opts.audio);
  }

  _i18n() {
    const settings = this.getSettings();
    return I18n.create(I18n.resolveLanguage(settings.ui && settings.ui.language, app.getLocale()));
  }

  _open({ kind, app, title, titleKey = '', titleName = '', width, height, opts, hidden = false, sink = '', native = false, net = false, relay = null, usb = '' }) {
    if (!this.bridge.serial && kind !== 'netsound' && !net && !native && !relay && !usb) {
      // Wireless debugging not up yet (just on Wi-Fi after Bluetooth): main.js opens it once it is.
      if (kind !== 'mic' && this.onNoAdb && this.onNoAdb({ kind, app, title, titleKey, titleName, width, height, opts, hidden })) return;
      return this.bridge.emit('popup', 'home', 'Set up wireless debugging on the Phone page first');
    }
    const id = nextId++;
    const win = new BrowserWindow({
      width, height, useContentSize: true, minWidth: 220, minHeight: 300, title, show: false, backgroundColor: '#000000',
      icon: path.join(__dirname, 'assets', 'icon.png'), autoHideMenuBar: true,
      // autoplayPolicy: the phone's sound plays without a click (its sound window is hidden, so a
      // click never comes: without this its AudioContext stays suspended and silent).
      webPreferences: { preload: path.join(__dirname, 'preload-phoneview.js'), contextIsolation: true, nodeIntegration: false, backgroundThrottling: false, autoplayPolicy: 'no-user-gesture-required' },
    });
    const v = { id, kind, app, title, win, sink, native, net, relay, usb, session: null, keys: new KeyState(), eaten: new Set(), size: null, ready: false, queue: [] };
    this.views.set(id, v);
    win.loadFile(path.join(__dirname, 'phoneview.html'), { query: { kind, title, titleKey, titleName, ...(kind === 'mic' ? { sink, virtual: process.platform === 'linux' ? '1' : '' } : {}), language: this._i18n().locale } });
    if (!hidden) win.once('ready-to-show', () => win.show());
    win.webContents.once('did-finish-load', () => {
      v.ready = true;
      for (const [ch, m] of v.queue.splice(0)) win.webContents.send(ch, m);
      win.webContents.send('phoneview:opts', { panel: this.getSettings().phone.panel !== false });
    });
    win.on('focus', () => this.emit('focus'));
    win.on('blur', () => this.emit('focus'));
    win.on('moved', () => this.emit('focus')); // moved to or off the crossing side (#356)
    // Its warnings in the log (a decoder that failed: the picture that never came).
    win.webContents.on('console-message', (e, level, message) => {
      const lvl = e && e.level !== undefined ? e.level : level;
      if (lvl === 'warning' || lvl === 'error' || lvl >= 2) console.log(`[phone] window ${title}: ${String((e && e.message) || message).slice(0, 300)}`);
    });
    // A camera's window: closed, it only hides (the camera stops with Camera's switch).
    if (kind === 'camera') {
      win.on('close', (e) => {
        if (v.ending || quitting) return;
        e.preventDefault();
        win.hide();
        this.emit('change');
      });
      win.on('show', () => this.emit('change'));
    }
    win.on('closed', () => {
      if (v.h264) v.h264.close();
      if (v.session) v.session.stop();
      this.saver.closed(id); // a recording keeps what it has
      this.views.delete(id);
      this.emit('change');
    });
    this.emit('change');
    if (kind !== 'netsound' && !net) this._start(v, opts).catch((e) => {
      console.log(`[phone] ${kind} window: ${e.message}`);
      this._send(v, 'phoneview:status', { error: e.message, errorKey: e.messageKey, errorVars: e.messageVars });
    });
    return v;
  }

  _send(v, ch, m) {
    if (!v.win || v.win.isDestroyed()) return;
    if (!v.ready) return v.queue.push([ch, m]);
    v.win.webContents.send(ch, m);
  }

  async _start(v, opts) {
    const s = v.relay ? this.makeRelay(v.relay) : v.usb ? new IosUsbScreen({ ...opts, id: v.usb }) : v.native ? new NativeScreen(this.server, opts) : new Session(this.bridge.adb, this.bridge.serial, opts);
    const via = v.native || v.relay || v.usb ? null : this.bridge.via;
    if (v.native) setImmediate(() => this.bridge._sound()); // its sound, when it plays it
    if (v.native) s.on('waiting', () => this._send(v, 'phoneview:status', { error: 'Tap Start on the phone to share its screen', errorKey: 'Tap Start on the phone to share its screen' }));
    v.session = s;
    s.on('size', (size) => {
      v.size = size;
      this.emit('focus'); // a focused window that now shows the phone: its edges stop crossing
      this._send(v, 'phoneview:size', size);
      const auto = require('../shared/appturn.js').autoRotate(this.getSettings());
      if (v.kind === 'app') require('../shared/appturn.js').appSized(v, size, auto); // the app turned its display round (#258)
      else if ((v.kind === 'camera' || auto || !v.shaped) && v.win && !v.win.isDestroyed()) v.win.setAspectRatio(size.width / size.height); // Auto-rotate off: the window keeps its shape
      v.shaped = true;
    });
    s.on('video', (p) => {
      // For an H.264 conversion started later (_h264): the parameter sets, and the frames from the last
      // keyframe on (an iPhone sends one seldom, and a keyframe asked for may not come).
      if (p.config) v.config = p.data;
      else if ((v.usb || v.relay) && !v.h264) {
        if (p.key) v.gop = [p];
        else if (v.gop) v.gop.push(p);
        if (v.gop && v.gop.length > 1800) v.gop = null; // too far: the next keyframe
      }
      if (v.h264) v.h264.push(p);
      else this._send(v, 'phoneview:video', p);
    });
    s.on('audio', (p) => !p.config && this._send(v, 'phoneview:audio', p.data));
    s.on('closed', (why, metadata) => {
      if (v.session !== s) return; // one a flip replaced
      setImmediate(() => this.emit('focus')); // closed (s.closed set): the edges cross again
      this._send(v, 'phoneview:status', { closed: why, closedKey: metadata && metadata.messageKey, closedVars: metadata && metadata.messageVars });
      if (v.kind === 'camera' && why !== 'stopped') {
        v.error = why;
        this.emit('change');
      }
    });
    await s.start();
    // An app window on an asleep phone waited for a picture that never came (#247, #239): the phone
    // wakes first (a phone that's awake ignores it), so its new display draws.
    if (v.app && !v.native) s.tap(ANDROID.WAKEUP);
    if (v.app) setTimeout(() => require('../shared/appstart.js').startApp(s, { adb: this.bridge.adb, serial: this.bridge.serial, maker: ((this.phone && this.phone.info) || {}).maker, app: v.app }), 300); // full screen on HyperOS (#265)
    this._send(v, 'phoneview:status', { ready: true, via });
    this._send(v, 'phoneview:opts', this._opts(v));
  }

  // The window's switches as they are now (its controls light up).
  _opts(v) {
    const ph = this.getSettings().phone || {};
    return { enterSends: ph.enterSends !== false, autoRotate: ph.autoRotate !== false, arrowSwipe: ph.arrowSwipe === true, screenOff: !!v.screenOff, pinned: !!(v.win && !v.win.isDestroyed() && v.win.isAlwaysOnTop()) };
  }

  // Enter sends / Arrow keys swipe changed (here, or on the Phone page): every window shows it.
  applyOpts() {
    for (const v of this.views.values()) if (v.kind !== 'sound' && v.kind !== 'netsound' && v.kind !== 'mic') this._send(v, 'phoneview:opts', this._opts(v));
  }

  // Enter in a chat app, an arrow that swipes (shared/phonechat.js): done here, the key (and its
  // release) left out. True when the key was used up.
  _special(v, code, down) {
    if (!down) return v.eaten.delete(code);
    if (v.eaten.has(code)) return true; // held: once
    const ph = this.getSettings().phone || {};
    const s = v.session;
    let done = false;
    const dir = chat.swipeOf(code, ph.arrowSwipe === true, v.keys.held);
    if (dir) {
      this._swipe(v, dir);
      done = true;
    } else if (chat.isEnter(code)) {
      done = chat.enter({
        on: ph.enterSends !== false,
        all: ph.enterAll === true,
        pkg: v.app || this.activeApp,
        shift: v.keys.held.has('ShiftLeft') || v.keys.held.has('ShiftRight'),
        a11y: this.a11y,
        phoneSend: (all) => this.server.sendToClient(all ? { t: T.PHONE_SEND, all: true } : { t: T.PHONE_SEND }),
        tap: (k) => !s.closed && s.tap(k),
        text: (t) => s.text(t),
      });
    }
    if (done) v.eaten.add(code);
    return done;
  }

  _h264(v) {
    const s = v.session;
    if (v.h264 || !s || s.closed || !(v.usb || v.relay)) return;
    console.log(`[phone] ${v.title}: no HEVC decoding here, H.264 through ffmpeg`);
    const t = new HevcToH264();
    v.h264 = t;
    if (v.config) t.push({ config: true, data: v.config }); // the parameter sets came before
    for (const p of v.gop || []) t.push(p);
    v.gop = null;
    t.on('video', (p) => this._send(v, 'phoneview:video', p));
    t.on('closed', (why) => {
      if (v.h264 !== t) return;
      v.h264 = null;
      console.log(`[phone] ${v.title}: ffmpeg: ${why}`);
      const missing = why === 'missing';
      this._send(v, 'phoneview:status', missing
        ? { error: 'Install ffmpeg to see an iPhone’s screen on this computer', errorKey: 'Install ffmpeg to see an iPhone’s screen on this computer' }
        : { error: why });
    });
    s.simple(TYPE.RESET_VIDEO); // from a keyframe
  }

  _input(v, m) {
    // Keep on top (the title bar's pin): the window's own, no phone needed.
    if (m.t === 'pin') {
      const on = !v.win.isAlwaysOnTop();
      v.win.setAlwaysOnTop(on);
      return this._send(v, 'phoneview:opts', { pinned: on });
    }
    // The window can't decode the iPhone's HEVC (no VA-API driver with it): H.264 through ffmpeg.
    if (m.t === 'h264') return this._h264(v);
    // Fullscreen (its title-bar button, F11): only the picture, black around it; F11 again leaves.
    if (m.t === 'full') {
      const on = !v.win.isFullScreen();
      v.win.setFullScreen(on);
      return this._send(v, 'phoneview:opts', { full: on });
    }
    // The title bar's panel button: the controls shown or hidden in every phone window, remembered.
    if (m.t === 'panel') {
      const ph = this.getSettings().phone;
      ph.panel = ph.panel === false;
      this.bridge.emit('save');
      for (const w of this.views.values()) this._send(w, 'phoneview:opts', { panel: ph.panel });
      return this.emit('change');
    }
    if (m.t === 'toggle' && (m.what === 'enterSends' || m.what === 'arrowSwipe' || m.what === 'autoRotate')) {
      const ph = this.getSettings().phone;
      ph[m.what] = m.what === 'arrowSwipe' ? ph.arrowSwipe !== true : ph[m.what] === false; // the others are on unless switched off
      this.bridge.emit('save');
      this.applyOpts();
      return this.emit('change');
    }
    const s = v.session;
    const size = v.size;
    if (!s || s.closed) return;
    // A camera's picture isn't the phone's screen: touches and keys there would land on whatever the screen shows.
    if (v.kind === 'camera' && (m.t === 'touch' || m.t === 'scroll' || m.t === 'key')) return;
    const num = (x) => (Number.isFinite(x) ? x : 0);
    switch (m.t) {
      case 'touch': // a finger (pointer ≥ 0) or the mouse (-1) at video coordinates
        if (!size) return;
        if (m.action === ACTION.HOVER_MOVE && (this.getSettings().phone || {}).hover === false) return; // Phone › Hover off (#330)
        s.touch(m.action | 0, Math.max(-3, Math.min(9, m.pointer | 0)), num(m.x), num(m.y), size.width, size.height,
          m.action === ACTION.UP ? 0 : 1, m.actionButton | 0, m.buttons | 0);
        break;
      case 'scroll':
        if (!size) return;
        s.scroll(num(m.x), num(m.y), size.width, size.height, num(m.hs), num(m.vs), 0);
        break;
      case 'key': {
        if (typeof m.code !== 'string') return;
        if (typeof s.keyCode === 'function') { // a phone through another computer (phone-relay.js): an iPhone's HID keyboard, Command where Ctrl is; an Android phone's keys by their place
          const swapI = this.getSettings().keys.swapCtrlCmd !== false && P.keySwapNeeded(P.OS.LINUX, s.os === 'android' ? P.OS.ANDROID : P.OS.MAC);
          s.keyCode(swapI ? P.mapKeyFromOtherPlatform(m.code) : m.code, !!m.down);
          break;
        }
        const swap = P.keySwapNeeded(P.OS.LINUX, P.OS.ANDROID) && this.getSettings().keys.swapCtrlCmd !== false;
        let code = swap ? P.mapKeyFromOtherPlatform(m.code) : m.code;
        if (this._special(v, code, !!m.down)) break;
        const uhid = (this.getSettings().phone || {}).uhid === true;
        if (!uhid) { // by what the key types here, not its place on Android's QWERTY (shared/phonetype.js, #260)
          const r = (v.type || (v.type = new (require('../shared/phonetype.js').PhoneType)())).fromWindow({ code, down: !!m.down, repeat: !!m.repeat, key: m.key, shift: !!m.shift, ctrl: !!m.ctrl, meta: !!m.meta, altGr: !!m.altGr });
          if (r.text) { s.text(r.text); break; }
          if (!r.code) break;
          code = r.code;
        }
        const e = v.keys.event(code, !!m.down);
        if (uhidKey(s, uhid, code, !!m.down)) break; // a HID keyboard (#123)
        if (e) s.key(m.down ? ACTION.DOWN : ACTION.UP, e.keycode, e.meta, m.repeat ? 1 : 0);
        break;
      }
      case 'nav': {
        const k = { back: ANDROID.BACK, home: ANDROID.HOME, recents: ANDROID.APP_SWITCH, power: ANDROID.POWER, volumeUp: ANDROID.VOLUME_UP, volumeDown: ANDROID.VOLUME_DOWN }[m.key];
        if (m.key === 'back') { s.backOrScreenOn(ACTION.DOWN); s.backOrScreenOn(ACTION.UP); } else if (k) s.tap(k);
        if (m.key === 'notifications') s.simple(TYPE.EXPAND_NOTIFICATIONS);
        if (m.key === 'rotate') s.simple(TYPE.ROTATE);
        // The phone's own screen off, its picture still here (scrcpy's display power).
        if (m.key === 'screenPower' && (v.kind === 'screen' || v.kind === 'app') && !v.native) { // an app window too: its app runs with the phone dark (#247)
          v.screenOff = !v.screenOff;
          s.setDisplayPower(!v.screenOff);
          this._send(v, 'phoneview:opts', { screenOff: v.screenOff });
        }
        break;
      }
      case 'resetVideo': // the window skipped frames: a keyframe now
        s.simple(TYPE.RESET_VIDEO);
        break;
      case 'cameraTorch':
        if (v.kind === 'camera') { v.torch = !!m.on; s.setTorch(v.torch); }
        break;
      case 'cameraZoomIn':
        if (v.kind === 'camera') s.zoomIn();
        break;
      case 'cameraZoomOut':
        if (v.kind === 'camera') s.zoomOut();
        break;
      case 'cameraSwitch': { // the other camera: a session of its own
        if (v.kind !== 'camera') break;
        this._flip(v, v.facing === 'front' ? 'back' : 'front');
        break;
      }
      case 'resize': // an app window changed size: its virtual display follows (flex)
        if (v.kind === 'app' && m.w > 50 && m.h > 50) s.resizeDisplay(...require('../shared/appturn.js').appResized(v, m)); // a phone-like size (shared/appsize.js), swapped back while the app has it turned (#258)
        break;
      case 'swipe':
        if (typeof m.dir === 'string') this._swipe(v, m.dir);
        break;
      default: break;
    }
  }

  _swipe(v, dir) {
    const s = v.session;
    const size = v.size;
    if (!s || s.closed || !size) return;
    if (v.swiping) {
      // Buffer at most 1 subsequent swipe so rapid taps are never dropped
      v.pendingSwipe = dir;
      return;
    }
    v.swiping = true;

    const w = size.width;
    const h = size.height;
    let startX, startY, endX, endY;

    // Inverted directional swipe for natural navigation:
    // ArrowDown -> content moves down (finger swipes UP from bottom to top)
    // ArrowUp -> content moves up (finger swipes DOWN from top to bottom)
    // ArrowRight -> content moves right (finger swipes LEFT from right to left)
    // ArrowLeft -> content moves left (finger swipes RIGHT from left to right)
    switch (dir) {
      case 'down':
        startX = Math.round(w * 0.5);
        startY = Math.round(h * 0.78);
        endX = Math.round(w * 0.5);
        endY = Math.round(h * 0.22);
        break;
      case 'up':
        startX = Math.round(w * 0.5);
        startY = Math.round(h * 0.22);
        endX = Math.round(w * 0.5);
        endY = Math.round(h * 0.78);
        break;
      case 'right':
        startX = Math.round(w * 0.82);
        startY = Math.round(h * 0.5);
        endX = Math.round(w * 0.18);
        endY = Math.round(h * 0.5);
        break;
      case 'left':
        startX = Math.round(w * 0.18);
        startY = Math.round(h * 0.5);
        endX = Math.round(w * 0.82);
        endY = Math.round(h * 0.5);
        break;
      default:
        v.swiping = false;
        return;
    }

    const duration = 160; // ms: natural flick duration
    const startTime = Date.now();
    const dx = endX - startX;
    const dy = endY - startY;

    // Send touch down directly over control socket (pointer: -2 = FINGER)
    s.touch(ACTION.DOWN, -2, startX, startY, w, h, 1, 0, 0);

    const timer = setInterval(() => {
      if (s.closed) {
        clearInterval(timer);
        v.swiping = false;
        v.swipeTimer = null;
        v.pendingSwipe = null;
        return;
      }

      const elapsed = Date.now() - startTime;
      const progress = Math.min(1, elapsed / duration);

      if (progress < 1) {
        // Mild ease-in curve (t^1.15): starts cleanly without jerk and maintains brisk velocity
        // right through release (ACTION.UP), ensuring Android's VelocityTracker detects a
        // natural fling and triggers a smooth inertia scroll.
        const ease = Math.pow(progress, 1.15);
        const curX = Math.round(startX + dx * ease);
        const curY = Math.round(startY + dy * ease);
        s.touch(ACTION.MOVE, -2, curX, curY, w, h, 1, 0, 0);
      } else {
        clearInterval(timer);
        v.swipeTimer = null;
        // Liftoff at terminal position with authentic release velocity
        s.touch(ACTION.UP, -2, endX, endY, w, h, 0, 0, 0);
        setTimeout(() => {
          v.swiping = false;
          if (v.pendingSwipe) {
            const next = v.pendingSwipe;
            v.pendingSwipe = null;
            this._swipe(v, next);
          }
        }, 30);
      }
    }, 10);
    v.swipeTimer = timer;
  }

  shutdown() {
    this.closeAll();
  }
}

module.exports = { PhoneViews };