Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

8.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import {
  DEFAULT_APP_WINDOW_SIZE_BOUNDS,
  type LogicalWindowSize,
  type WindowSizeBounds,
  calculateWindowSizeBounds,
} from "./window-layout.ts";

export type WindowLayoutGuard = () => boolean;

export async function prepareSetupWindow(options: {
  resetLayout: () => Promise<unknown>;
  unmaximize: () => Promise<void>;
  clearConstraints: () => Promise<void>;
  enableResize: () => Promise<void>;
  resizeForSetup: () => Promise<boolean>;
  disableResize: () => Promise<void>;
  isCurrent: WindowLayoutGuard;
}): Promise<boolean> {
  const {
    resetLayout,
    unmaximize,
    clearConstraints,
    enableResize,
    resizeForSetup,
    disableResize,
    isCurrent,
  } = options;
  await resetLayout();
  if (!isCurrent()) return false;
  await unmaximize();
  if (!isCurrent()) return false;
  await clearConstraints();
  if (!isCurrent()) return false;
  // GTK can ignore a size change on a non-resizable restored window.
  await enableResize();
  if (!isCurrent()) return false;
  if (!(await resizeForSetup()) || !isCurrent()) return false;
  await disableResize();
  return isCurrent();
}

type WorkAreaMonitor = {
  scaleFactor: number;
  workArea: {
    size: {
      toLogical: (scaleFactor: number) => LogicalWindowSize;
    };
  };
};

type PhysicalWindowSize = {
  width: number;
  height: number;
};

export type MeasuredWindowLayout<Monitor extends WorkAreaMonitor> = {
  bounds: WindowSizeBounds;
  monitor: Monitor | null;
  frameSize: PhysicalWindowSize;
};

type WindowMonitorReader<Monitor extends WorkAreaMonitor> = {
  currentMonitor: () => Promise<Monitor | null>;
  primaryMonitor: () => Promise<Monitor | null>;
  innerSize?: () => Promise<PhysicalWindowSize>;
  outerSize?: () => Promise<PhysicalWindowSize>;
};

/**
 * Size bounds the window must stay within on its current monitor. logicalPerCssPx reports the
 * webview's zoom above the monitor's display scale, keeping the resize floor in CSS pixels under
 * Windows text scaling; the default no-op covers platforms without it.
 */
export async function measureWindowLayout<Monitor extends WorkAreaMonitor>(
  reader: WindowMonitorReader<Monitor>,
  isCurrent: WindowLayoutGuard,
  logicalPerCssPx: (monitorScale: number) => number = () => 1,
): Promise<MeasuredWindowLayout<Monitor> | null> {
  // Some platforms cannot resolve the monitor for a hidden window.
  const monitor =
    (await reader.currentMonitor()) ?? (await reader.primaryMonitor());
  if (!isCurrent()) return null;

  const frameSize = { width: 0, height: 0 };
  let availableInnerSize: LogicalWindowSize | undefined;
  if (monitor) {
    availableInnerSize = monitor.workArea.size.toLogical(monitor.scaleFactor);
    if (reader.innerSize && reader.outerSize) {
      const [innerSize, outerSize] = await Promise.all([
        reader.innerSize(),
        reader.outerSize(),
      ]);
      if (!isCurrent()) return null;
      frameSize.width = Math.max(0, outerSize.width - innerSize.width);
      frameSize.height = Math.max(0, outerSize.height - innerSize.height);
      // Tauri sizes the inner rectangle but positions the outer rectangle.
      availableInnerSize = {
        width: Math.max(
          1,
          availableInnerSize.width - frameSize.width / monitor.scaleFactor,
        ),
        height: Math.max(
          1,
          availableInnerSize.height - frameSize.height / monitor.scaleFactor,
        ),
      };
    }
  }

  const bounds = availableInnerSize
    ? calculateWindowSizeBounds(
        availableInnerSize,
        monitor ? logicalPerCssPx(monitor.scaleFactor) : 1,
      )
    : DEFAULT_APP_WINDOW_SIZE_BOUNDS;
  return { bounds, monitor, frameSize };
}

export function shouldFinishWindowLayoutWait(
  sawNativeChange: boolean,
): boolean {
  return sawNativeChange;
}

type ResolutionQuery = {
  addEventListener: (type: "change", listener: () => void) => void;
  removeEventListener: (type: "change", listener: () => void) => void;
};

export type PixelRatioSource = {
  devicePixelRatio: () => number;
  matchResolution: (dppx: number) => ResolutionQuery | null;
};

/** No event for DPR changes, so a matchMedia query for the current ratio stands in. */
export function observeDevicePixelRatio(
  source: PixelRatioSource,
  onChange: () => void,
): () => void {
  let query: ResolutionQuery | null = null;
  let disposed = false;
  const listen = () => {
    query?.removeEventListener("change", handle);
    query = disposed ? null : source.matchResolution(source.devicePixelRatio());
    query?.addEventListener("change", handle);
  };
  function handle() {
    listen();
    if (!disposed) onChange();
  }
  listen();
  return () => {
    disposed = true;
    query?.removeEventListener("change", handle);
    query = null;
  };
}
type FinalizeAppWindowLayoutOptions<Monitor extends WorkAreaMonitor> = {
  restored: boolean;
  nativeRestored?: boolean;
  measured: MeasuredWindowLayout<Monitor>;
  show: () => Promise<boolean>;
  waitForSettled?: () => Promise<void>;
  measure: () => Promise<MeasuredWindowLayout<Monitor> | null>;
  setMinimumConstraints: (minimum: LogicalWindowSize) => Promise<void>;
  enforceBounds: (bounds: WindowSizeBounds) => Promise<void>;
  isCurrent: WindowLayoutGuard;
};

export async function finalizeAppWindowLayout<Monitor extends WorkAreaMonitor>({
  restored,
  nativeRestored = false,
  measured,
  show,
  waitForSettled,
  measure,
  setMinimumConstraints,
  enforceBounds,
  isCurrent,
}: FinalizeAppWindowLayoutOptions<Monitor>): Promise<void> {
  if (!isCurrent()) return;
  // restoreState returns before native resize lands; showing now flashes the setup size.
  if (restored && !nativeRestored) {
    await waitForSettled?.();
    if (!isCurrent()) return;
  }
  const shown = await show();
  if (!isCurrent()) return;
  // A restored hidden autostart cannot resolve its saved monitor yet; wait for tray reveal.
  if (restored && !shown) return;
  if (restored) {
    // A hidden GTK window only refreshes its cached size once mapped.
    if (nativeRestored) await waitForSettled?.();
    if (!isCurrent()) return;
    measured = (await measure()) ?? measured;
    if (!isCurrent()) return;
  }

  await setMinimumConstraints(measured.bounds.minimum);
  if (!isCurrent()) return;
  // Do not cap restored sizes against a temporary monitor fallback.
  await enforceBounds(
    restored ? { minimum: measured.bounds.minimum } : measured.bounds,
  );
}

type MinimumSizeWindow = {
  isRestored: () => Promise<boolean>;
  onResized: (handler: () => void) => Promise<() => void>;
  applyFloor: (minimum: LogicalWindowSize) => Promise<void>;
};

export type MinimumSizeApplier = {
  apply: (minimum: LogicalWindowSize) => Promise<void>;
  /** Drops a floor still waiting, e.g. before setup clears the constraints. */
  cancel: () => void;
};

/**
 * tao applies a size floor by resizing to its inner size, which drops maximized first, so a
 * maximized window comes back at full-screen size, its bottom under the Windows taskbar (#13616); a
 * call while maximized, fullscreen or minimized waits for restore.
 */
export function createMinimumSizeApplier(
  win: MinimumSizeWindow,
): MinimumSizeApplier {
  let pending: LogicalWindowSize | null = null;
  let listening: Promise<() => void> | null = null;

  const stopListening = () => {
    const unlisten = listening;
    listening = null;
    unlisten?.then((stop) => stop()).catch(() => undefined);
  };

  const flush = async () => {
    if (!pending || !(await win.isRestored()) || !pending) return;
    const minimum = pending;
    pending = null;
    stopListening();
    await win.applyFloor(minimum);
  };

  return {
    apply: async (minimum) => {
      pending = minimum;
      if (await win.isRestored()) {
        await flush();
        return;
      }
      listening ??= win.onResized(() => {
        flush().catch(() => undefined);
      });
      await listening;
      // A restore that landed while the listener was registering sent no resize here.
      await flush();
    },
    cancel: () => {
      pending = null;
      stopListening();
    },
  };
}