Kaleido-Desktop/src/platform/native.ts
Elijah Kuntz 7d0803481b Port Kaleido Desktop to macOS
macOS (Apple silicon) now plays, browses and updates like Windows:

- Video: libmpv's render API draws into a CAOpenGLLayer beneath the
  WKWebView, with the miniplayer rectangle, HDR passthrough through
  extended dynamic range (PQ/BT.2020) and display-sleep prevention.
- Window: native traffic lights on the top bar's centre line, hidden
  with the player's controls; the page's caption buttons are Windows-only.
- Interface: macOS shortcut labels (⌘K, ⌘[, ⌃⌘F), Plex identifies the
  player as a Mac, and header values are kept ASCII (Mac computer names
  usually contain a curly apostrophe).
- The window appears without waiting for an animation frame, which
  WKWebView doesn't run in a hidden window.
- Credentials: release builds use the Keychain and are signed with a
  lasting self-signed certificate so access survives updates; debug
  builds keep tokens in a private file to avoid prompts on every rebuild.
- Bundling: scripts/fetch-libmpv.sh makes Homebrew's libmpv and its
  libraries self-contained; scripts/build.sh builds the .app, .dmg and
  signed update archive.

Releases now carry both platforms: publish-release.mjs uploads each
machine's build into one release, and update-manifest.mjs writes the
feed from that release's assets, refusing while a platform is missing.

The updater uses a new signing key (public key in tauri.conf.json), so
existing installs must be reinstalled once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:14:40 -07:00

185 lines
6.9 KiB
TypeScript

/**
* The boundary between Kaleido and its host. In the desktop app this talks to
* the Rust side through Tauri; in a plain browser (used for UI development) it
* degrades gracefully: no video, no downloads, tokens in localStorage.
*/
import type { UnlistenFn } from '@tauri-apps/api/event';
export const isNative = typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
/** The host OS, known synchronously from the web view (WebView2, WKWebView, WebKitGTK). */
export const hostOS: 'windows' | 'macos' | 'linux' =
typeof navigator !== 'undefined' && /Macintosh|Mac OS X/.test(navigator.userAgent) ? 'macos' : typeof navigator !== 'undefined' && /Linux|X11/.test(navigator.userAgent) ? 'linux' : 'windows';
export const isMac = hostOS === 'macos';
/** A shortcut with the platform's command key: "⌘K" on macOS, "Ctrl + K" elsewhere. */
export const shortcut = (key: string) => (isMac ? `⌘${key}` : `Ctrl + ${key}`);
/** How the window enters full screen from the keyboard. */
export const fullscreenShortcut = isMac ? '⌃⌘F' : 'F11';
export async function invoke<T>(cmd: string, args?: Record<string, unknown>): Promise<T> {
if (!isNative) throw new Error(`${cmd} is only available in the desktop app.`);
const { invoke } = await import('@tauri-apps/api/core');
return invoke<T>(cmd, args);
}
export async function listen<T>(event: string, handler: (payload: T) => void): Promise<UnlistenFn> {
if (!isNative) return () => {};
const { listen } = await import('@tauri-apps/api/event');
return listen<T>(event, (e) => handler(e.payload));
}
/** HTTP for Plex APIs: native requests avoid CORS and local-network limits. */
let nativeFetch: typeof fetch | null = null;
export async function httpFetch(input: string, init?: RequestInit): Promise<Response> {
if (!isNative) return fetch(input, init);
if (!nativeFetch) nativeFetch = (await import('@tauri-apps/plugin-http')).fetch as typeof fetch;
return nativeFetch(input, init);
}
export const secrets = {
async get(key: string): Promise<string | null> {
if (!isNative) return localStorage.getItem(`kaleido.dev.secret.${key}`);
return invoke<string | null>('secret_get', { key });
},
async set(key: string, value: string): Promise<void> {
if (!isNative) return localStorage.setItem(`kaleido.dev.secret.${key}`, value);
await invoke('secret_set', { key, value });
},
async delete(key: string): Promise<void> {
if (!isNative) return localStorage.removeItem(`kaleido.dev.secret.${key}`);
await invoke('secret_delete', { key });
},
};
export interface AppInfo {
version: string;
dataDir: string;
defaultDownloadDir: string;
platform: string;
osVersion: string;
deviceName: string;
/** Graphics adapters by name (empty where not reported). */
gpus: string[];
}
let info: AppInfo | null = null;
export async function appInfo(): Promise<AppInfo> {
if (info) return info;
info = isNative
? await invoke<AppInfo>('app_info')
: { version: '0.1.0-dev', dataDir: '', defaultDownloadDir: '', platform: 'browser', osVersion: '', deviceName: 'Browser preview', gpus: [] };
return info;
}
/** Local development only: start signed in from the Android project's `.env`. */
export async function devSession(): Promise<{ server: string; token: string } | null> {
if (!import.meta.env.DEV) return null;
try {
if (isNative) return await invoke<{ server: string; token: string } | null>('dev_session');
const r = await fetch('/__dev/session');
if (!r.ok) return null;
const j = await r.json();
return j.server && j.token ? j : null;
} catch {
return null;
}
}
export const win = {
async current() {
const { getCurrentWindow } = await import('@tauri-apps/api/window');
return getCurrentWindow();
},
async minimize() {
if (isNative) (await this.current()).minimize();
},
async toggleMaximize() {
if (isNative) (await this.current()).toggleMaximize();
},
async close() {
if (isNative) (await this.current()).close();
},
async isMaximized() {
return isNative ? (await this.current()).isMaximized() : false;
},
async setFullscreen(on: boolean) {
if (isNative) return (await this.current()).setFullscreen(on);
if (on) await document.documentElement.requestFullscreen?.().catch(() => {});
else if (document.fullscreenElement) await document.exitFullscreen().catch(() => {});
},
async isFullscreen() {
return isNative ? (await this.current()).isFullscreen() : !!document.fullscreenElement;
},
async show() {
if (isNative) {
const w = await this.current();
await w.show();
await w.setFocus();
}
},
/** The OS's own window buttons (the macOS traffic lights); elsewhere the page draws them. */
async setButtonsVisible(visible: boolean) {
if (isNative && isMac) await invoke('window_buttons', { visible }).catch(() => {});
},
async onResized(cb: () => void): Promise<UnlistenFn> {
if (!isNative) {
window.addEventListener('resize', cb);
return () => window.removeEventListener('resize', cb);
}
return (await this.current()).onResized(cb);
},
};
export async function openExternal(url: string) {
if (!isNative) {
window.open(url, '_blank', 'noopener');
return;
}
const { openUrl } = await import('@tauri-apps/plugin-opener');
await openUrl(url);
}
export async function revealPath(path: string) {
if (!isNative) return;
const { revealItemInDir } = await import('@tauri-apps/plugin-opener');
await revealItemInDir(path);
}
export async function pickFolder(defaultPath?: string): Promise<string | null> {
if (!isNative) return null;
const { open } = await import('@tauri-apps/plugin-dialog');
const r = await open({ directory: true, defaultPath, multiple: false });
return typeof r === 'string' ? r : null;
}
export async function pickFile(filters?: { name: string; extensions: string[] }[]): Promise<string | null> {
if (!isNative) return null;
const { open } = await import('@tauri-apps/plugin-dialog');
const r = await open({ directory: false, multiple: false, filters });
return typeof r === 'string' ? r : null;
}
export async function saveFile(defaultPath: string): Promise<string | null> {
if (!isNative) return null;
const { save } = await import('@tauri-apps/plugin-dialog');
return (await save({ defaultPath })) ?? null;
}
/** Converts a local file path to a URL the web view may load (offline artwork). */
export async function localFileUrl(path: string): Promise<string> {
if (!isNative || !path) return '';
const { convertFileSrc } = await import('@tauri-apps/api/core');
return convertFileSrc(path);
}
/** Absolute path of a file bundled with the app (Tauri resources), or '' in a browser. */
export async function resourcePath(relative: string): Promise<string> {
if (!isNative) return '';
const { resolveResource } = await import('@tauri-apps/api/path');
return resolveResource(relative);
}
export function keepAwake(enabled: boolean) {
if (isNative) invoke('keep_awake', { enabled }).catch(() => {});
}