Skip to content

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

41.5 KB
Raw Blame
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import {
  Sparkles,
  MemoryStick,
  Monitor,
  HardDrive,
  ChevronDown,
  ChevronRight,
  RefreshCw,
  Trash2,
  RotateCw,
  Check,
  AlertTriangle,
  SlidersHorizontal,
} from 'lucide-react';
import {
  AppSettings,
  CanvasFilteringQuality,
  DEFAULT_APP_SETTINGS,
  DesktopGraphicsApi,
  GpuPowerPreference,
  GpuTexturePoolPreset,
  PerformancePresetId,
  Preview3DMaxResolution,
  RenderBackend,
  ScratchDiskCompression,
  ViewportResolutionScale,
} from '../types/settings';
import {
  GPU_TEXTURE_POOL_CONFIGS,
  LiveMemoryTelemetry,
  PurgeScope,
  SystemHardwareInfo,
  buildPerformancePreset,
  computeAdobeMemoryLimits,
  computeRecommendedSettings,
  memoryMbToPercent,
  memoryPercentToMb,
  performanceManager,
} from '../utils/performanceManager';
import { useI18n } from '../i18n';

interface PerformanceSettingsTabProps {
  settings: AppSettings;
  isDesktopTauri: boolean;
  onUpdateSettings: (next: AppSettings) => void;
  onShowToast: (message: string) => void;
}

function formatMb(mb: number): string {
  if (mb >= 1024) {
    return `${(mb / 1024).toFixed(mb % 1024 === 0 ? 0 : 1)} GB`;
  }
  return `${Math.round(mb)} MB`;
}

function formatGpuKindLabel(kind: string): string {
  switch (kind) {
    case 'discrete':
      return 'Dedicated';
    case 'integrated':
      return 'Integrated';
    case 'software':
      return 'Software';
    default:
      return 'GPU';
  }
}

export const PerformanceSettingsTab: React.FC<PerformanceSettingsTabProps> = ({
  settings: rawSettings,
  isDesktopTauri,
  onUpdateSettings,
  onShowToast,
}) => {
  const { t, tc, td, lang } = useI18n();
  // Defensive merge so hot-reloaded or legacy partial settings objects never have undefined fields
  const settings: AppSettings = useMemo(
    () => ({
      ...DEFAULT_APP_SETTINGS,
      ...rawSettings,
    }),
    [rawSettings]
  );

  const [hwInfo, setHwInfo] = useState<SystemHardwareInfo | null>(null);
  const [telemetry, setTelemetry] = useState<LiveMemoryTelemetry | null>(null);
  const [isRefreshingHw, setIsRefreshingHw] = useState(false);
  const [isPurging, setIsPurging] = useState(false);
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [scratchPathInput, setScratchPathInput] = useState(settings.scratchDiskPath || '');
  const [scratchError, setScratchError] = useState<string | null>(null);
  const [isApplyingScratch, setIsApplyingScratch] = useState(false);

  useEffect(() => {
    setScratchPathInput(settings.scratchDiskPath || '');
  }, [settings.scratchDiskPath]);

  const refreshHardware = useCallback(async (force = false) => {
    setIsRefreshingHw(true);
    try {
      const info = await performanceManager.detectHardwareInfo(force);
      setHwInfo(info);
      return info;
    } finally {
      setIsRefreshingHw(false);
    }
  }, []);

  const refreshTelemetry = useCallback(async () => {
    const memTelemetry = await performanceManager.getMemoryTelemetry();
    setTelemetry(memTelemetry);
  }, []);

  useEffect(() => {
    void refreshHardware(false);
    void refreshTelemetry();
    const id = setInterval(() => {
      void refreshTelemetry();
    }, 1500);
    return () => clearInterval(id);
  }, [refreshHardware, refreshTelemetry]);

  const totalRamMb = hwInfo?.totalRamMb ?? 8192;
  const cpuCores = hwInfo?.cpuLogicalCores ?? 4;
  const memLimits = useMemo(() => computeAdobeMemoryLimits(totalRamMb), [totalRamMb]);

  const recommended = useMemo(
    () =>
      computeRecommendedSettings(
        hwInfo ?? {
          totalRamMb,
          cpuLogicalCores: cpuCores,
          gpus: [],
          activeWebGl: {
            available: true,
            renderer: 'WebGL2 GPU',
            vendor: 'Generic',
            glVersion: 'WebGL 2.0',
            maxTextureSize: 4096,
            maxArrayLayers: 256,
          },
        }
      ),
    [hwInfo, totalRamMb, cpuCores, lang]
  );

  const currentBudgetMb = Math.max(
    memLimits.minMb,
    Math.min(memLimits.maxMb, settings.tileMemoryBudgetMb || 1024)
  );
  const currentPercent = memoryMbToPercent(currentBudgetMb, totalRamMb);
  const isAutoMode = Boolean(settings.autoOptimizePerformance);

  const patchManual = (patch: Partial<AppSettings>) => {
    onUpdateSettings({
      ...settings,
      ...patch,
      autoOptimizePerformance: false,
    });
  };

  const handleEnableAuto = async (showFeedback = true) => {
    const info = hwInfo ?? (await refreshHardware(false));
    const rec = computeRecommendedSettings(info);
    onUpdateSettings({
      ...settings,
      ...rec.settings,
      autoOptimizePerformance: true,
    });
    if (showFeedback) {
      onShowToast(t('Automatic optimization enabled ({summary})', { summary: rec.summary }));
    }
  };

  const handleToggleAuto = (checked: boolean) => {
    if (checked) {
      void handleEnableAuto(true);
    } else {
      onUpdateSettings({ ...settings, autoOptimizePerformance: false });
    }
  };

  const handleApplyPreset = (presetId: PerformancePresetId, label: string) => {
    const presetPatch = buildPerformancePreset(presetId, totalRamMb);
    onUpdateSettings({
      ...settings,
      ...presetPatch,
      autoOptimizePerformance: false,
    });
    onShowToast(t('Switched to "{mode}" mode', { mode: t(label) }));
  };

  const handlePercentSliderChange = (nextPct: number) => {
    const nextMb = memoryPercentToMb(nextPct, totalRamMb);
    patchManual({
      memoryAllocationPercent: nextPct,
      tileMemoryBudgetMb: nextMb,
    });
  };

  const handleBudgetMbInputChange = (rawMb: number) => {
    if (!Number.isFinite(rawMb)) return;
    const clampedMb = Math.max(memLimits.minMb, Math.min(memLimits.maxMb, Math.round(rawMb)));
    const nextPct = memoryMbToPercent(clampedMb, totalRamMb);
    patchManual({
      tileMemoryBudgetMb: clampedMb,
      memoryAllocationPercent: nextPct,
    });
  };

  const handlePurge = async (scope: PurgeScope) => {
    if (isPurging) return;
    setIsPurging(true);
    try {
      const res = await performanceManager.purgeMemory(scope);
      await refreshTelemetry();
      const parts: string[] = [];
      if (res.freedTileMb > 0) parts.push(t('{mb} MB tiles', { mb: res.freedTileMb }));
      if (res.offloadedUndoSteps > 0) {
        parts.push(t('{n} undo steps', { n: res.offloadedUndoSteps }));
      }
      if (res.flushedGpuTextures) parts.push(t('GPU cache'));
      if (res.freedScratchDiskMb > 0) {
        parts.push(t('{mb} MB scratch', { mb: res.freedScratchDiskMb }));
      }
      onShowToast(
        parts.length > 0
          ? t('Freed {items}', { items: parts.join(', ') })
          : t('Memory caches are already clean')
      );
    } finally {
      setIsPurging(false);
    }
  };

  const handleApplyScratchPath = async (nextPath: string) => {
    setScratchError(null);
    setIsApplyingScratch(true);
    try {
      const candidate: AppSettings = { ...settings, scratchDiskPath: nextPath.trim() };
      const result = await performanceManager.syncDesktopBackendConfig(candidate);
      if (!result.ok) {
        setScratchError(result.error || t('Unable to validate scratch disk directory'));
        return;
      }
      if (result.info) {
        setHwInfo(result.info);
      }
      onUpdateSettings(candidate);
      onShowToast(
        nextPath.trim()
          ? t('Scratch disk location updated')
          : t('Scratch disk reset to system temporary folder')
      );
    } finally {
      setIsApplyingScratch(false);
    }
  };

  const handleRelaunchDesktop = async () => {
    if (!isDesktopTauri) return;
    try {
      await performanceManager.syncDesktopBackendConfig(settings);
      const { relaunch } = await import('@tauri-apps/plugin-process');
      await relaunch();
    } catch (err) {
      onShowToast(
        err instanceof Error
          ? t('Restart failed: {message}', { message: err.message })
          : t('Please restart Ink Studio manually')
      );
    }
  };

  const needsRestart = performanceManager.needsRestartForDesktopGpuFlags(settings);
  const activeRendererName =
    telemetry?.compositor?.rendererName || hwInfo?.activeWebGl?.renderer || t('Detecting...');
  const activeRendererLower = activeRendererName.toLowerCase();
  const activePoolSpec =
    GPU_TEXTURE_POOL_CONFIGS[settings.gpuTexturePoolPreset] ?? GPU_TEXTURE_POOL_CONFIGS.high;
  const workerThreadsValue = Number.isFinite(settings.cpuWorkerThreads)
    ? settings.cpuWorkerThreads
    : 0;

  const barScaleMax = memLimits.totalRamMb;
  const allocatedPctOfTotal = Math.min(100, (currentBudgetMb / barScaleMax) * 100);
  const idealLeftPct = (memLimits.idealMinMb / barScaleMax) * 100;
  const idealWidthPct = Math.max(
    4,
    ((memLimits.idealMaxMb - memLimits.idealMinMb) / barScaleMax) * 100
  );
  const isOverIdeal = currentBudgetMb > memLimits.idealMaxMb;

  return (
    <div className="space-y-4" data-testid="performance-settings-tab">
      {/* 1. Automatic Optimization Hero & Quick Mode Selector */}
      <section className="rounded-ui-md bg-ui-header p-3.5 space-y-3 border border-ui-subtle">
        <div className="flex items-start justify-between gap-3">
          <div className="flex items-start gap-2.5 min-w-0">
            <Sparkles className="w-4 h-4 text-ui-accent mt-0.5 shrink-0" />
            <div className="min-w-0">
              <div className="flex items-center gap-2">
                <h3 className="text-xs font-medium text-ui-primary">{t('Automatic Settings')}</h3>
                {isAutoMode && (
                  <span className="text-[10px] px-1.5 py-0.5 rounded-ui-xs bg-ui-success/15 text-ui-success border border-ui-success/30 font-medium">
                    {tc('status', 'Active')}
                  </span>
                )}
              </div>
              <p className="text-[11px] text-ui-muted mt-0.5">
                {isAutoMode
                  ? t('Automatically tuned for your hardware: {summary}', {
                      summary: recommended.summary,
                    })
                  : t('Custom settings active. Turn on to let Ink Studio tune RAM, GPU, and caches automatically.')}
              </p>
            </div>
          </div>

          <label className="flex items-center gap-2 shrink-0 cursor-pointer pt-0.5">
            <input
              type="checkbox"
              aria-label={t('Automatic performance settings')}
              checked={isAutoMode}
              onChange={(e) => handleToggleAuto(e.target.checked)}
            />
          </label>
        </div>

        {/* Quick Mode Bar */}
        <div className="grid grid-cols-4 gap-1.5">
          <button
            type="button"
            onClick={() => void handleEnableAuto(true)}
            className={`py-1.5 px-2 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
              isAutoMode
                ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
            }`}
          >
            {t('Auto')}
          </button>
          <button
            type="button"
            onClick={() => handleApplyPreset('maximum', 'Max Performance')}
            className={`py-1.5 px-2 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
              !isAutoMode && settings.renderBackend === 'webgl2' && settings.gpuPowerPreference === 'high-performance'
                ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
            }`}
          >
            {t('Performance')}
          </button>
          <button
            type="button"
            onClick={() => handleApplyPreset('battery', 'Battery Saver')}
            className={`py-1.5 px-2 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
              !isAutoMode && settings.gpuPowerPreference === 'low-power'
                ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
            }`}
          >
            {t('Battery')}
          </button>
          <button
            type="button"
            onClick={() => handleApplyPreset('compatibility', 'CPU Safe Mode')}
            className={`py-1.5 px-2 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
              !isAutoMode && settings.renderBackend === 'canvas2d'
                ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
            }`}
          >
            {t('CPU Safe')}
          </button>
        </div>

        {/* Compact System Strip */}
        <div className="flex items-center justify-between gap-2 pt-2 border-t border-ui-subtle text-[10px] text-ui-muted font-ui-mono tabular-nums">
          <div className="flex items-center gap-2 min-w-0 truncate">
            <span>{t('{ram} RAM', { ram: formatMb(totalRamMb) })}</span>
            <span>·</span>
            <span>{t('{count} threads', { count: cpuCores })}</span>
            <span>·</span>
            <span className="truncate text-ui-secondary" title={activeRendererName}>
              {telemetry?.compositor?.backend === 'canvas2d'
                ? t('Canvas 2D (CPU)')
                : activeRendererName}
            </span>
          </div>
          <button
            type="button"
            onClick={() => {
              void refreshHardware(true);
              void refreshTelemetry();
            }}
            disabled={isRefreshingHw}
            className="p-1 rounded-ui-xs hover:bg-ui-control-hover text-ui-muted hover:text-ui-primary cursor-pointer shrink-0 disabled:opacity-50"
            title={t('Refresh hardware & memory telemetry')}
          >
            <RefreshCw className={`w-3 h-3 ${isRefreshingHw ? 'animate-spin' : ''}`} />
          </button>
        </div>
      </section>

      {/* 2. Memory (RAM Limit) */}
      <section className="rounded-ui-md bg-ui-header p-3.5 space-y-3 border border-ui-subtle">
        <div className="flex items-center justify-between gap-2">
          <div className="flex items-center gap-2">
            <MemoryStick className="w-3.5 h-3.5 text-ui-accent" />
            <h3 className="text-xs font-medium text-ui-primary">{t('Memory Usage (Max RAM)')}</h3>
          </div>
          <div className="flex items-center gap-1.5 shrink-0">
            <input
              type="number"
              aria-label={t('Maximum RAM in MB')}
              min={memLimits.minMb}
              max={memLimits.maxMb}
              step={128}
              value={currentBudgetMb}
              onChange={(e) => handleBudgetMbInputChange(Number(e.target.value))}
              className="w-20 bg-ui-input px-2 py-1 rounded-ui-sm font-ui-mono tabular-nums text-xs text-right text-ui-primary border border-ui-default"
            />
            <span className="text-[11px] font-ui-mono tabular-nums text-ui-muted">MB ({currentPercent}%)</span>
          </div>
        </div>

        <div className="space-y-1.5">
          <div className="relative h-2 rounded-full bg-ui-control overflow-hidden">
            <div
              className="absolute top-0 bottom-0 bg-ui-success/20 border-x border-ui-success/45"
              style={{ left: `${idealLeftPct}%`, width: `${idealWidthPct}%` }}
              title={t('Ideal range: {min} – {max}', {
                min: formatMb(memLimits.idealMinMb),
                max: formatMb(memLimits.idealMaxMb),
              })}
            />
            <div
              className="h-full rounded-full transition-all duration-150"
              style={{
                width: `${allocatedPctOfTotal}%`,
                backgroundColor: isOverIdeal ? 'var(--ui-warning)' : 'var(--ui-accent)',
              }}
            />
          </div>

          <input
            type="range"
            aria-label={t('RAM allocation percentage')}
            min={20}
            max={85}
            step={1}
            value={currentPercent}
            onChange={(e) => handlePercentSliderChange(Number(e.target.value))}
            className="w-full"
          />

          <div className="flex items-center justify-between text-[10px] font-ui-mono tabular-nums text-ui-muted">
            <span>{formatMb(memLimits.minMb)}</span>
            <span className="text-ui-success">
              {t('Ideal: {min} – {max}', {
                min: formatMb(memLimits.idealMinMb),
                max: formatMb(memLimits.idealMaxMb),
              })}
            </span>
            <span>{formatMb(memLimits.maxMb)}</span>
          </div>
        </div>

        {isOverIdeal && (
          <div className="flex items-center gap-1.5 text-[10px] text-ui-warning bg-ui-warning/15 border border-ui-warning/35 rounded-ui-sm px-2 py-1">
            <AlertTriangle className="w-3 h-3 shrink-0" />
            <span>{t('Above 70% of system RAM may slow down other apps.')}</span>
          </div>
        )}

        {/* Compact Live Usage + Single Free Memory Action */}
        <div className="flex items-center justify-between gap-2 pt-2 border-t border-ui-subtle">
          <div className="text-[10px] font-ui-mono tabular-nums text-ui-muted truncate">
            {telemetry
              ? t('In use: {tileMb} MB tiles · {undoSteps} undo · ~{vramMb} MB VRAM', {
                  tileMb: telemetry.activeTileMb,
                  undoSteps: telemetry.ramUndoSteps,
                  vramMb: telemetry.compositor.estimatedVramMb,
                })
              : t('Measuring memory usage...')}
          </div>
          <button
            type="button"
            disabled={isPurging}
            onClick={() => void handlePurge('all')}
            className="flex items-center gap-1 px-2.5 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[10px] text-ui-primary font-medium cursor-pointer shrink-0 disabled:opacity-50 transition-colors"
            title={t('Offload inactive tiles & undo states and flush GPU texture cache')}
          >
            <Trash2 className="w-3 h-3 text-ui-accent" />
            <span>{t('Free Memory')}</span>
          </button>
        </div>
      </section>

      {/* 3. Graphics & Rendering */}
      <section className="rounded-ui-md bg-ui-header p-3.5 space-y-3 border border-ui-subtle">
        <div className="flex items-center gap-2">
          <Monitor className="w-3.5 h-3.5 text-ui-accent" />
          <h3 className="text-xs font-medium text-ui-primary">{t('Graphics & Rendering')}</h3>
        </div>

        <div className="grid grid-cols-3 gap-1.5">
          {(
            [
              { id: 'auto', label: 'Auto (GPU)' },
              { id: 'webgl2', label: 'WebGL2 GPU' },
              { id: 'canvas2d', label: 'Canvas 2D (CPU)' },
            ] as Array<{ id: RenderBackend; label: string }>
          ).map((opt) => {
            const selected = settings.renderBackend === opt.id;
            return (
              <button
                key={opt.id}
                type="button"
                onClick={() => patchManual({ renderBackend: opt.id })}
                className={`py-1.5 px-2 rounded-ui-sm text-[11px] transition-colors cursor-pointer border ${
                  selected
                    ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                    : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                }`}
              >
                {t(opt.label)}
              </button>
            );
          })}
        </div>

        <div className="flex items-center justify-between gap-3 pt-2 border-t border-ui-subtle">
          <span className="text-xs text-ui-primary">{t('Graphics Card')}</span>
          <select
            aria-label={t('Graphics Card Preference')}
            disabled={settings.renderBackend === 'canvas2d'}
            value={settings.gpuPowerPreference}
            onChange={(e) =>
              patchManual({ gpuPowerPreference: e.target.value as GpuPowerPreference })
            }
            className="bg-ui-input text-ui-primary text-xs px-2.5 py-1.5 rounded-ui-sm border border-ui-default cursor-pointer disabled:opacity-40"
          >
            <option value="high-performance">{t('High-Performance (Dedicated)')}</option>
            <option value="low-power">{t('Power-Saving (Integrated)')}</option>
            <option value="default">{t('System Default')}</option>
          </select>
        </div>

        {/* Detected GPUs (compact rows) */}
        {hwInfo && Array.isArray(hwInfo.gpus) && hwInfo.gpus.length > 0 && (
          <div className="space-y-1 pt-2 border-t border-ui-subtle">
            {hwInfo.gpus.map((gpu) => {
              const gpuName = gpu.name || t('Graphics Adapter');
              const isActive =
                (telemetry?.compositor?.backend === 'dx12' ||
                  telemetry?.compositor?.backend === 'webgl2') &&
                gpuName.length > 0 &&
                activeRendererLower.includes(gpuName.toLowerCase().slice(0, 14));
              return (
                <div
                  key={gpu.id}
                  className={`flex items-center justify-between gap-2 px-2.5 py-1.5 rounded-ui-sm text-[11px] border ${
                    isActive
                      ? 'bg-ui-control border-ui-accent-border'
                      : 'bg-ui-panel border-ui-subtle'
                  }`}
                >
                  <div className="flex items-center gap-1.5 min-w-0">
                    <span className="text-ui-primary truncate">{gpuName}</span>
                    <span className="text-[9px] px-1.5 py-0.5 rounded-ui-xs bg-ui-header border border-ui-subtle text-ui-muted font-ui-mono tabular-nums shrink-0">
                      {t(formatGpuKindLabel(gpu.kind))}
                      {gpu.vramMb > 0 ? ` · ${formatMb(gpu.vramMb)}` : ''}
                    </span>
                  </div>
                  {isActive && (
                    <span className="flex items-center gap-1 text-[10px] font-medium text-ui-success shrink-0">
                      <Check className="w-3 h-3" />
                      {t('Active')}
                    </span>
                  )}
                </div>
              );
            })}
          </div>
        )}

        {needsRestart && (
          <div className="flex items-center justify-between gap-2 p-2 rounded-ui-sm bg-ui-warning/15 border border-ui-warning/35 text-[11px]">
            <span className="text-ui-warning">
              {t('Restart Ink Studio to apply the OS-level GPU preference.')}
            </span>
            <button
              type="button"
              onClick={() => void handleRelaunchDesktop()}
              className="flex items-center gap-1 px-2.5 py-1 rounded-ui-xs bg-ui-accent text-ui-accent-contrast font-medium shrink-0 cursor-pointer hover:opacity-90"
            >
              <RotateCw className="w-3 h-3" />
              <span>{t('Restart')}</span>
            </button>
          </div>
        )}
      </section>

      {/* 4. Collapsible Advanced Settings */}
      <section className="rounded-ui-md bg-ui-header border border-ui-subtle overflow-hidden">
        <button
          type="button"
          onClick={() => setShowAdvanced((v) => !v)}
          aria-expanded={showAdvanced}
          className="w-full px-3.5 py-2.5 flex items-center justify-between text-left hover:bg-ui-control-hover/60 transition-colors cursor-pointer"
        >
          <div className="flex items-center gap-2">
            <SlidersHorizontal className="w-3.5 h-3.5 text-ui-icon-muted" />
            <div>
              <span className="text-xs font-medium text-ui-primary">{t('Advanced Settings')}</span>
              <span className="ml-2 text-[10px] text-ui-muted">
                {t('VRAM Cache, HiDPI, Undo, CPU Threads & Scratch Disk')}
              </span>
            </div>
          </div>
          {showAdvanced ? (
            <ChevronDown className="w-3.5 h-3.5 text-ui-icon-muted" />
          ) : (
            <ChevronRight className="w-3.5 h-3.5 text-ui-icon-muted" />
          )}
        </button>

        {showAdvanced && (
          <div className="px-3.5 pb-3.5 pt-2 border-t border-ui-subtle space-y-4">
            {/* GPU & Display Tuning */}
            <div className="space-y-2.5">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted font-medium">
                {t('GPU & Display')}
              </div>

              <div className="space-y-1.5">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-ui-primary">{t('GPU Tile Cache (VRAM)')}</span>
                  <span className="font-ui-mono tabular-nums text-[10px] text-ui-muted">
                    {t('{count} slices', { count: activePoolSpec.arrayLayers })}
                  </span>
                </div>
                <div className="grid grid-cols-4 gap-1.5">
                  {(['low', 'balanced', 'high', 'ultra'] as GpuTexturePoolPreset[]).map((preset) => {
                    const spec = GPU_TEXTURE_POOL_CONFIGS[preset];
                    const selected = settings.gpuTexturePoolPreset === preset;
                    return (
                      <button
                        key={preset}
                        type="button"
                        disabled={settings.renderBackend === 'canvas2d'}
                        onClick={() => patchManual({ gpuTexturePoolPreset: preset })}
                        className={`py-1 px-1.5 rounded-ui-sm text-[10px] transition-colors cursor-pointer disabled:opacity-40 border ${
                          selected
                            ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                            : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                        }`}
                      >
                        {td(spec.label)}
                      </button>
                    );
                  })}
                </div>
              </div>

              <div className="flex items-center justify-between gap-3">
                <span className="text-xs text-ui-primary">{t('Viewport Resolution (HiDPI)')}</span>
                <select
                  aria-label={t('Viewport Resolution Scaling')}
                  value={settings.viewportResolutionScale}
                  onChange={(e) =>
                    patchManual({
                      viewportResolutionScale: e.target.value as ViewportResolutionScale,
                    })
                  }
                  className="bg-ui-input text-ui-primary text-xs px-2 py-1 rounded-ui-sm border border-ui-default cursor-pointer"
                >
                  <option value="native">{t('Native Display DPI')}</option>
                  <option value="capped-2x">{t('Capped 2× (Recommended)')}</option>
                  <option value="1x">{t('Standard 1× (High FPS)')}</option>
                  <option value="0.75x">{t('Performance 0.75×')}</option>
                </select>
              </div>

              <div className="flex items-center justify-between gap-3">
                <span className="text-xs text-ui-primary">{t('Zoom Texture Filtering')}</span>
                <select
                  aria-label={t('Canvas Texture Filtering')}
                  value={settings.canvasFilteringQuality}
                  onChange={(e) =>
                    patchManual({
                      canvasFilteringQuality: e.target.value as CanvasFilteringQuality,
                    })
                  }
                  className="bg-ui-input text-ui-primary text-xs px-2 py-1 rounded-ui-sm border border-ui-default cursor-pointer"
                >
                  <option value="auto">{t('Auto (Crisp ≥200%)')}</option>
                  <option value="smooth">{t('Always Smooth')}</option>
                  <option value="pixelated">{t('Always Sharp (Nearest)')}</option>
                </select>
              </div>

              {isDesktopTauri && (
                <div className="flex items-center justify-between gap-3">
                  <span className="text-xs text-ui-primary">{t('Desktop Graphics API (ANGLE)')}</span>
                  <select
                    aria-label={t('Desktop Graphics API')}
                    value={settings.desktopGraphicsApi}
                    onChange={(e) =>
                      patchManual({ desktopGraphicsApi: e.target.value as DesktopGraphicsApi })
                    }
                    className="bg-ui-input text-ui-primary text-xs px-2 py-1 rounded-ui-sm border border-ui-default cursor-pointer"
                  >
                    <option value="auto">{t('Auto (OS Default)')}</option>
                    <option value="d3d11">Direct3D 11</option>
                    <option value="vulkan">Vulkan</option>
                    <option value="gl">OpenGL</option>
                    <option value="warp">{t('WARP (Software)')}</option>
                  </select>
                </div>
              )}

              <label className="flex items-center justify-between py-0.5 cursor-pointer">
                <span className="text-xs text-ui-primary">{t('GPU Brush Acceleration')}</span>
                <input
                  type="checkbox"
                  disabled={settings.renderBackend === 'canvas2d'}
                  checked={settings.gpuBrushAcceleration}
                  onChange={(e) => patchManual({ gpuBrushAcceleration: e.target.checked })}
                />
              </label>

              <label className="flex items-center justify-between py-0.5 cursor-pointer">
                <span className="text-xs text-ui-primary">{t('Baked Layer Stack Cache')}</span>
                <input
                  type="checkbox"
                  disabled={settings.renderBackend === 'canvas2d'}
                  checked={settings.layerStackCaching}
                  onChange={(e) => patchManual({ layerStackCaching: e.target.checked })}
                />
              </label>
            </div>

            {/* Undo & Multi-Tab Memory */}
            <div className="space-y-2.5 pt-3 border-t border-ui-subtle">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted font-medium">
                {t('Undo & Multi-Document Memory')}
              </div>

              <div className="space-y-1">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-ui-primary">{t('Max History States')}</span>
                  <span className="font-ui-mono tabular-nums text-[11px] text-ui-primary">
                    {settings.maxHistorySteps}
                  </span>
                </div>
                <div className="grid grid-cols-6 gap-1">
                  {[25, 50, 75, 100, 150, 200].map((steps) => (
                    <button
                      key={steps}
                      type="button"
                      onClick={() => patchManual({ maxHistorySteps: steps })}
                      className={`py-1 rounded-ui-sm font-ui-mono tabular-nums text-[10px] cursor-pointer border transition-colors ${
                        settings.maxHistorySteps === steps
                          ? 'bg-ui-control-active text-ui-primary font-medium border-ui-accent-border'
                          : 'bg-ui-input text-ui-secondary border-ui-subtle hover:text-ui-primary hover:bg-ui-control-hover'
                      }`}
                    >
                      {steps}
                    </button>
                  ))}
                </div>
              </div>

              <div className="space-y-1">
                <div className="flex items-center justify-between">
                  <span className="text-xs text-ui-primary">{t('In-RAM Undo Steps')}</span>
                  <span className="font-ui-mono tabular-nums text-[11px] text-ui-primary">
                    {t('{n} steps', { n: settings.undoRamSteps })}
                  </span>
                </div>
                <input
                  type="range"
                  aria-label={t('In-RAM undo steps')}
                  min={4}
                  max={50}
                  step={1}
                  value={settings.undoRamSteps}
                  onChange={(e) => patchManual({ undoRamSteps: Number(e.target.value) })}
                  className="w-full"
                />
              </div>

              <label className="flex items-center justify-between py-0.5 cursor-pointer">
                <span className="text-xs text-ui-primary">{t('Offload Inactive Document Tabs')}</span>
                <input
                  type="checkbox"
                  checked={settings.offloadInactiveTabs}
                  onChange={(e) => patchManual({ offloadInactiveTabs: e.target.checked })}
                />
              </label>

              <div className="flex items-center justify-between gap-2 pt-1">
                <span className="text-[10px] text-ui-muted">{t('Granular Cache Purge')}</span>
                <div className="flex items-center gap-1.5">
                  <button
                    type="button"
                    disabled={isPurging}
                    onClick={() => void handlePurge('tiles')}
                    className="px-2 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer disabled:opacity-50 transition-colors"
                  >
                    {t('Tiles')}
                  </button>
                  <button
                    type="button"
                    disabled={isPurging}
                    onClick={() => void handlePurge('undo')}
                    className="px-2 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer disabled:opacity-50 transition-colors"
                  >
                    {t('Undo')}
                  </button>
                  <button
                    type="button"
                    disabled={isPurging}
                    onClick={() => void handlePurge('gpu')}
                    className="px-2 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[10px] text-ui-primary cursor-pointer disabled:opacity-50 transition-colors"
                  >
                    GPU
                  </button>
                </div>
              </div>
            </div>

            {/* 3D & CPU Threading */}
            <div className="space-y-2.5 pt-3 border-t border-ui-subtle">
              <div className="text-[10px] uppercase tracking-wider text-ui-muted font-medium">
                {t('3D & CPU')}
              </div>

              <div className="flex items-center justify-between gap-3">
                <span className="text-xs text-ui-primary">{t('3D Preview Resolution')}</span>
                <div className="flex items-center gap-2">
                  <select
                    aria-label={t('3D Preview Resolution Cap')}
                    value={settings.preview3DMaxResolution}
                    onChange={(e) =>
                      patchManual({
                        preview3DMaxResolution: Number(e.target.value) as Preview3DMaxResolution,
                      })
                    }
                    className="bg-ui-input text-ui-primary text-xs px-2 py-1 rounded-ui-sm border border-ui-default font-ui-mono tabular-nums cursor-pointer"
                  >
                    <option value={1024}>1024 px</option>
                    <option value={1920}>1920 px</option>
                    <option value={2560}>2560 px</option>
                  </select>
                  <label className="flex items-center gap-1 text-[11px] text-ui-primary cursor-pointer">
                    <input
                      type="checkbox"
                      checked={settings.preview3DAntialias}
                      onChange={(e) => patchManual({ preview3DAntialias: e.target.checked })}
                    />
                    <span>AA</span>
                  </label>
                </div>
              </div>

              {isDesktopTauri && (
                <>
                  <div className="space-y-1">
                    <div className="flex items-center justify-between">
                      <span className="text-xs text-ui-primary">{t('CPU Worker Threads')}</span>
                      <span className="font-ui-mono tabular-nums text-[11px] text-ui-primary">
                        {workerThreadsValue === 0
                          ? t('Auto ({cores})', { cores: cpuCores })
                          : `${workerThreadsValue} / ${cpuCores}`}
                      </span>
                    </div>
                    <input
                      type="range"
                      aria-label={t('CPU worker threads')}
                      min={0}
                      max={cpuCores}
                      step={1}
                      value={Math.min(workerThreadsValue, cpuCores)}
                      onChange={(e) => patchManual({ cpuWorkerThreads: Number(e.target.value) })}
                      className="w-full"
                    />
                  </div>

                  <label className="flex items-center justify-between py-0.5 cursor-pointer">
                    <span className="text-xs text-ui-primary">{t('Native Rust Acceleration')}</span>
                    <input
                      type="checkbox"
                      checked={settings.useNativeRustAcceleration}
                      onChange={(e) =>
                        patchManual({ useNativeRustAcceleration: e.target.checked })
                      }
                    />
                  </label>
                </>
              )}
            </div>

            {/* Scratch Disk */}
            <div className="space-y-2 pt-3 border-t border-ui-subtle">
              <div className="flex items-center justify-between">
                <span className="text-[10px] uppercase tracking-wider text-ui-muted font-medium flex items-center gap-1.5">
                  <HardDrive className="w-3 h-3" />
                  <span>{t('Scratch Disk')}</span>
                </span>
                <span
                  className="font-ui-mono tabular-nums text-[10px] text-ui-muted truncate max-w-[260px]"
                  title={hwInfo?.scratchDiskPath ? td(hwInfo.scratchDiskPath) : undefined}
                >
                  {hwInfo?.scratchDiskPath ? td(hwInfo.scratchDiskPath) : t('System Temp')}
                  {isDesktopTauri && hwInfo && hwInfo.scratchDiskFreeMb > 0
                    ? t(' · {size} free', { size: formatMb(hwInfo.scratchDiskFreeMb) })
                    : ''}
                </span>
              </div>

              {isDesktopTauri && (
                <>
                  <div className="flex items-center gap-1.5">
                    <input
                      type="text"
                      value={scratchPathInput}
                      onChange={(e) => {
                        setScratchPathInput(e.target.value);
                        setScratchError(null);
                      }}
                      placeholder={t('Custom folder (optional, e.g. secondary SSD)')}
                      className="flex-1 bg-ui-input px-2.5 py-1 rounded-ui-sm font-ui-mono text-[11px] text-ui-primary placeholder:text-ui-muted/60 border border-ui-default"
                    />
                    <button
                      type="button"
                      disabled={isApplyingScratch}
                      onClick={() => void handleApplyScratchPath(scratchPathInput)}
                      className="px-2.5 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-default text-[11px] text-ui-primary font-medium cursor-pointer shrink-0 disabled:opacity-50 transition-colors"
                    >
                      {t('Apply')}
                    </button>
                    {settings.scratchDiskPath && (
                      <button
                        type="button"
                        disabled={isApplyingScratch}
                        onClick={() => {
                          setScratchPathInput('');
                          void handleApplyScratchPath('');
                        }}
                        className="px-2 py-1 rounded-ui-sm bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-[11px] text-ui-secondary hover:text-ui-primary cursor-pointer shrink-0 transition-colors"
                      >
                        {t('Reset')}
                      </button>
                    )}
                  </div>
                  {scratchError && <div className="text-[10px] text-ui-danger">{scratchError}</div>}

                  <div className="flex items-center justify-between gap-3">
                    <span className="text-xs text-ui-primary">{t('Scratch Compression')}</span>
                    <select
                      aria-label={t('Scratch Disk Compression')}
                      value={settings.scratchDiskCompression}
                      onChange={(e) =>
                        patchManual({
                          scratchDiskCompression: e.target.value as ScratchDiskCompression,
                        })
                      }
                      className="bg-ui-input text-ui-primary text-xs px-2 py-1 rounded-ui-sm border border-ui-default cursor-pointer"
                    >
                      <option value="lz4">{t('LZ4 Fast (Recommended)')}</option>
                      <option value="none">{t('Uncompressed')}</option>
                    </select>
                  </div>
                </>
              )}
            </div>
          </div>
        )}
      </section>
    </div>
  );
};