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.

13.9 KB
Raw Blame
// TwinDesk — Copyright (C) 2026 inukaasith. GPL-3.0, see LICENSE.
// Extend: a virtual monitor for this PC that only the Mac shows, from the Virtual Display
// Driver (https://github.com/VirtualDrivers/Virtual-Display-Driver — MIT, signed by SignPath
// Foundation; an IddCx driver). Installed once, elevated (scripts\vdd-install.ps1); after that the
// monitor is switched on/off without a prompt through two SYSTEM scheduled tasks the user may run.
// It is on only while Extend is on, like the Mac's TwinDesk display.
// Multi-device › Share screen › Add virtual display: more monitors from the same driver (setExtras), shared
// to devices like real screens. The driver makes <monitors><count> of them when it starts, so a new count
// restarts it (every one of its monitors goes and comes back). With none added, nothing here changes:
// one monitor, on only for Extend. The first of its monitors is Extend's while Extend is on.
const { app } = require('electron');
const { execFile } = require('child_process');
const fs = require('fs');
const path = require('path');
const { script, scriptElevated } = require('./ps');
const Helper = require('./helper');
const { fetchFile, readResult } = require('./fetchfile');

// Pinned release, driver package only: the "x86" one is x64 despite its name (see the project's
// silent-install.ps1). Windows on ARM needs the ARM64 one (same files and settings layout).
const RELEASE = 'https://github.com/VirtualDrivers/Virtual-Display-Driver/releases/download/25.7.23/';
const DRIVERS = {
  x64: { url: RELEASE + 'VirtualDisplayDriver-x86.Driver.Only.zip', sha256: 'E24210692B442B39AF763536330CE78B423F19342B7A7792C26DE3944E418B3A' },
  arm64: { url: RELEASE + 'VirtualDisplayDriver-ARM64.Driver.Only.zip', sha256: 'DCD487161469C726BAB60F174A7E7F70EE02AFD437CAD0D5C0E6755953DE5A25' },
};
const SETTINGS_XML = 'C:\\VirtualDisplayDriver\\vdd_settings.xml';
const ADAPTER = /virtual display driver/i; // the device name in MttVDD.inf
const MONITOR_ID = 'MTT1337'; // its monitor's EDID id (MONITOR\MTT1337\…)
const SCHTASKS = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'schtasks.exe');

// scripts/vdd-status.ps1: the driver's device and status, and our Extend tasks.

class Vdd {
  // opts: helper, onChange()
  constructor(opts) {
    Object.assign(this, opts);
    this.state = { checked: false, installed: false, on: false, busy: '', message: '' };
    this.extras = []; // the added monitors wanted: [{slot, width, height}] (setExtras)
    this.extraMons = []; // those on the desktop now, in slot order: [{name, x, y, width, height}]
  }

  // How many monitors the driver should make now: Extend's, and the added ones.
  _count() {
    return (this.wanted ? 1 : 0) + this.extras.length;
  }

  // The added monitors: [{slot, width, height}]. Switches the driver on, off or restarts it to match.
  async setExtras(list) {
    const next = (Array.isArray(list) ? list : []).map((v) => ({ slot: v.slot, width: v.width, height: v.height }));
    if (JSON.stringify(next) === JSON.stringify(this.extras)) return;
    const had = this.extras.length > 0;
    this.extras = next;
    let added = false;
    for (const v of next) added = this.addMode(v.width, v.height) || added;
    await this.setOn(!!this.wanted, { force: added || (had && !next.length) }); // the last one gone: back to one monitor (or none)
  }

  // <monitors><count>n</count> in the driver's settings; true when it changed (read when the device starts).
  _writeCount(n) {
    try {
      const xml = fs.readFileSync(SETTINGS_XML, 'utf8');
      const m = /(<monitors>\s*<count>\s*)(\d+)(\s*<\/count>)/.exec(xml);
      if (!m || Number(m[2]) === n) return false;
      fs.writeFileSync(SETTINGS_XML, xml.replace(m[0], m[1] + n + m[3]));
      return true;
    } catch (_) { return false; /* not writable: the driver's own count */ }
  }

  view() {
    return { ...this.state };
  }

  _set(p) {
    Object.assign(this.state, p);
    this.onChange();
  }

  // Is the driver there and are our tasks there? At start (switching a leftover monitor off).
  async check() {
    try {
      const r = JSON.parse((await script('vdd-status', {}, 30000)).trim() || '{}');
      this._set({ checked: true, installed: !!(r.device && r.tasks), on: r.status === 'OK' });
      if (this.state.installed && this.state.on && !this.wanted && !this.extras.length) await this.setOn(false);
    } catch (e) {
      this._set({ checked: true, message: 'Couldn’t check the display driver: ' + e.message });
    }
  }

  async install() {
    if (this.state.busy) return;
    this._set({ busy: 'install', message: '' });
    const log = path.join(app.getPath('userData'), 'vdd-result.txt');
    const zip = path.join(app.getPath('userData'), 'vdd-driver.zip');
    let cpu = '';
    let done = false; // the installer said ok
    try {
      try { fs.unlinkSync(log); } catch (_) { /* none */ }
      // The driver must match Windows, not this app (the x64 app also runs on ARM, emulated), so
      // ask WMI: Win32_Processor.Architecture 12 = ARM64.
      let sid;
      [sid, cpu] = (await script('vdd-whoami')).trim().split(/\s+/);
      if (!/^S-1-[\d-]+$/.test(sid)) throw new Error('couldn’t read this account’s id');
      const driver = DRIVERS[cpu === '12' ? 'arm64' : 'x64'];
      // Downloaded here, before the prompt, through Windows' proxy settings (#348).
      { const no = require('./portable').refuse('vdd-install'); if (no) throw new Error(no); } // Portable: refuse before downloading
      this._set({ message: 'Downloading the display driver…' });
      await fetchFile(driver.url, driver.sha256, zip);
      this._set({ message: '' });
      await scriptElevated('vdd-install', { Helper: Helper.EXE, UserSid: sid, Log: log, File: zip, Sha256: driver.sha256 }, 300000);
      const r = readResult(log, 'error: the setup didn’t finish');
      if (r !== 'ok') throw new Error(r.replace(/^error: /, ''));
      this.state.message = '';
      done = true;
    } catch (e) {
      if (/cancel/i.test(e.message)) this.state.message = 'The administrator prompt was declined';
      // Windows on ARM takes only Microsoft-signed drivers; the ARM64 build is signed by SignPath
      // only (VirtualDrivers/Virtual-Display-Driver#465). Install works again once a signed one is pinned.
      else if (cpu === '12' && /800B0109/.test(e.message)) this.state.message = 'Extend isn’t available on Windows on ARM yet: Windows there accepts only Microsoft-signed display drivers, and the virtual display driver’s ARM64 build isn’t one (Virtual-Display-Driver#465)';
      else this.state.message = 'Installing the display driver failed: ' + e.message;
    } finally {
      try { fs.unlinkSync(log); } catch (_) { /* none */ }
      try { fs.unlinkSync(zip); } catch (_) { /* none */ }
      this.state.busy = '';
      await this.check();
    }
    // Installed, yet Windows doesn't report the device and its tasks (#116): say so, not just "Not installed".
    if (done && !this.state.installed) this._set({ message: 'The display driver was installed, but Windows doesn’t report it back yet. Restart TwinDesk, or this PC, and check again' });
  }

  async remove() {
    if (this.state.busy) return;
    this._set({ busy: 'remove', message: '' });
    const log = path.join(app.getPath('userData'), 'vdd-result.txt');
    try {
      if (this.state.on) await this.setOn(false);
      await scriptElevated('vdd-remove', { Log: log }, 120000);
      const r = readResult(log, 'error: it didn’t finish');
      if (r !== 'ok') throw new Error(r.replace(/^error: /, ''));
    } catch (e) {
      this.state.message = /cancel/i.test(e.message) ? 'The administrator prompt was declined' : 'Removing the display driver failed: ' + e.message;
    } finally {
      try { fs.unlinkSync(log); } catch (_) { /* none */ }
      this.state.busy = '';
      await this.check();
    }
  }

  _task(on) {
    return new Promise((resolve) => execFile(SCHTASKS, ['/run', '/tn', on ? '\\MacShare\\Extend on' : '\\MacShare\\Extend off'],
      { windowsHide: true, timeout: 15000 }, (err) => {
        if (err) this.state.message = 'Couldn’t switch the virtual monitor: ' + String(err.message).split('\n')[0];
        resolve();
      }));
  }

  // Switch Extend's virtual monitor on/off (scheduled task, no prompt). Resolves when the monitor is
  // there / gone (or after a timeout). With added monitors (setExtras) the driver stays on for them; a
  // new count, or force (a new size in its settings), restarts it.
  async setOn(on, { force = false } = {}) {
    this.wanted = on;
    if (!this.state.installed) return false;
    if (!this.extras.length && !force) return this._switch(on); // as it always was: one monitor
    const count = this._count();
    const restart = (this._writeCount(Math.max(1, count)) || force) && this.state.on && count > 0;
    if (restart || count === 0) {
      await this._task(false);
      await this._until(() => this.extraMons.length === 0 && !this.mon, 15000, true);
      if (count === 0) { this._set({ on: false }); return true; }
    }
    await this._task(true);
    // Not on the desktop yet: Windows may show them as a Duplicate (as _switch says): extend them.
    const ok = await this._until(() => (this.mon ? 1 : 0) + this.extraMons.length === count, 20000, false,
      () => this.helper.request('displayExtend', { monitor: MONITOR_ID }).catch(() => {}));
    this._set({ on: true, ...(ok ? {} : { message: 'The virtual monitor didn’t appear' }) });
    await this._sizeExtras();
    return this.mon || ok;
  }

  // A size added to the driver's settings is read when it starts: start it again.
  restart() {
    return this.setOn(!!this.wanted, { force: true });
  }

  // Polls the driver's monitors (find) until test() is true or the time is up; true when it was.
  async _until(test, ms, all = false, miss = null) {
    const until = Date.now() + ms;
    for (;;) {
      await this.find(all).catch(() => null);
      if (test()) return true;
      if (miss) await miss();
      if (Date.now() > until) return false;
      await new Promise((r) => setTimeout(r, 500));
    }
  }

  // One monitor, Extend's (no added ones): unchanged from before them.
  async _switch(on) {
    this._writeCount(1);
    await this._task(on);
    const until = Date.now() + 20000;
    for (;;) {
      const mon = await this.find().catch(() => null);
      if (!!mon === on) {
        this._set({ on });
        return mon || true;
      }
      // Not on the desktop yet: Windows may show it as a Duplicate of another monitor (it
      // remembers that per set of monitors). The helper extends only then.
      if (on) await this.helper.request('displayExtend', { monitor: MONITOR_ID }).catch(() => {});
      if (Date.now() > until) {
        this._set({ message: on ? 'The virtual monitor didn’t appear' : 'The virtual monitor didn’t go away' });
        return false;
      }
      await new Promise((r) => setTimeout(r, 500));
    }
  }

  // Extend's virtual monitor on the desktop: {name, x, y, width, height} in physical px, or null. The
  // driver's other monitors are the added ones (extraMons), in name order.
  async find(all = false) {
    const r = await this.helper.request('displays');
    const mons = (r.displays || []).filter((d) => ADAPTER.test(d.adapter || ''))
      .sort((a, b) => String(a.name).localeCompare(String(b.name), 'en', { numeric: true }));
    if (!this.extras.length && !all) { // one monitor, Extend's, whatever wanted says (as before)
      this.mon = mons[0] || null;
      this.extraMons = [];
      return this.mon;
    }
    this.mon = this.wanted ? mons[0] || null : null;
    this.extraMons = all ? mons.slice(this.mon ? 1 : 0) : (this.wanted ? mons.slice(1) : mons).slice(0, this.extras.length);
    return this.mon;
  }

  // Each added monitor at its size.
  async _sizeExtras() {
    for (let i = 0; i < this.extraMons.length && i < this.extras.length; i++) {
      const v = this.extras[i];
      const m = this.extraMons[i];
      if (m.width === v.width && m.height === v.height) continue;
      try { await this.helper.request('displayMode', { name: m.name, width: v.width, height: v.height }); } catch (_) { /* keeps its size */ }
    }
  }

  // The added monitors for the page: [{slot, name, x, y, width, height}] of those on the desktop.
  extrasView() {
    return this.extraMons.map((m, i) => ({ slot: (this.extras[i] || {}).slot, name: m.name, x: m.x, y: m.y, width: m.width, height: m.height }));
  }

  // Before switching on: make sure the Mac's preferred size is one of the driver's modes (it reads
  // its settings when the device starts). Then, once on, set that size. A portrait size (a phone)
  // is its landscape mode, turned by setMode.
  addMode(width, height) {
    [width, height] = [Math.max(width, height), Math.min(width, height)];
    try {
      let xml = fs.readFileSync(SETTINGS_XML, 'utf8');
      // A size under 640 × 480 or a portrait one (older phone Extends added them) keeps the whole
      // monitor from coming on.
      const bad = /\s*<resolution>\s*<width>\s*(\d+)\s*<\/width>\s*<height>\s*(\d+)\s*<\/height>[\s\S]*?<\/resolution>/g;
      const cleaned = xml.replace(bad, (r, w, h) => (Number(w) < 640 || Number(h) < 480 || Number(w) < Number(h) ? '' : r));
      const dropped = cleaned !== xml;
      xml = cleaned;
      if (dropped) fs.writeFileSync(SETTINGS_XML, xml);
      const has = new RegExp('<width>\\s*' + width + '\\s*</width>\\s*<height>\\s*' + height + '\\s*</height>');
      if (has.test(xml) || !/<\/resolutions>/.test(xml)) return dropped;
      xml = xml.replace(/<\/resolutions>/, '    <resolution>\n            <width>' + width + '</width>\n            <height>' + height
        + '</height>\n            <refresh_rate>60</refresh_rate>\n        </resolution>\n    </resolutions>');
      fs.writeFileSync(SETTINGS_XML, xml);
      return true; // read when the device starts
    } catch (_) { return false; /* not writable: the driver's own sizes */ }
  }

  async setMode(mon, width, height) {
    try {
      await this.helper.request('displayMode', { name: mon.name, width, height });
    } catch (_) { /* keeps its size */ }
    return this.find();
  }
}

module.exports = Vdd;