Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

6.0 KB
Raw Blame
/**
 * Native Windows OS-key (Windows key) hotkey bridge for Tauri desktop builds.
 *
 * When Ink Studio is the foreground window on Windows, registers a lightweight, on-demand
 * WH_KEYBOARD_LL hook ONLY for user-configured `OS+...` shortcuts (or while actively recording
 * a shortcut) so Windows Shell does not hijack bound combinations (e.g. Win+1, Win+E, Win+Q)
 * or pop up the Start Menu. Safe no-op in Web/browser and test environments.
 */

import { isTauriEnvironment } from './tauriEnv';
import {
  CommandDefinition,
  KeyboardEventLike,
  parseShortcut,
  resolveCommandShortcut,
} from './shortcutManager';
import { ShortcutOverrides } from '../types/settings';

export interface NativeOsHotkeyBinding {
  code: string;
  ctrl: boolean;
  shift: boolean;
  alt: boolean;
}

export interface NativeOsHotkeyEvent extends KeyboardEventLike {
  phase: 'keydown' | 'keyup';
  code: string;
  key: string;
  ctrlKey: boolean;
  metaKey: boolean;
  shiftKey: boolean;
  altKey: boolean;
  repeat: boolean;
  isRecording: boolean;
}

export type NativeOsHotkeyListener = (event: NativeOsHotkeyEvent) => void;

const listeners = new Set<NativeOsHotkeyListener>();
let activeRecordingCount = 0;
let lastBindings: NativeOsHotkeyBinding[] = [];
let lastSentSignature = '';
let activeChannel: unknown = null;

/**
 * Extracts all unique OS/Win-key (`meta: true`) bindings from the active command registry
 * + shortcut overrides, including alternate key codes (e.g. Numpad0 for Digit0).
 */
export function extractNativeOsHotkeyBindings(
  commands: readonly CommandDefinition[],
  overrides?: ShortcutOverrides
): NativeOsHotkeyBinding[] {
  const seen = new Set<string>();
  const bindings: NativeOsHotkeyBinding[] = [];

  const pushCode = (code: string, ctrl: boolean, shift: boolean, alt: boolean) => {
    const key = `${code}|${ctrl ? 1 : 0}|${shift ? 1 : 0}|${alt ? 1 : 0}`;
    if (seen.has(key)) return;
    seen.add(key);
    bindings.push({ code, ctrl, shift, alt });
  };

  const inspectRaw = (raw: string) => {
    const parsed = parseShortcut(raw);
    if (!parsed || !parsed.meta) return;
    pushCode(parsed.code, parsed.ctrl, parsed.shift, parsed.alt);
    if (parsed.altCodes) {
      for (const altCode of parsed.altCodes) {
        pushCode(altCode, parsed.ctrl, parsed.shift, parsed.alt);
      }
    }
  };

  for (const cmd of commands) {
    const bound = resolveCommandShortcut(cmd, overrides);
    if (bound) inspectRaw(bound);
  }

  // Also include any OS-key overrides whose dynamic command might not be synced yet
  if (overrides) {
    for (const val of Object.values(overrides)) {
      if (val) inspectRaw(val);
    }
  }

  return bindings;
}

function buildSignature(bindings: readonly NativeOsHotkeyBinding[], recording: boolean): string {
  const sorted = bindings
    .map((b) => `${b.code}:${b.ctrl ? 1 : 0}${b.shift ? 1 : 0}${b.alt ? 1 : 0}`)
    .sort()
    .join(',');
  return `${recording ? 'R' : 'N'}|${sorted}`;
}

let nativeSyncGeneration = 0;
let nativeSyncChain: Promise<void> = Promise.resolve();

async function runNativeSyncStep(gen: number): Promise<void> {
  if (gen !== nativeSyncGeneration) return;
  const recording = activeRecordingCount > 0;
  const bindingsSnapshot = lastBindings.slice();
  const sig = buildSignature(bindingsSnapshot, recording);
  if (sig === lastSentSignature && activeChannel !== null) return;

  if (!isTauriEnvironment()) {
    lastSentSignature = sig;
    return;
  }

  try {
    const { invoke, Channel } = await import('@tauri-apps/api/core');
    if (gen !== nativeSyncGeneration) return;

    if (bindingsSnapshot.length === 0 && !recording) {
      if (activeChannel !== null) {
        await invoke('os_hotkeys_stop');
      }
      if (gen === nativeSyncGeneration) {
        lastSentSignature = sig;
      }
      return;
    }

    if (!activeChannel) {
      const ch = new Channel<NativeOsHotkeyEvent>();
      ch.onmessage = (ev: NativeOsHotkeyEvent) => {
        for (const fn of Array.from(listeners)) {
          try {
            fn(ev);
          } catch (err) {
            console.error('Native OS hotkey listener error:', err);
          }
        }
      };
      activeChannel = ch;
    }

    await invoke('os_hotkeys_sync', {
      bindings: bindingsSnapshot,
      recording,
      onEvent: activeChannel,
    });
    if (gen === nativeSyncGeneration) {
      lastSentSignature = sig;
    }
  } catch {
    // Non-desktop or unavailable backend: keep silent fallback to DOM KeyboardEvents
  }
}

function flushNativeSync(): Promise<void> {
  const gen = ++nativeSyncGeneration;
  nativeSyncChain = nativeSyncChain.then(() => runNativeSyncStep(gen));
  return nativeSyncChain;
}

export function syncNativeOsHotkeys(
  commands: readonly CommandDefinition[],
  overrides?: ShortcutOverrides
): void {
  lastBindings = extractNativeOsHotkeyBindings(commands, overrides);
  void flushNativeSync();
}

/**
 * Marks shortcut recording active/inactive so the native Windows hook temporarily captures
 * any `Win + <key>` combination without triggering Windows Shell actions.
 * Returns a cleanup function that decrements the recording ref-count.
 */
export function acquireNativeOsHotkeyRecording(): () => void {
  activeRecordingCount += 1;
  void flushNativeSync();
  let released = false;
  return () => {
    if (released) return;
    released = true;
    activeRecordingCount = Math.max(0, activeRecordingCount - 1);
    void flushNativeSync();
  };
}

export function subscribeNativeOsHotkeys(listener: NativeOsHotkeyListener): () => void {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

export function stopNativeOsHotkeys(): void {
  lastBindings = [];
  activeRecordingCount = 0;
  lastSentSignature = '';
  activeChannel = null;
  if (!isTauriEnvironment()) return;
  void import('@tauri-apps/api/core')
    .then(({ invoke }) => invoke('os_hotkeys_stop'))
    .catch(() => {});
}

/** Test helper for dispatching synthetic native OS-key events in Vitest */
export function dispatchNativeOsHotkeyForTest(event: NativeOsHotkeyEvent): void {
  for (const fn of Array.from(listeners)) {
    fn(event);
  }
}