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.

15.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Share screen (copy of windows/ui-share.js): this computer's screen in a window on the
// other computer, controlled from there. Mirror shows an existing monitor; Extend adds an extra
// (virtual) screen (vdd.js: Mutter's on GNOME Wayland, a spare output on X11, which needs the
// helper Install puts in once). On Wayland the desktop asks which screen to share each time sharing starts.
'use strict';

function sharingAny(s) {
  const p = s.pcScreen;
  const tg = Array.isArray(p.targets) ? p.targets : null;
  return tg && tg.length ? tg.some((x) => x.mode !== 'off' || (x.more || []).length > 0) : p.mode !== 'off';
}

UI.tab({
  id: 'pc-mac',
  group: 'Display',
  order: 11,
  title: 'Share screen',
  heading: /\/mesh\//.test(location.pathname) ? 'Share screen' : '{me}’s screen on {name}', // Multi-device: every device, not one
  icon: 'display',
  color: 'linear-gradient(#5ac8fa, #0a84ff)',
  desc: /\/mesh\//.test(location.pathname) ? 'Show {me}’s screens on your other devices.' : 'See {me} in a window on the other computer.',
  // Multi-device: on while any screen goes to any device, off only once every share has stopped (off stops them all).
  master: { get: (s) => sharingAny(s), set: (v) => UI.api.setPcScreenMode(v ? 'last' : 'off') },
  badge: (s) => (sharingAny(s) ? 'on' : ''), // sharing on, as the Mac's (watched or not)
  build(body) {
    const { el, api } = UI;
    const t = (...args) => I18n.t(...args);
    const driverMessage = (message) => {
      const prefixes = ['Couldn’t check the display driver: ', 'Installing the display driver failed: ', 'Removing the display driver failed: ', 'Couldn’t switch the virtual monitor: '];
      const prefix = prefixes.find((value) => (message || '').startsWith(value));
      return prefix ? t(prefix + '{error}', { error: message.slice(prefix.length) }) : t(message || '');
    };
    const set = (partial) => api.setPcScreen(partial);
    const mode = UI.segmented([
      { value: 'off', label: t('Off') },
      { value: 'extend', label: t('Extend') },
      { value: 'mirror', label: t('Mirror') },
    ], (v) => api.setPcScreenMode(v));
    const monitor = UI.select([], (v) => set({ monitor: v }));
    const EXTEND_SIZES = [
      { value: 'mac', label: t('Same as the other screen') },
      { value: '1920x1080', label: '1920 × 1080' },
      { value: '2560x1440', label: '2560 × 1440' },
      { value: '3840x2160', label: '3840 × 2160' },
    ];
    const extendSize = UI.select(EXTEND_SIZES, (v) => set({ extendSize: v }));
    const streamSize = UI.select([
      { value: 1080, label: t('1080p (1920 × 1080), fastest') },
      { value: 1440, label: t('1440p (2560 × 1440), sharper') },
      { value: 2160, label: t('4K (3840 × 2160), sharpest') },
      { value: 0, label: t('Full size') },
    ], (v) => set({ maxHeight: Number(v) }));
    const quality = UI.select([
      { value: 10, label: t('Low, 10 Mbps') },
      { value: 20, label: t('Medium, 20 Mbps') },
      { value: 30, label: t('High, 30 Mbps') },
      { value: 50, label: t('Best, 50 Mbps (wired)') },
      { value: 80, label: t('Max, 80 Mbps (wired)') },
    ], (v) => set({ mbps: Number(v) }));
    const paceRow = UI.paceRow(); // One Playback setting, synced with the other computer
    // Frame rate: the monitor's refresh rate unless capped (pcscreen.js; a change starts a new session).
    const frameRate = UI.select([
      { value: 0, label: t('Match the display') },
      { value: 60, label: t('60 fps') },
      { value: 30, label: t('30 fps, lighter') },
    ], (v) => set({ fps: Number(v) }));
    const codecRow = UI.codecRow((v) => set({ codec: v })); // Encoder (shared/screencodec.js)
    const sound = UI.switch((v) => set({ sound: v }), { label: t('Include sound') });
    const input = UI.switch((v) => set({ input: v }), { label: t('Receive input') });
    const inputRow = UI.row(t('Receive input'), '', [input], { literal: true }); // "Receive input from Mac" / "from PC2"
    const remote = UI.switch((v) => set({ remote: v }), { label: t('Remote start') });
    const remoteRow = UI.row(t('Let the other computer start and switch this screen'), '', [remote], { literal: true }); // screen.ctl

    const monitorRow = UI.row(t('Display'), '', [monitor], { literal: true });
    const extendRow = UI.row(t('Size'), '', [extendSize]);
    const details = UI.details(['Status', 'Display', 'Picture', 'Speed', 'Round trip', 'Codec', 'Encoder', 'Frames dropped']);

    const note = UI.note('info', '', { literal: true });
    // X11: Extend's screen is a spare output switched on through a small root helper (vdd.js).
    const installBtn = UI.button(t('Install'), () => api.installVdd(), 'small primary');
    const removeBtn = UI.button(t('Remove'), () => api.removeVdd(), 'small');
    const driver = UI.row(t('TwinDesk virtual display driver'), '', [installBtn, removeBtn]);
    const driverCard = UI.card('', [driver], { cls: 'keep-on' });
    // KDE Plasma on Wayland (#69): KWin makes virtual screens only for its own tools, so Extend can't
    // add one here. KDE's krfb-virtualmonitor can, and Mirror then shares it: the workaround, spelled out.
    const KDE_CMD = 'krfb-virtualmonitor --name TwinDesk --resolution 1920x1080 --password CHANGE-ME --port 5901';
    const kdeCard = UI.card(t('Extend on KDE Plasma'), [
      UI.row(t('1. Install krfb'), t('From Discover, or in a terminal: {command}', { command: 'sudo apt install krfb  ·  sudo dnf install krfb  ·  sudo pacman -S krfb' }), []),
      UI.row(t('2. Make the extra screen'), t('Run {command} and leave it running: the screen lasts as long as it does. It also starts a VNC server on that port, so pick your own password and keep the port closed to other networks. Use the other computer’s resolution.', { command: KDE_CMD }), []),
      UI.row(t('3. Place it'), t('System Settings › Display & Monitor: put the new screen on the side where the other computer is.'), []),
      UI.row(t('4. Share it'), t('Choose Mirror above. When your desktop asks which screen to share, pick the new one.'), []),
    ]);

    // Multi-device: this computer's monitors as the desktop arranges them (boxes), and what each connected
    // device gets (shared/pcscreen-set.js; one-to-one has no displays, so the card stays hidden).
    const map = el('div', { class: 'screen-map', attrs: { 'data-literal': '' } });
    map.style.cssText = 'position:relative;height:120px;margin:8px 0';
    const targetsBox = el('div', { class: 'screen-targets' });
    let targetsKey = '';
    const drawMap = (displays, targets) => {
      map.textContent = '';
      if (!displays.length) return;
      const x0 = Math.min(...displays.map((d) => d.x)), y0 = Math.min(...displays.map((d) => d.y));
      const w = Math.max(...displays.map((d) => d.x + d.w)) - x0, h = Math.max(...displays.map((d) => d.y + d.h)) - y0;
      const k = Math.min(100 / h, 100 / w * (map.clientWidth || 480) / 100, 1);
      for (const d of displays) {
        const who = targets.filter((t) => t.mode === 'mirror' && t.monitor === d.id).map((t) => t.name);
        const box = el('div', { text: [UI.monitorLabel(d.name + (d.primary ? ' (main)' : '')), d.w + ' × ' + d.h].concat(who.length ? ['→ ' + who.join(', ')] : []).join(String.fromCharCode(10)) });
        box.style.cssText = `position:absolute;box-sizing:border-box;border:1px solid var(--accent,#0a84ff);border-radius:4px;font-size:11px;white-space:pre;overflow:hidden;padding:2px 4px;opacity:${who.length ? 1 : 0.6};`
          + `left:${(d.x - x0) * k}px;top:${(d.y - y0) * k}px;width:${d.w * k}px;height:${d.h * k}px`;
        map.append(box);
      }
      map.style.height = h * k + 'px';
    };
    const drawTargets = (p) => {
      const key = JSON.stringify([p.targets, p.monitors, p.vdd.installed]);
      if (key === targetsKey) return;
      targetsKey = key;
      targetsBox.textContent = '';
      for (const target of p.targets) {
        const seg = UI.segmented([{ value: 'off', label: t('Off') }, { value: 'extend', label: t('Extend') }, { value: 'mirror', label: t('Mirror') }],
          (v) => api.setPcScreenTarget(target.id, { mode: v, displayId: target.monitor || undefined }));
        seg.set(target.mode);
        seg.el.querySelectorAll('button').forEach((b, i) => { b.disabled = target.busy || (i === 1 && !p.vdd.installed); });
        const sel = UI.select(p.monitors.map((m) => ({ value: m.id, label: UI.monitorLabel(m.label) })), (v) => api.setPcScreenTarget(target.id, { mode: 'mirror', displayId: v }));
        sel.set(target.monitor || (p.monitors.find((m) => /\(main\)$/.test(m.label)) || p.monitors[0] || { id: '' }).id);
        sel.el.hidden = target.mode !== 'mirror';
        targetsBox.append(UI.row(target.name, t(target.error || ''), [seg, sel], { literal: true }));
      }
    };
    // Multi-device: the sharing map (shared/ui-sharemap.js), drag a screen onto a device.
    const shareMap = window.ShareMap ? ShareMap.create({ assign: (id, c) => api.setPcScreenTarget(id, c), main: {
        // The main card: Mirror or Extend for a device that opens this screen itself (only while it's shared),
        // Mirror's monitor, Extend's size.
        mode: (v) => { if (UI.state && UI.state.pcScreen && UI.state.pcScreen.mode !== 'off') api.setPcScreenMode(v); },
        mirror: (v) => api.setPcScreen({ monitor: v }),
        size: (v) => api.setPcScreen({ extendSize: v }),
      } }) : null;
    const screens = UI.card(t('Displays'), [map, targetsBox]);

    const screenCard = UI.card(t('Screen'), [UI.row(t('Mode'), '', [mode]), monitorRow, extendRow]); // the map's main card is the same, so hidden with the map
    body.append(
      UI.groupedSections([
        { id: 'screens', title: t('Screens'), cards: [...(shareMap ? [shareMap.el] : []), screens, screenCard, kdeCard, note] },
        { id: 'quality', title: t('Quality'), cards: [UI.card(t('Quality'), [UI.row(t('Resolution'), '', [streamSize]), UI.row(t('Quality'), '', [quality]), UI.row(t('Frame rate'), '', [frameRate]), paceRow, codecRow], { cls: 'keep-on' })] },
        { id: 'sound', title: t('Sound and control'), cards: [UI.card(t('Sound and control'), [UI.row(t('Include sound'), '', [sound]), inputRow], { cls: 'keep-on' }), UI.card(t('Remote'), [remoteRow], { cls: 'keep-on' })] },
        { id: 'stats', title: t('Statistics'), cards: [details] },
        // The display driver last: installed once, rarely touched.
        { id: 'driver', title: t('Display driver'), cards: [driverCard] },
      ]),
    );

    return (s) => {
      const p = s.pcScreen;
      const connected = s.link.state === 'connected';
      screens.hidden = !(p.displays && p.displays.length);
      if (!screens.hidden) drawMap(p.displays, p.targets || []);
      targetsBox.hidden = !p.targets || p.targets.length < 2; // one device: the Screen card below does it all
      if (!targetsBox.hidden) drawTargets(p);
      if (shareMap) {
        const peers = s.peers || [];
        const mine = new Set((p.monitors || []).map((m) => m.id));
        const own = (p.displays || []).filter((d) => !mine.size || mine.has(d.id)); // Extend's output is the card's Extend
        shareMap.render(p.targets ? {
          displays: own,
          main: {
            mode: p.mode === 'off' ? undefined : p.mode === 'extend' ? 'extend' : 'mirror',
            mirror: p.monitor || (own.find((d) => d.primary) || own[0] || {}).id,
            mirrors: (p.monitors || []).map((m) => ({ value: m.id, label: UI.monitorLabel(m.label) })),
            size: p.extendSize, sizes: EXTEND_SIZES,
            // One device at a time on Linux: the virtual output is one.
            extend: { can: !!(p.vdd && p.vdd.installed), why: t('Needs the display driver') },
          },
          targets: p.targets.map((x) => ({ id: x.id, name: x.name, os: x.os, mode: x.mode, displayId: x.monitor, place: x.place || '', multi: !!x.multi, more: x.more || [], monitors: ShareMap.monitorsOf(s, x.id), status: x.status, error: x.error })),
          selected: (peers.find((x) => x.selected) || {}).id || '',
        } : null);
        if (p.targets) screens.hidden = true; // the map has it all
        screenCard.hidden = !!p.targets;
      }
      mode.set(p.mode);
      const v = p.vdd;
      mode.el.querySelectorAll('button').forEach((b, i) => { b.disabled = p.busy || (i === 1 && !v.installed); });
      monitor.options(p.monitors.map((m) => ({ value: m.id, label: UI.monitorLabel(m.label) })));
      monitor.set(p.monitor || (p.monitors.find((m) => /\(main\)$/.test(m.label)) || p.monitors[0] || { id: '' }).id);
      monitorRow.hidden = p.mode === 'extend';
      extendRow.hidden = p.mode !== 'extend';
      extendSize.set(p.extendSize);
      extendRow.setHint(p.extendSize === 'mac' ? p.extendPx[0] + ' × ' + p.extendPx[1] : '');
      streamSize.set(p.maxHeight);
      quality.set(p.mbps);
      frameRate.set(p.fps || 0);
      paceRow.render(s);
      codecRow.render(p.codec);
      sound.set(p.sound);
      input.set(p.input);
      remote.set(p.remote);

      const on = p.mode !== 'off';
      const st = p.status === 'live' && p.stats;
      const who = UI.peer(s).the;
      const mon = p.monitors.find((m) => m.id === p.monitor) || p.monitors.find((m) => /\(main\)$/.test(m.label)) || p.monitors[0];
      details.set({
        Status: (!on ? t('Off') : p.busy ? t('Starting the extra screen…') : p.status === 'live' ? t('On {device}', { device: who })
          : !connected ? t('Waiting for {device}', { device: who }) : !p.mac.accept ? t('Ready, starts when {device} opens it', { device: who }) : t('Connecting…')) + (p.error ? ': ' + t(p.error) : ''),
        Display: !on ? '' : p.mode === 'extend' ? t('Virtual monitor, {width} × {height}', { width: p.extendPx[0], height: p.extendPx[1] }) : mon ? UI.monitorLabel(mon.label) : '',
        Picture: st ? `${st.width} × ${st.height}, ${st.fps} fps` : '',
        Speed: st ? (st.targetMbps ? t('{mbps} Mbps sent, network allows {targetMbps}', { mbps: st.mbps, targetMbps: st.targetMbps }) : t('{mbps} Mbps sent', { mbps: st.mbps })) : '',
        'Round trip': st && st.rttMs != null ? st.rttMs + ' ms' : '',
        Codec: st && st.codec ? st.codec.toUpperCase() : '',
        Encoder: st && st.encoder ? UI.codecImpl(st.encoder, st.hw) : '',
        'Frames dropped': st ? st.dropped || 0 : '',
      });

      inputRow.label.textContent = t('Receive input from {device}', { device: UI.peer(s).them });
      remoteRow.label.textContent = t('Let {device} start and switch this screen', { device: UI.peer(s).the });
      remoteRow.setHint(p.remote ? t('Opening the screen window there starts sharing; Extend and Mirror can be switched from there.') : '');
      const wayland = s.session && s.session.type === 'wayland';
      kdeCard.hidden = !(wayland && /kde/i.test(s.session.desktop || ''));
      monitorRow.hidden = wayland || p.mode === 'extend';
      driverCard.hidden = !(v.setup || v.removable || v.busy);
      installBtn.hidden = !v.setup;
      installBtn.disabled = !!v.busy;
      installBtn.textContent = v.busy === 'install' ? t('Installing…') : t('Install');
      removeBtn.hidden = !v.removable;
      removeBtn.disabled = !!v.busy || p.mode === 'extend';
      driver.setHint(v.busy === 'remove' ? t('Removing…') : v.busy === 'install' ? t('Installing…') : v.hint ? t(v.hint) : v.removable ? t('Installed. Adds the extra screen for Extend.')
        : t('Adds an extra screen for Extend by switching on a spare display output. Installs a small helper and asks for your password once.'));
      const extend = !v.checked || (v.setup && !v.message) ? '' : !v.installed ? t(v.message || 'Extend isn’t available on this desktop') + '.'
        : v.message ? t(v.message) + '.' : '';
      note.set([
        wayland ? (p.mode === 'extend' ? t('Wayland: your desktop asks which screen to share each time sharing starts, choose “Virtual remote monitor”.') : t('Wayland: your desktop asks which screen to share each time sharing starts.'))
          + (s.session.input === 'uinput' ? '' : ' ' + t('Input from {device} needs input access (General).', { device: UI.peer(s).the })) : '',
        extend,
      ].filter(Boolean).join(' '));
    };
  },
});