基于WebView2实现的Win11桌面框架,利用插件自定义
Moli
2026-05-03 5852890ac7c6925af4edd70398790d96f8b44284
v1.0
6个文件已添加
6个文件已修改
1801 ■■■■■ 已修改文件
samples/plugins/sample.audio-visualizer/demo.html 584 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/index.html 479 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/index_test.html 551 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/plugin.json 10 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
scripts/publish-to-apps.ps1 135 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Assets/1.icon.png 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Assets/2.icon.png 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Assets/Moli.Desktop - 副本.ico 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Assets/Moli.Desktop.ico 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Audio/AudioSpectrumAnalyzer.cs 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Moli.Desktop.csproj 7 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/Moli.Desktop/Tray/TrayShell.cs 33 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
samples/plugins/sample.audio-visualizer/demo.html
New file
@@ -0,0 +1,584 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <title>Moli Desktop Audio Waveform</title>
  <style>
    html,
    body {
      margin: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      background: transparent;
    }
    body {
      background:
        radial-gradient(circle at 68% 66%, rgba(0, 210, 255, 0.18), transparent 18%),
        radial-gradient(circle at 50% 66%, rgba(255, 0, 200, 0.16), transparent 32%),
        linear-gradient(90deg, rgba(0, 12, 22, 0.55), rgba(20, 0, 35, 0.55));
    }
    canvas {
      width: 100vw;
      height: 100vh;
      display: block;
    }
    #status {
      position: fixed;
      left: 10px;
      top: 8px;
      font-size: 12px;
      font-family: Consolas, monospace;
      color: rgba(255, 255, 255, .55);
      pointer-events: none;
    }
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <div id="status">connecting...</div>
  <script>
    const WS_URL = "ws://127.0.0.1:8765/ws/events";
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    const statusEl = document.getElementById("status");
    let W = 0;
    let H = 0;
    let dpr = 1;
    let sourceLevels = new Array(64).fill(0);
    let displayBars = [];
    let lastEnergy = 0;
    let beat = 0;
    const config = {
      barCount: 150,
      // å±å¹•下方 1/3 é™„è¿‘
      centerYRatio: 0.66,
      // å•边最大高度,总高度约为 2 å€
      maxHeightRatio: 0.20,
      barWidth: 4,
      gap: 6,
      radius: 3,
      smooth: 0.5,
      decay: 0.5,
      sensitivity: 1.5,
      compressionPower: 0.70,
      showStatus: true
    };
    function safeNumber(v, fallback = 0) {
      v = Number(v);
      return Number.isFinite(v) ? v : fallback;
    }
    function clamp(v, min, max) {
      v = safeNumber(v, min);
      return Math.max(min, Math.min(max, v));
    }
    function sampleLevel(levels, idx) {
      if (!Array.isArray(levels) || levels.length === 0) return 0;
      const n = levels.length;
      idx = clamp(idx, 0, n - 1);
      const i0 = Math.floor(idx);
      const i1 = Math.min(n - 1, i0 + 1);
      const f = idx - i0;
      const a = safeNumber(levels[i0], 0);
      const b = safeNumber(levels[i1], 0);
      return a * (1 - f) + b * f;
    }
    function resize() {
      dpr = window.devicePixelRatio || 1;
      W = window.innerWidth;
      H = window.innerHeight;
      canvas.width = Math.floor(W * dpr);
      canvas.height = Math.floor(H * dpr);
      canvas.style.width = W + "px";
      canvas.style.height = H + "px";
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
      displayBars = new Array(config.barCount).fill(0);
    }
    window.addEventListener("resize", resize);
    resize();
    function connect() {
      const ws = new WebSocket(WS_URL);
      ws.onopen = () => {
        statusEl.textContent = "connected";
      };
      ws.onclose = () => {
        statusEl.textContent = "disconnected, reconnecting...";
        setTimeout(connect, 1000);
      };
      ws.onerror = () => {
        statusEl.textContent = "websocket error";
      };
      ws.onmessage = (event) => {
        try {
          const msg = JSON.parse(event.data);
          if (msg.name !== "audio.spectrum") return;
          const levels = msg.payload && msg.payload.levels;
          if (!Array.isArray(levels)) return;
          sourceLevels = levels.map(v => Math.max(0, Number(v) || 0));
          if (config.showStatus) {
            const rms = Number(msg.payload.rms || 0);
            statusEl.textContent =
              `audio.spectrum | levels ${sourceLevels.length} -> ${config.barCount} | rms ${rms.toFixed(4)}`;
          } else {
            statusEl.style.display = "none";
          }
        } catch (e) { }
      };
    }
    connect();
    function clamp(v, min, max) {
      return Math.max(min, Math.min(max, v));
    }
    function lerp(a, b, t) {
      return a + (b - a) * t;
    }
    function sampleLevel(levels, idx) {
      const n = levels.length;
      if (!n) return 0;
      idx = clamp(idx, 0, n - 1);
      const i0 = Math.floor(idx);
      const i1 = Math.min(n - 1, i0 + 1);
      const f = idx - i0;
      return levels[i0] * (1 - f) + levels[i1] * f;
    }
    function smoothstep(edge0, edge1, x) {
      x = clamp((x - edge0) / (edge1 - edge0), 0, 1);
      return x * x * (3 - 2 * x);
    }
    /**
     * è§†è§‰ç›®æ ‡ï¼š
     * - å·¦ä¾§ï¼šä¸­é¢‘ + å°‘量高频,小而细碎
     * - ä¸­é—´ï¼šé«˜é¢‘,细密闪烁
     * - åå³ 2/3:低频 / ä¸­ä½Žé¢‘,大波峰
     * - æœ€å³ï¼šé«˜é¢‘尾巴,快速衰减
     *
     * è¿™ä¸æ˜¯ç‰©ç†é¢‘谱,而是接近参考图的“设计型频谱重排”。
     */
    function calcMidBar(levels, t, n, bassEnd, midEnd, highEnd) {
      const p = t / 0.35;
      const midIdx = lerp(bassEnd, midEnd, Math.pow(p, 0.9));
      const highIdx = lerp(midEnd, highEnd, Math.pow(p, 0.7));
      const mid = sampleLevel(levels, midIdx);
      const high = sampleLevel(levels, highIdx);
      const fadeIn = smoothstep(0.0, 0.42, p);
      const introFloor = 0.06 + p * 0.10;
      const mainShape = 0.18 + Math.pow(p, 0.9) * 0.48;
      return {
        v: mid * 0.72 + high * 0.28,
        shape: introFloor + mainShape * fadeIn,
        band: "mid"
      };
    }
    function calcTrebleBar(levels, t, n, bassEnd, midEnd, highEnd) {
      const p = (t - 0.35) / 0.23;
      const highIdx = lerp(midEnd, highEnd, Math.pow(p, 0.8));
      const midIdx = lerp(midEnd * 0.75, midEnd, p);
      const high = sampleLevel(levels, highIdx);
      const mid = sampleLevel(levels, midIdx);
      return {
        v: high * 0.82 + mid * 0.18,
        shape: 0.22 + Math.sin(p * Math.PI) * 0.28,
        band: "treble"
      };
    }
    function calcBassBar(levels, t, n, bassEnd, midEnd, highEnd) {
      const p = (t - 0.58) / 0.24;
      const bassIdx = lerp(0, bassEnd, Math.pow(p, 0.55));
      const midBassIdx = lerp(bassEnd, Math.floor(n * 0.32), p);
      const highIdx = lerp(midEnd, highEnd, p);
      const bass = sampleLevel(levels, bassIdx);
      const midBass = sampleLevel(levels, midBassIdx);
      const high = sampleLevel(levels, highIdx);
      const peak = Math.exp(-Math.pow((p - 0.58) / 0.36, 2));
      const enter = smoothstep(0.0, 0.38, p);
      return {
        v: bass * 0.58 + midBass * 0.24 + high * 0.18,
        shape: 0.16 + enter * (0.08 + peak * 0.72),
        band: "bass"
      };
    }
    function calcTailBar(levels, t, n, bassEnd, midEnd, highEnd) {
      const p = (t - 0.82) / 0.18;
      const highIdx = lerp(midEnd, highEnd, p);
      const bassIdx = bassEnd * 0.45;
      const midIdx = lerp(bassEnd, midEnd * 0.7, 1 - p);
      const high = sampleLevel(levels, highIdx);
      const bass = sampleLevel(levels, bassIdx);
      const mid = sampleLevel(levels, midIdx);
      return {
        v: high * 0.62 + bass * 0.16 + mid * 0.10,
        shape: Math.pow(1 - p, 1.65) * 0.38 + 0.06,
        band: "tail"
      };
    }
    function mixBar(a, b, k) {
      k = smoothstep(0, 1, k);
      // åŽŸå§‹å¹³æ»‘æ··åˆ
      const mixedV = lerp(a.v, b.v, k);
      // è¿‡æ¸¡åŒºè¡¥åº•:避免 a、b åœ¨åˆ‡æ¢æ—¶åŒæ—¶åä½Ž
      const bridge = Math.max(a.v, b.v) * 0.25;
      return {
        v: mixedV + bridge,
        shape: lerp(a.shape, b.shape, k),
        band: k < 0.5 ? a.band : b.band
      };
    }
    function applyBandGain(v, band) {
      if (band === "bass") return v * 2.15;
      if (band === "mid") return v * 1.75;
      if (band === "treble") return v * 2.35;
      if (band === "tail") return v * 1.95;
      return v;
    }
    function applyCompression(v) {
      v = Math.pow(v * config.sensitivity, config.compressionPower);
      return v / (1 + v);
    }
    function applyVisualTexture(v, band, i, shape) {
      const grain =
        0.92 +
        0.06 * Math.sin(i * 0.47) +
        0.04 * Math.sin(i * 1.13);
      const sparkle =
        band === "treble" || band === "tail"
          ? 0.92 + 0.12 * Math.sin(performance.now() * 0.018 + i * 0.9)
          : 1;
      return clamp(v * shape * grain * sparkle, 0, 1);
    }
    function getBarByPosition(levels, t, n, bassEnd, midEnd, highEnd) {
      const blend58 = 0.00;
      const blend82 = 0.035;
      if (t < 0.35) {
        return calcMidBar(levels, t, n, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 - blend58) {
        return calcTrebleBar(levels, t, n, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 + blend58) {
        const k = (t - (0.58 - blend58)) / (blend58 * 2);
        return mixBar(
          calcTrebleBar(levels, t, n, bassEnd, midEnd, highEnd),
          calcBassBar(levels, t, n, bassEnd, midEnd, highEnd),
          k
        );
      }
      if (t < 0.82 - blend82) {
        return calcBassBar(levels, t, n, bassEnd, midEnd, highEnd);
      }
      if (t < 0.82 + blend82) {
        const k = (t - (0.82 - blend82)) / (blend82 * 2);
        return mixBar(
          calcBassBar(levels, t, n, bassEnd, midEnd, highEnd),
          calcTailBar(levels, t, n, bassEnd, midEnd, highEnd),
          k
        );
      }
      return calcTailBar(levels, t, n, bassEnd, midEnd, highEnd);
    }
    function buildBars(levels, count) {
      const res = new Array(count);
      const n = levels.length || 64;
      const bassEnd = Math.floor(n * 0.16);
      const midEnd = Math.floor(n * 0.55);
      const highEnd = n - 1;
      for (let i = 0; i < count; i++) {
        const t = i / (count - 1);
        const item = getBarByPosition(
          levels,
          t,
          n,
          bassEnd,
          midEnd,
          highEnd
        );
        let v = applyBandGain(item.v, item.band);
        v = applyCompression(v);
        res[i] = applyVisualTexture(v, item.band, i, item.shape);
      }
      return res;
    }
    // function colorByPosition(t) {
    //   if (t < 0.18) return "hsl(330, 100%, 58%)";
    //   if (t < 0.35) return "hsl(95, 100%, 58%)";
    //   if (t < 0.58) return "hsl(285, 100%, 62%)";
    //   if (t < 0.72) return "hsl(140, 100%, 58%)";
    //   if (t < 0.82) return "hsl(190, 100%, 60%)";
    //   return "hsl(260, 100%, 64%)";
    // }
    // ===== è¿žç»­æ¸å˜è‰²ï¼ˆæ›¿æ¢ colorByPosition) =====
    function hslToString(h, s, l) {
      return `hsl(${h}, ${s}%, ${l}%)`;
    }
    function mixColorStop(a, b, k) {
      // ä½¿ç”¨ smoothstep,让过渡更丝滑
      k = smoothstep(0, 1, k);
      return {
        h: lerp(a.h, b.h, k),
        s: lerp(a.s, b.s, k),
        l: lerp(a.l, b.l, k)
      };
    }
    function colorByPosition(t) {
      // ðŸ‘‰ æ•´ä½“偏霓虹粉紫(接近你参考图)
      const stops = [
        { pos: 0.00, h: 330, s: 100, l: 62 }, // äº®ç²‰
        { pos: 0.35, h: 323, s: 100, l: 66 }, // ç²‰ç´«
        { pos: 0.65, h: 310, s: 100, l: 68 }, // æ´‹çº¢
        { pos: 1.00, h: 292, s: 100, l: 70 }  // ç´«
      ];
      // æ‰¾åˆ°æ‰€åœ¨åŒºé—´å¹¶æ’值
      for (let i = 0; i < stops.length - 1; i++) {
        const a = stops[i];
        const b = stops[i + 1];
        if (t >= a.pos && t <= b.pos) {
          const k = (t - a.pos) / (b.pos - a.pos);
          const c = mixColorStop(a, b, k);
          return hslToString(c.h, c.s, c.l);
        }
      }
      // fallback(理论不会走到)
      const last = stops[stops.length - 1];
      return hslToString(last.h, last.s, last.l);
    }
    function roundedBar(x, y, w, h, r) {
      const rr = Math.min(r, w / 2, h / 2);
      ctx.beginPath();
      ctx.moveTo(x + rr, y);
      ctx.lineTo(x + w - rr, y);
      ctx.quadraticCurveTo(x + w, y, x + w, y + rr);
      ctx.lineTo(x + w, y + h - rr);
      ctx.quadraticCurveTo(x + w, y + h, x + w - rr, y + h);
      ctx.lineTo(x + rr, y + h);
      ctx.quadraticCurveTo(x, y + h, x, y + h - rr);
      ctx.lineTo(x, y + rr);
      ctx.quadraticCurveTo(x, y, x + rr, y);
      ctx.closePath();
      ctx.fill();
    }
    function drawBackground(centerY) {
      const g1 = ctx.createRadialGradient(W * 0.68, centerY, 0, W * 0.68, centerY, W * 0.22);
      g1.addColorStop(0, "rgba(0, 220, 255, 0.18)");
      g1.addColorStop(0.45, "rgba(0, 120, 255, 0.08)");
      g1.addColorStop(1, "rgba(0, 0, 0, 0)");
      ctx.fillStyle = g1;
      ctx.fillRect(0, 0, W, H);
      const g2 = ctx.createRadialGradient(W * 0.50, centerY, 0, W * 0.50, centerY, W * 0.42);
      g2.addColorStop(0, "rgba(255, 0, 220, 0.12)");
      g2.addColorStop(0.55, "rgba(110, 0, 255, 0.07)");
      g2.addColorStop(1, "rgba(0, 0, 0, 0)");
      ctx.fillStyle = g2;
      ctx.fillRect(0, 0, W, H);
    }
    function bellShapeSmooth(data) {
      const n = data.length;
      if (n <= 1) return data.slice();
      const sorted = data.slice().sort((a, b) => a - b);
      const result = new Array(n);
      let leftPos = Math.floor((n - 1) / 2);
      let rightPos = leftPos + 1;
      // æœ€å¤§å€¼æ”¾ä¸­é—´ï¼Œç„¶åŽæ¬¡å¤§å€¼å·¦å³äº¤æ›¿
      for (let i = n - 1, toggle = 0; i >= 0; i--, toggle ^= 1) {
        if (toggle === 0 && leftPos >= 0) {
          result[leftPos--] = sorted[i];
        } else if (rightPos < n) {
          result[rightPos++] = sorted[i];
        } else {
          result[leftPos--] = sorted[i];
        }
      }
      return result;
    }
    function draw() {
      ctx.clearRect(0, 0, W, H);
      const centerY = H * config.centerYRatio;
      const maxHalfH = H * config.maxHeightRatio;
      drawBackground(centerY);
      let bars = buildBars(sourceLevels, config.barCount);
      // ç®€å• beat:主要给右侧低频主峰一点呼吸感
      const energy = sourceLevels.reduce((a, b) => a + b, 0);
      if (energy > lastEnergy * 1.12) {
        beat = 1;
      } else {
        beat *= 0.90;
      }
      lastEnergy = energy;
      const totalW =
        config.barCount * config.barWidth +
        (config.barCount - 1) * config.gap;
      let x = (W - totalW) / 2;
      // åŸºçº¿
      ctx.save();
      ctx.shadowBlur = 10;
      ctx.shadowColor = "rgba(255,255,255,.65)";
      ctx.fillStyle = "rgba(255,255,255,.42)";
      ctx.fillRect(0, centerY - 0.5, W, 1);
      ctx.restore();
      for (let i = 0; i < config.barCount; i++) {
        const t = i / (config.barCount - 1);
        let target = bars[i];
        // ä½Žé¢‘主峰区域额外 beat boost
        if (t > 0.58 && t < 0.82) {
          target *= 1 + beat * 0.34;
        } else if (t >= 0.35 && t < 0.58) {
          target *= 1 + beat * 0.10;
        }
        displayBars[i] = Math.max(
          target * config.smooth + displayBars[i] * (1 - config.smooth),
          displayBars[i] * config.decay
        );
        // const h = Math.max(1.2, displayBars[i] * maxHalfH);
        const color = colorByPosition(t);
        const rawH = displayBars[i] * maxHalfH;
        const h = Math.max(1.2, safeNumber(rawH, 1.2));
        if (!Number.isFinite(h)) {
          continue;
        }
        const grad = ctx.createLinearGradient(
          0,
          centerY - h,
          0,
          centerY + h
        );
        grad.addColorStop(0, "rgba(255,255,255,0.95)");
        grad.addColorStop(0.28, color);
        grad.addColorStop(0.72, color);
        grad.addColorStop(1, "rgba(0,230,255,0.85)");
        ctx.save();
        ctx.fillStyle = grad;
        ctx.shadowBlur = 11;
        ctx.shadowColor = color;
        roundedBar(x, centerY - h, config.barWidth, h * 2, config.radius);
        ctx.restore();
        x += config.barWidth + config.gap;
      }
      requestAnimationFrame(draw);
    }
    draw();
  </script>
</body>
</html>
samples/plugins/sample.audio-visualizer/index.html
@@ -1,5 +1,6 @@
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
@@ -15,180 +16,390 @@
      user-select: none;
    }
    body {
      /* background:
        radial-gradient(circle at 68% 66%, rgba(0, 210, 255, 0.18), transparent 18%),
        radial-gradient(circle at 50% 66%, rgba(255, 0, 200, 0.16), transparent 32%),
        linear-gradient(90deg, rgba(0, 12, 22, 0.45), rgba(20, 0, 35, 0.45)); */
      background: transparent;
    }
    #stage {
      position: fixed;
      inset: 0;
      width: 100vw;
      height: 100vh;
      position: relative;
      box-sizing: border-box;
      overflow: hidden;
      background: transparent;
      --base-y: 58%;
      --glow: rgba(255, 47, 179, 0.42);
      --cool: #29d8ff;
      --hot: #ff2fb3;
      --accent: #f8fbff;
    }
    #stage::before {
      content: "";
    #visualizer {
      position: absolute;
      left: 0;
      right: 0;
      top: var(--base-y);
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.72), transparent);
      box-shadow:
        0 0 8px rgba(255, 255, 255, 0.7),
        0 0 22px var(--glow);
      opacity: 0.86;
    }
    .bars {
      position: absolute;
      inset: 0 10px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 2px;
    }
    .bar {
      --level: 0.16;
      --bar-height: 7%;
      --bar-top: 51%;
      --bar-opacity: 0.43;
      --reflection-height: 4vh;
      --reflection-opacity: 0.06;
      position: relative;
      flex: 1 1 auto;
      min-width: 1px;
      max-width: 4px;
      height: var(--bar-height);
      margin-top: var(--bar-top);
      border-radius: 999px;
      transform-origin: bottom center;
      background:
        linear-gradient(180deg, var(--accent), var(--hot) 36%, var(--cool));
      box-shadow:
        0 0 5px rgba(255, 255, 255, 0.72),
        0 0 12px var(--glow);
      opacity: var(--bar-opacity);
      transition:
        height 64ms linear,
        margin-top 64ms linear,
        opacity 64ms linear;
    }
    .bar::after {
      content: "";
      position: absolute;
      width: inherit;
      min-width: inherit;
      max-width: inherit;
      height: var(--reflection-height);
      transform: translateY(100%) scaleY(0.72);
      transform-origin: top center;
      border-radius: inherit;
      background: linear-gradient(180deg, rgba(255, 47, 179, 0.26), rgba(41, 216, 255, 0.02));
      filter: blur(1px);
      opacity: var(--reflection-opacity);
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
  </style>
</head>
<body>
  <main id="stage" aria-hidden="true">
    <div id="bars" class="bars"></div>
    <canvas id="visualizer"></canvas>
  </main>
  <script>
    const stage = document.getElementById("stage");
    const barRoot = document.getElementById("bars");
    const DISPLAY_BAR_COUNT = 256;
    const FALLBACK_LEVEL_COUNT = 128;
    const canvas = document.getElementById("visualizer");
    const ctx = canvas.getContext("2d", { alpha: true });
    const settings = {
      barCount: 192,
      primaryColor: "#ff2fb3",
      secondaryColor: "#29d8ff",
      accentColor: "#f8fbff",
      sensitivity: 1.42
      sensitivity: 5.5,
      centerYRatio: 0.66,
      maxHeightRatio: 3.5,
      smooth: 0.3,
      decay: 0.5,
      compressionPower: 0.7
    };
    let hostLevels = null;
    let width = 1;
    let height = 1;
    let ratio = 1;
    let sourceLevels = new Array(FALLBACK_LEVEL_COUNT).fill(0);
    let displayLevels = new Array(DISPLAY_BAR_COUNT).fill(0.01);
    let smoothedLevels = new Array(DISPLAY_BAR_COUNT).fill(0.01);
    let lastHostSampleAt = 0;
    let fallbackPhase = 0;
    let bars = [];
    let lastEnergy = 0;
    let beat = 0;
    let phase = 0;
    function safeNumber(value, fallback = 0) {
      const number = Number(value);
      return Number.isFinite(number) ? number : fallback;
    }
    function clamp(value, min, max) {
      return Math.max(min, Math.min(max, safeNumber(value, min)));
    }
    function lerp(a, b, t) {
      return a + (b - a) * t;
    }
    function smoothstep(edge0, edge1, x) {
      const span = edge1 - edge0 || 1;
      x = clamp((x - edge0) / span, 0, 1);
      return x * x * (3 - 2 * x);
    }
    function resize() {
      ratio = window.devicePixelRatio || 1;
      width = Math.max(1, window.innerWidth);
      height = Math.max(1, window.innerHeight);
      canvas.width = Math.floor(width * ratio);
      canvas.height = Math.floor(height * ratio);
      canvas.style.width = `${width}px`;
      canvas.style.height = `${height}px`;
      ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
    }
    function applyConfig(config) {
      Object.assign(settings, config || {});
      stage.style.setProperty("--hot", settings.primaryColor);
      stage.style.setProperty("--cool", settings.secondaryColor);
      stage.style.setProperty("--accent", settings.accentColor);
      stage.style.setProperty("--glow", `${hexToRgb(settings.primaryColor, "255, 47, 179")}, 0.42)`.replace(/^/, "rgba("));
      const count = Math.max(96, Math.min(320, Number(settings.barCount) || 192));
      if (bars.length === count) {
      settings.sensitivity = clamp(settings.sensitivity, 0.2, 6);
      settings.centerYRatio = clamp(settings.centerYRatio, 0.2, 0.9);
      settings.maxHeightRatio = clamp(settings.maxHeightRatio, 0.06, 0.48);
    }
    async function loadHostConfig() {
      if (!window.moliDesktop?.getConfig) {
        return;
      }
      barRoot.textContent = "";
      bars = Array.from({ length: count }, () => {
        const node = document.createElement("i");
        node.className = "bar";
        barRoot.appendChild(node);
        return node;
      try {
        applyConfig(await window.moliDesktop.getConfig());
        await window.moliDesktop.notify?.({
          level: "info",
          message: "Audio visualizer loaded through moliDesktop bridge."
        });
      } catch {
        // The visualizer should keep rendering even if a host bridge call fails.
      }
    }
    function acceptLevels(levels) {
      if (!Array.isArray(levels) || levels.length === 0) {
        return;
      }
      sourceLevels = levels.map(value => clamp(value, 0, 1));
      displayLevels = buildBars(sourceLevels, DISPLAY_BAR_COUNT);
      lastHostSampleAt = performance.now();
    }
    function sampleLevel(levels, index) {
      if (!Array.isArray(levels) || levels.length === 0) {
        return 0;
      }
      const last = levels.length - 1;
      const safeIndex = clamp(index, 0, last);
      const i0 = Math.floor(safeIndex);
      const i1 = Math.min(last, i0 + 1);
      const t = safeIndex - i0;
      return lerp(safeNumber(levels[i0]), safeNumber(levels[i1]), t);
    }
    function calcMidBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = t / 0.35;
      const mid = sampleLevel(levels, lerp(bassEnd, midEnd, Math.pow(p, 0.9)));
      const high = sampleLevel(levels, lerp(midEnd, highEnd, Math.pow(p, 0.7)));
      return {
        value: mid * 0.72 + high * 0.28,
        shape: 0.06 + p * 0.1 + (0.18 + Math.pow(p, 0.9) * 0.48) * smoothstep(0, 0.42, p),
        band: "mid"
      };
    }
    function calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.35) / 0.23;
      const high = sampleLevel(levels, lerp(midEnd, highEnd, Math.pow(p, 0.8)));
      const mid = sampleLevel(levels, lerp(midEnd * 0.75, midEnd, p));
      return {
        value: high * 0.82 + mid * 0.18,
        shape: 0.22 + Math.sin(p * Math.PI) * 0.28,
        band: "treble"
      };
    }
    function calcBassBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.58) / 0.24;
      const bass = sampleLevel(levels, lerp(0, bassEnd, Math.pow(p, 0.55)));
      const midBass = sampleLevel(levels, lerp(bassEnd, Math.floor(count * 0.32), p));
      const high = sampleLevel(levels, lerp(midEnd, highEnd, p));
      const peak = Math.exp(-Math.pow((p - 0.58) / 0.36, 2));
      return {
        value: bass * 0.58 + midBass * 0.24 + high * 0.18,
        shape: 0.16 + smoothstep(0, 0.38, p) * (0.08 + peak * 0.72),
        band: "bass"
      };
    }
    function calcTailBar(levels, t, count, bassEnd, midEnd, highEnd) {
      const p = (t - 0.82) / 0.18;
      const high = sampleLevel(levels, lerp(midEnd, highEnd, p));
      const bass = sampleLevel(levels, bassEnd * 0.45);
      const mid = sampleLevel(levels, lerp(bassEnd, midEnd * 0.7, 1 - p));
      return {
        value: high * 0.62 + bass * 0.16 + mid * 0.1,
        shape: Math.pow(1 - p, 1.65) * 0.38 + 0.06,
        band: "tail"
      };
    }
    function mixBar(a, b, k) {
      const ratio = smoothstep(0, 1, k);
      return {
        value: lerp(a.value, b.value, ratio),
        shape: lerp(a.shape, b.shape, ratio),
        band: ratio < 0.5 ? a.band : b.band
      };
    }
    function getBarByPosition(levels, t, count, bassEnd, midEnd, highEnd) {
      const blend58 = 0.07;
      const blend82 = 0.035;
      if (t < 0.35) {
        return calcMidBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 - blend58) {
        return calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.58 + blend58) {
        const k = (t - (0.58 - blend58)) / (blend58 * 2);
        return mixBar(
          calcTrebleBar(levels, t, count, bassEnd, midEnd, highEnd),
          calcBassBar(levels, t, count, bassEnd, midEnd, highEnd),
          k);
      }
      if (t < 0.82 - blend82) {
        return calcBassBar(levels, t, count, bassEnd, midEnd, highEnd);
      }
      if (t < 0.82 + blend82) {
        const k = (t - (0.82 - blend82)) / (blend82 * 2);
        return mixBar(
          calcBassBar(levels, t, count, bassEnd, midEnd, highEnd),
          calcTailBar(levels, t, count, bassEnd, midEnd, highEnd),
          k);
      }
      return calcTailBar(levels, t, count, bassEnd, midEnd, highEnd);
    }
    function applyBandGain(value, band) {
      if (band === "bass") return value * 2.15;
      if (band === "mid") return value * 1.75;
      if (band === "treble") return value * 2.35;
      if (band === "tail") return value * 1.95;
      return value;
    }
    function applyCompression(value) {
      const compressed = Math.pow(value * settings.sensitivity, settings.compressionPower);
      return compressed / (1 + compressed);
    }
    function buildBars(levels, count) {
      const inputCount = levels.length || FALLBACK_LEVEL_COUNT;
      const bassEnd = Math.floor(inputCount * 0.16);
      const midEnd = Math.floor(inputCount * 0.55);
      const highEnd = inputCount - 1;
      return Array.from({ length: count }, (_, index) => {
        const t = index / Math.max(1, count - 1);
        const item = getBarByPosition(levels, t, inputCount, bassEnd, midEnd, highEnd);
        let value = applyCompression(applyBandGain(item.value, item.band));
        const grain = 0.92 + 0.06 * Math.sin(index * 0.47) + 0.04 * Math.sin(index * 1.13);
        const sparkle = item.band === "treble" || item.band === "tail"
          ? 0.92 + 0.12 * Math.sin(performance.now() * 0.018 + index * 0.9)
          : 1;
        return clamp(value * item.shape * grain * sparkle, 0.01, 1);
      });
    }
    function sample(index) {
      if (hostLevels && performance.now() - lastHostSampleAt < 420) {
        const bin = Math.min(hostLevels.length - 1, Math.floor(index / Math.max(1, bars.length) * hostLevels.length));
        const value = Number(hostLevels[bin]) || 0;
        const neighbor = (Number(hostLevels[Math.max(0, bin - 1)]) || 0) * 0.16
          + (Number(hostLevels[Math.min(hostLevels.length - 1, bin + 1)]) || 0) * 0.16;
        return Math.min(1, Math.pow(value, 0.72) * settings.sensitivity + neighbor);
    function buildFallbackLevels() {
      phase += 0.018;
      const levels = new Array(FALLBACK_LEVEL_COUNT);
      for (let index = 0; index < levels.length; index++) {
        const t = index / Math.max(1, levels.length - 1);
        const bass = Math.exp(-Math.pow((t - 0.12) / 0.12, 2)) * (0.35 + Math.sin(phase * 1.7) * 0.25);
        const mid = Math.exp(-Math.pow((t - 0.48) / 0.18, 2)) * (0.22 + Math.sin(phase * 2.8 + index * 0.08) * 0.16);
        const high = Math.exp(-Math.pow((t - 0.78) / 0.22, 2)) * (0.16 + Math.sin(phase * 5.2 + index * 0.3) * 0.12);
        levels[index] = clamp(0.02 + bass + mid + high, 0, 1);
      }
      return levels;
      }
      fallbackPhase += 0.0025;
      const main = Math.sin(index * 0.18 + fallbackPhase * 54) * 0.5 + 0.5;
      const ripple = Math.sin(index * 0.047 - fallbackPhase * 22) * 0.5 + 0.5;
      const burst = Math.pow(Math.sin(index * 0.022 + fallbackPhase * 13) * 0.5 + 0.5, 7);
      return 0.08 + main * 0.18 + ripple * 0.12 + burst * 0.58;
    function colorByPosition(t) {
      // const hue = lerp(330, 292, smoothstep(0, 1, t));
      // return `hsl(${hue}, 100%, ${lerp(62, 70, t)}%)`;
      const hue = lerp(330, 292, smoothstep(0, 1, t));
      return `hsla(${hue}, 100%, ${lerp(62, 70, t)}%, 0.35)`;
    }
    function roundedBar(x, y, barWidth, barHeight, radius) {
      const safeRadius = Math.min(radius, barWidth / 2, barHeight / 2);
      ctx.beginPath();
      ctx.moveTo(x + safeRadius, y);
      ctx.lineTo(x + barWidth - safeRadius, y);
      ctx.quadraticCurveTo(x + barWidth, y, x + barWidth, y + safeRadius);
      ctx.lineTo(x + barWidth, y + barHeight - safeRadius);
      ctx.quadraticCurveTo(x + barWidth, y + barHeight, x + barWidth - safeRadius, y + barHeight);
      ctx.lineTo(x + safeRadius, y + barHeight);
      ctx.quadraticCurveTo(x, y + barHeight, x, y + barHeight - safeRadius);
      ctx.lineTo(x, y + safeRadius);
      ctx.quadraticCurveTo(x, y, x + safeRadius, y);
      ctx.closePath();
    }
    function drawBackground(centerY) {
      // const cyan = ctx.createRadialGradient(width * 0.68, centerY, 0, width * 0.68, centerY, width * 0.22);
      // cyan.addColorStop(0, "rgba(0, 220, 255, 0.18)");
      // cyan.addColorStop(0.45, "rgba(0, 120, 255, 0.08)");
      // cyan.addColorStop(1, "rgba(0, 0, 0, 0)");
      // ctx.fillStyle = cyan;
      // ctx.fillRect(0, 0, width, height);
      // const magenta = ctx.createRadialGradient(width * 0.5, centerY, 0, width * 0.5, centerY, width * 0.42);
      // magenta.addColorStop(0, "rgba(255, 0, 220, 0.12)");
      // magenta.addColorStop(0.55, "rgba(110, 0, 255, 0.07)");
      // magenta.addColorStop(1, "rgba(0, 0, 0, 0)");
      // ctx.fillStyle = magenta;
      // ctx.fillRect(0, 0, width, height);
    }
    function draw() {
      bars.forEach((bar, index) => {
        const centerBias = Math.sin((index / Math.max(1, bars.length - 1)) * Math.PI);
        const value = Math.min(1, sample(index) * (0.72 + centerBias * 0.36));
        const height = value * 44;
        const top = Math.max(0, 58 - height);
        bar.style.setProperty("--level", value.toFixed(3));
        bar.style.setProperty("--bar-height", `${height.toFixed(2)}%`);
        bar.style.setProperty("--bar-top", `${top.toFixed(2)}%`);
        bar.style.setProperty("--bar-opacity", (0.32 + value * 0.68).toFixed(3));
        bar.style.setProperty("--reflection-height", `${(value * 26).toFixed(2)}vh`);
        bar.style.setProperty("--reflection-opacity", (value * 0.36).toFixed(3));
      });
      resize();
      if (performance.now() - lastHostSampleAt > 900) {
        acceptLevels(buildFallbackLevels());
      }
      ctx.clearRect(0, 0, width, height);
      const centerY = height * settings.centerYRatio;
      // const maxHalfHeight = height * settings.maxHeightRatio;
      const maxHalfHeight = height / 2;
      drawBackground(centerY);
      const energy = sourceLevels.reduce((sum, value) => sum + value, 0);
      beat = energy > lastEnergy * 1.12 ? 1 : beat * 0.9;
      lastEnergy = energy;
      const SILENCE_THRESHOLD = 0.001;
      const isSilent = energy < SILENCE_THRESHOLD;
      const line = ctx.createLinearGradient(0, 0, width, 0);
      line.addColorStop(0, "rgba(255,255,255,0)");
      line.addColorStop(0.5, "rgba(255,255,255,0.72)");
      line.addColorStop(1, "rgba(255,255,255,0)");
      ctx.save();
      ctx.fillStyle = line;
      ctx.shadowBlur = 10;
      ctx.shadowColor = "rgba(255,255,255,0.65)";
      ctx.fillRect(0, centerY - 0.5, width, 1);
      ctx.restore();
      const gap = width < 900 ? 2 : 3;
      const barWidth = Math.max(1.2, Math.min(5, (width - gap * (DISPLAY_BAR_COUNT - 1)) / DISPLAY_BAR_COUNT));
      const totalWidth = DISPLAY_BAR_COUNT * barWidth + (DISPLAY_BAR_COUNT - 1) * gap;
      let x = (width - totalWidth) / 2;
      if (isSilent) {
        requestAnimationFrame(draw);
        return;
      }
      for (let index = 0; index < DISPLAY_BAR_COUNT; index++) {
        const t = index / Math.max(1, DISPLAY_BAR_COUNT - 1);
        const target = displayLevels[index] * (t > 0.58 && t < 0.82 ? 1 + beat * 0.34 : t >= 0.35 && t < 0.58 ? 1 + beat * 0.1 : 1);
        smoothedLevels[index] = Math.max(
          target * settings.smooth + smoothedLevels[index] * (1 - settings.smooth),
          smoothedLevels[index] * settings.decay);
        const value = clamp(smoothedLevels[index], 0.01, 1);
        const barHeight = Math.max(1.2, value * maxHalfHeight);
        const color = colorByPosition(t);
        const gradient = ctx.createLinearGradient(0, centerY - barHeight, 0, centerY + barHeight);
        // gradient.addColorStop(0, "rgba(255,255,255,0.95)");
        // gradient.addColorStop(0.28, color);
        // gradient.addColorStop(0.72, color);
        // gradient.addColorStop(1, "rgba(0,230,255,0.85)");
        gradient.addColorStop(0, "rgba(255,255,255,0.35)");
        gradient.addColorStop(0.28, color);
        gradient.addColorStop(0.72, color);
        gradient.addColorStop(1, "rgba(0,230,255,0.35)");
        ctx.save();
        ctx.fillStyle = gradient;
        ctx.shadowBlur = 8;
        ctx.shadowColor = color;
        roundedBar(x, centerY - barHeight, barWidth, barHeight * 2, Math.min(3, barWidth / 2));
        ctx.fill();
        ctx.restore();
        x += barWidth + gap;
      }
      requestAnimationFrame(draw);
    }
    function hexToRgb(hex, fallback) {
      const match = String(hex || "").trim().match(/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i);
      if (!match) {
        return fallback;
      }
      return `${parseInt(match[1], 16)}, ${parseInt(match[2], 16)}, ${parseInt(match[3], 16)}`;
    }
    window.addEventListener("moli:widget-loaded", async () => {
      if (window.moliDesktop?.getConfig) {
        applyConfig(await window.moliDesktop.getConfig());
      }
    });
    window.addEventListener("moli:audio-spectrum", event => {
      const levels = event.detail?.levels;
      if (Array.isArray(levels) && levels.length > 0) {
        hostLevels = levels;
        lastHostSampleAt = performance.now();
      }
    });
    window.addEventListener("resize", resize);
    window.addEventListener("moli:widget-loaded", loadHostConfig);
    window.addEventListener("moli:config-changed", event => applyConfig(event.detail));
    window.addEventListener("moli:audio-spectrum", event => acceptLevels(event.detail?.levels || event.detail?.Levels));
    applyConfig();
    loadHostConfig();
    resize();
    draw();
  </script>
</body>
</html>
samples/plugins/sample.audio-visualizer/index_test.html
New file
@@ -0,0 +1,551 @@
<!doctype html>
<html lang="zh-CN">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Audio Visualizer WS Test</title>
  <style>
    :root {
      color-scheme: dark;
      --hot: #ff2fb3;
      --cool: #29d8ff;
      --accent: #f8fbff;
      --panel: rgba(9, 12, 18, 0.72);
      --line: rgba(255, 255, 255, 0.14);
      --text: #edf4ff;
      --muted: #8ea2b8;
      --ok: #42f5b0;
      --warn: #ffd166;
      --bad: #ff6b6b;
    }
    html,
    body {
      width: 100%;
      height: 100%;
      margin: 0;
      overflow: hidden;
      background: #05070b;
      color: var(--text);
      font-family: "Segoe UI", Arial, sans-serif;
    }
    body {
      display: grid;
      grid-template-rows: auto 1fr;
    }
    .toolbar {
      display: grid;
      grid-template-columns: minmax(220px, 1fr) auto auto;
      gap: 10px;
      align-items: center;
      padding: 10px 12px;
      background: var(--panel);
      border-bottom: 1px solid var(--line);
      box-sizing: border-box;
    }
    .url {
      min-width: 0;
      height: 32px;
      padding: 0 10px;
      border: 1px solid var(--line);
      border-radius: 6px;
      box-sizing: border-box;
      background: rgba(255, 255, 255, 0.06);
      color: var(--text);
      font: inherit;
    }
    .button {
      height: 32px;
      padding: 0 12px;
      border: 1px solid rgba(41, 216, 255, 0.45);
      border-radius: 6px;
      background: rgba(41, 216, 255, 0.14);
      color: var(--text);
      cursor: pointer;
      font: inherit;
    }
    .button:hover {
      background: rgba(41, 216, 255, 0.24);
    }
    .status {
      display: flex;
      align-items: center;
      gap: 8px;
      min-width: 132px;
      color: var(--muted);
      font-size: 13px;
      white-space: nowrap;
    }
    .dot {
      width: 9px;
      height: 9px;
      border-radius: 50%;
      background: var(--warn);
      box-shadow: 0 0 12px currentColor;
    }
    .status[data-state="open"] {
      color: var(--ok);
    }
    .status[data-state="closed"],
    .status[data-state="error"] {
      color: var(--bad);
    }
    .status[data-state="open"] .dot {
      background: var(--ok);
    }
    .status[data-state="closed"] .dot,
    .status[data-state="error"] .dot {
      background: var(--bad);
    }
    #stage {
      position: relative;
      width: 100vw;
      height: 100%;
      min-height: 0;
      overflow: hidden;
      background:
        linear-gradient(180deg, rgba(41, 216, 255, 0.08), transparent 28%),
        radial-gradient(circle at 50% 58%, rgba(255, 47, 179, 0.18), transparent 34%),
        #05070b;
      --base-y: 60%;
    }
    #stage::before {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      top: var(--base-y);
      height: 1px;
      background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.72), transparent);
      box-shadow: 0 0 8px rgba(255, 255, 255, 0.68), 0 0 22px rgba(255, 47, 179, 0.42);
      opacity: 0.86;
    }
    .bars {
      position: absolute;
      inset: 0 14px;
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      gap: 2px;
    }
    .visualizer {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
    .bar {
      --bar-height: 1%;
      --bar-top: 59%;
      --bar-opacity: 0.24;
      --reflection-height: 1vh;
      --reflection-opacity: 0.04;
      position: relative;
      flex: 1 1 auto;
      min-width: 2px;
      max-width: 7px;
      height: var(--bar-height);
      margin-top: var(--bar-top);
      border-radius: 999px;
      background: linear-gradient(180deg, var(--accent), var(--hot) 36%, var(--cool));
      box-shadow: 0 0 5px rgba(255, 255, 255, 0.72), 0 0 13px rgba(255, 47, 179, 0.46);
      opacity: var(--bar-opacity);
      transition: height 58ms linear, margin-top 58ms linear, opacity 58ms linear;
    }
    .bar::after {
      content: "";
      position: absolute;
      width: inherit;
      min-width: inherit;
      max-width: inherit;
      height: var(--reflection-height);
      transform: translateY(100%) scaleY(0.72);
      transform-origin: top center;
      border-radius: inherit;
      background: linear-gradient(180deg, rgba(255, 47, 179, 0.24), rgba(41, 216, 255, 0.02));
      filter: blur(1px);
      opacity: var(--reflection-opacity);
    }
    .metrics {
      position: absolute;
      left: 12px;
      bottom: 12px;
      width: min(680px, calc(100vw - 24px));
      display: grid;
      grid-template-columns: repeat(4, minmax(0, 1fr));
      gap: 8px;
      padding: 10px;
      border: 1px solid var(--line);
      border-radius: 8px;
      background: rgba(9, 12, 18, 0.72);
      box-sizing: border-box;
      backdrop-filter: blur(10px);
    }
    .metric {
      min-width: 0;
    }
    .label {
      display: block;
      color: var(--muted);
      font-size: 11px;
      line-height: 1.4;
    }
    .value {
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 13px;
      line-height: 1.5;
    }
    .raw {
      position: absolute;
      right: 12px;
      bottom: 12px;
      width: min(460px, calc(100vw - 24px));
      max-height: 136px;
      margin: 0;
      padding: 10px;
      overflow: auto;
      border: 1px solid var(--line);
      border-radius: 8px;
      background: rgba(9, 12, 18, 0.72);
      color: #b6c7dc;
      box-sizing: border-box;
      font: 12px/1.45 Consolas, "Cascadia Mono", monospace;
      backdrop-filter: blur(10px);
    }
    @media (max-width: 860px) {
      .toolbar {
        grid-template-columns: 1fr auto;
      }
      .status {
        grid-column: 1 / -1;
      }
      .metrics {
        grid-template-columns: repeat(2, minmax(0, 1fr));
      }
      .raw {
        display: none;
      }
    }
  </style>
</head>
<body>
  <header class="toolbar">
    <input id="wsUrl" class="url" value="ws://127.0.0.1:8765/ws/events" aria-label="WebSocket URL">
    <button id="connect" class="button" type="button">Connect</button>
    <div id="status" class="status" data-state="closed">
      <span class="dot"></span>
      <span id="statusText">未连接</span>
    </div>
  </header>
  <main id="stage">
    <canvas id="visualizer" class="visualizer"></canvas>
    <div id="bars" class="bars"></div>
    <section class="metrics" aria-label="WebSocket audio metrics">
      <div class="metric">
        <span class="label">EVENT</span>
        <span id="eventName" class="value">-</span>
      </div>
      <div class="metric">
        <span class="label">FRAMES</span>
        <span id="frameCount" class="value">0</span>
      </div>
      <div class="metric">
        <span class="label">RMS</span>
        <span id="rmsValue" class="value">-</span>
      </div>
      <div class="metric">
        <span class="label">LEVELS</span>
        <span id="levelsCount" class="value">-</span>
      </div>
    </section>
    <pre id="raw" class="raw">等待 ws://127.0.0.1:8765/ws/events æ•°æ®...</pre>
  </main>
  <script>
    const barCount = 192;
    const reconnectDelayMs = 1200;
    const compressionPower = 0.52;
    const smoothingAttack = 0.48;
    const smoothingRelease = 0.18;
    const gaussianSigma = 0.42;
    const canvas = document.getElementById("visualizer");
    const context = canvas.getContext("2d");
    const barsRoot = document.getElementById("bars");
    const wsUrlInput = document.getElementById("wsUrl");
    const connectButton = document.getElementById("connect");
    const statusNode = document.getElementById("status");
    const statusText = document.getElementById("statusText");
    const eventNameNode = document.getElementById("eventName");
    const frameCountNode = document.getElementById("frameCount");
    const rmsValueNode = document.getElementById("rmsValue");
    const levelsCountNode = document.getElementById("levelsCount");
    const rawNode = document.getElementById("raw");
    const bars = Array.from({ length: barCount }, () => {
      const node = document.createElement("i");
      node.className = "bar";
      barsRoot.appendChild(node);
      return node;
    });
    let socket = null;
    let reconnectTimer = 0;
    let manualClose = false;
    let rawLevels = new Array(64).fill(0);
    let visualLevels = new Array(barCount).fill(0.01);
    let smoothedLevels = new Array(barCount).fill(0.01);
    let frames = 0;
    function resizeCanvas() {
      const rect = canvas.getBoundingClientRect();
      const ratio = window.devicePixelRatio || 1;
      const width = Math.max(1, Math.floor(rect.width * ratio));
      const height = Math.max(1, Math.floor(rect.height * ratio));
      if (canvas.width !== width || canvas.height !== height) {
        canvas.width = width;
        canvas.height = height;
      }
      context.setTransform(ratio, 0, 0, ratio, 0, 0);
    }
    function setStatus(state, text) {
      statusNode.dataset.state = state;
      statusText.textContent = text;
    }
    function connect() {
      manualClose = false;
      clearTimeout(reconnectTimer);
      if (socket) {
        socket.close();
      }
      setStatus("connecting", "连接中");
      socket = new WebSocket(wsUrlInput.value.trim() || "ws://127.0.0.1:8765/ws/events");
      socket.addEventListener("open", () => setStatus("open", "已连接"));
      socket.addEventListener("message", event => handleMessage(event.data));
      socket.addEventListener("error", () => setStatus("error", "连接错误"));
      socket.addEventListener("close", () => {
        setStatus("closed", manualClose ? "已断开" : "已断开,重连中");
        if (!manualClose) {
          reconnectTimer = window.setTimeout(connect, reconnectDelayMs);
        }
      });
    }
    function disconnect() {
      manualClose = true;
      clearTimeout(reconnectTimer);
      if (socket) {
        socket.close();
        socket = null;
      }
      setStatus("closed", "已断开");
    }
    function handleMessage(text) {
      let message;
      try {
        message = JSON.parse(text);
      } catch {
        rawNode.textContent = text;
        return;
      }
      eventNameNode.textContent = message.name || "-";
      rawNode.textContent = JSON.stringify(message, null, 2).slice(0, 1600);
      if (message.name !== "audio.spectrum") {
        return;
      }
      const payload = message.payload || {};
      const nextLevels = payload.levels || payload.Levels;
      if (!Array.isArray(nextLevels) || nextLevels.length === 0) {
        return;
      }
      rawLevels = nextLevels.map(value => Math.max(0, Math.min(1, Number(value) || 0)));
      visualLevels = processSpectrum(rawLevels);
      const peak = Math.max(...rawLevels);
      frames += 1;
      frameCountNode.textContent = String(frames);
      levelsCountNode.textContent = `${rawLevels.length} -> ${visualLevels.length} / peak ${peak.toFixed(3)}`;
      rmsValueNode.textContent = Number(payload.rms ?? payload.Rms ?? 0).toFixed(4);
    }
    function processSpectrum(input) {
      const binned = logBin(input, barCount);
      const peak = Math.max(...binned);
      const gain = peak > 0 ? Math.min(18, Math.max(2, 0.86 / peak)) : 1;
      return binned.map((value, index) => {
        const compressed = Math.pow(Math.min(1, value * gain), compressionPower);
        return Math.max(0.01, Math.min(1, compressed * gaussianEnvelope(index, binned.length)));
      });
    }
    function logBin(input, outputCount) {
      if (input.length === 0) {
        return new Array(outputCount).fill(0);
      }
      const last = input.length - 1;
      const logMax = Math.log(input.length);
      return Array.from({ length: outputCount }, (_, index) => {
        const start = Math.max(0, Math.floor(Math.exp(logMax * (index / outputCount)) - 1));
        const end = Math.min(last, Math.ceil(Math.exp(logMax * ((index + 1) / outputCount)) - 1));
        let sum = 0;
        let weight = 0;
        for (let bin = start; bin <= end; bin++) {
          const localWeight = 1 + (bin / Math.max(1, last)) * 0.35;
          sum += (input[bin] || 0) * localWeight;
          weight += localWeight;
        }
        return weight > 0 ? sum / weight : 0;
      });
    }
    function gaussianEnvelope(index, count) {
      const x = count > 1 ? (index / (count - 1)) * 2 - 1 : 0;
      const gaussian = Math.exp(-(x * x) / (2 * gaussianSigma * gaussianSigma));
      return 0.28 + gaussian * 0.82;
    }
    function sample(index) {
      const target = visualLevels[index] || 0.01;
      const current = smoothedLevels[index] || 0.01;
      const rate = target > current ? smoothingAttack : smoothingRelease;
      const value = current + (target - current) * rate;
      smoothedLevels[index] = value;
      return Math.max(0.01, Math.min(1, value));
    }
    function draw() {
      resizeCanvas();
      const frameLevels = visualLevels.map((_, index) => sample(index));
      drawCanvas(frameLevels);
      bars.forEach((bar, index) => {
        const centerBias = Math.sin((index / Math.max(1, bars.length - 1)) * Math.PI);
        const value = Math.min(1, frameLevels[index] * (0.72 + centerBias * 0.36));
        const height = value * 46;
        const top = Math.max(0, 60 - height);
        bar.style.setProperty("--bar-height", `${height.toFixed(2)}%`);
        bar.style.setProperty("--bar-top", `${top.toFixed(2)}%`);
        bar.style.setProperty("--bar-opacity", (0.24 + value * 0.76).toFixed(3));
        bar.style.setProperty("--reflection-height", `${(value * 26).toFixed(2)}vh`);
        bar.style.setProperty("--reflection-opacity", (value * 0.34).toFixed(3));
      });
      requestAnimationFrame(draw);
    }
    function drawCanvas(frameLevels) {
      const width = canvas.clientWidth;
      const height = canvas.clientHeight;
      const baseY = height * 0.6;
      context.clearRect(0, 0, width, height);
      const lineGradient = context.createLinearGradient(0, 0, width, 0);
      lineGradient.addColorStop(0, "rgba(255,255,255,0)");
      lineGradient.addColorStop(0.5, "rgba(255,255,255,0.72)");
      lineGradient.addColorStop(1, "rgba(255,255,255,0)");
      context.fillStyle = lineGradient;
      context.shadowBlur = 18;
      context.shadowColor = "rgba(255, 47, 179, 0.55)";
      context.fillRect(0, baseY, width, 1);
      context.shadowBlur = 0;
      const gap = 2;
      const barWidth = Math.max(2, Math.min(7, (width - gap * (barCount - 1)) / barCount));
      for (let index = 0; index < barCount; index++) {
        const centerBias = Math.sin((index / Math.max(1, barCount - 1)) * Math.PI);
        const value = Math.min(1, frameLevels[index] * (0.72 + centerBias * 0.36));
        const barHeight = Math.max(2, value * height * 0.48);
        const x = index * (barWidth + gap);
        const y = baseY - barHeight;
        const gradient = context.createLinearGradient(0, y, 0, baseY);
        gradient.addColorStop(0, "#f8fbff");
        gradient.addColorStop(0.36, "#ff2fb3");
        gradient.addColorStop(1, "#29d8ff");
        context.globalAlpha = 0.28 + value * 0.72;
        context.fillStyle = gradient;
        context.shadowBlur = 13;
        context.shadowColor = "rgba(255, 47, 179, 0.5)";
        roundRect(context, x, y, barWidth, barHeight, barWidth / 2);
        context.fill();
        context.globalAlpha = value * 0.24;
        context.shadowBlur = 0;
        context.fillStyle = "rgba(255, 47, 179, 0.38)";
        roundRect(context, x, baseY, barWidth, barHeight * 0.62, barWidth / 2);
        context.fill();
      }
      context.globalAlpha = 1;
      context.shadowBlur = 0;
    }
    function roundRect(target, x, y, width, height, radius) {
      const safeRadius = Math.min(radius, width / 2, height / 2);
      target.beginPath();
      target.moveTo(x + safeRadius, y);
      target.lineTo(x + width - safeRadius, y);
      target.quadraticCurveTo(x + width, y, x + width, y + safeRadius);
      target.lineTo(x + width, y + height - safeRadius);
      target.quadraticCurveTo(x + width, y + height, x + width - safeRadius, y + height);
      target.lineTo(x + safeRadius, y + height);
      target.quadraticCurveTo(x, y + height, x, y + height - safeRadius);
      target.lineTo(x, y + safeRadius);
      target.quadraticCurveTo(x, y, x + safeRadius, y);
      target.closePath();
    }
    connectButton.addEventListener("click", () => {
      if (socket && socket.readyState === WebSocket.OPEN) {
        disconnect();
        connectButton.textContent = "Connect";
        return;
      }
      connect();
      connectButton.textContent = "Disconnect";
    });
    wsUrlInput.addEventListener("keydown", event => {
      if (event.key === "Enter") {
        connect();
        connectButton.textContent = "Disconnect";
      }
    });
    window.addEventListener("resize", resizeCanvas);
    draw();
    connect();
    connectButton.textContent = "Disconnect";
  </script>
</body>
</html>
samples/plugins/sample.audio-visualizer/plugin.json
@@ -4,16 +4,16 @@
  "version": "1.0.0",
  "type": "widget",
  "entry": "index.html",
  "description": "Full-width music rhythm bars for the lower desktop area.",
  "description": "Full-screen music rhythm bars for the desktop.",
  "author": "Moli.Desktop",
  "permissions": [
    "audio-capture"
  ],
  "defaultLayout": {
    "x": 0,
    "y": 720,
    "width": 1920,
    "height": 240,
    "y": 0,
    "width": 2560,
    "height": 1080,
    "locked": false,
    "clickThrough": true,
    "opacity": 0.92,
@@ -21,7 +21,7 @@
    "displayPriority": "iconLayer"
  },
  "config": {
    "barCount": 192,
    "barCount": 256,
    "primaryColor": "#ff2fb3",
    "secondaryColor": "#29d8ff",
    "accentColor": "#f8fbff",
scripts/publish-to-apps.ps1
New file
@@ -0,0 +1,135 @@
param(
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64",
    [string]$TargetRoot = "Y:\Application",
    [string]$AppName = "Moli.Desktop",
    [switch]$SelfContained,
    [switch]$SkipTests,
    [switch]$NoZip,
    [switch]$KeepStaging
)
$ErrorActionPreference = "Stop"
function Invoke-CheckedRobocopy {
    param(
        [Parameter(Mandatory = $true)]
        [string]$Source,
        [Parameter(Mandatory = $true)]
        [string]$Destination
    )
    robocopy $Source $Destination /MIR /FFT /R:2 /W:2 /XD ".git" ".vs" /XF "*.pdb"
    $exitCode = $LASTEXITCODE
    if ($exitCode -gt 7) {
        throw "robocopy failed with exit code $exitCode"
    }
}
function Stop-PublishedApplication {
    param(
        [Parameter(Mandatory = $true)]
        [string]$ProcessName,
        [Parameter(Mandatory = $true)]
        [string]$ExecutablePath
    )
    $normalizedExecutablePath = [System.IO.Path]::GetFullPath($ExecutablePath)
    $processes = Get-Process -Name $ProcessName -ErrorAction SilentlyContinue
    foreach ($process in $processes) {
        $matchesTarget = $false
        try {
            $processPath = [System.IO.Path]::GetFullPath($process.MainModule.FileName)
            $matchesTarget = [string]::Equals($processPath, $normalizedExecutablePath, [System.StringComparison]::OrdinalIgnoreCase)
        }
        catch {
            Write-Warning "Cannot inspect process path for $ProcessName (PID $($process.Id)); skipping it."
        }
        if ($matchesTarget) {
            Write-Host "Stopping running application: $ProcessName (PID $($process.Id))"
            Stop-Process -Id $process.Id -Force
            $process.WaitForExit(10000)
        }
    }
}
$repoRoot = Resolve-Path (Join-Path $PSScriptRoot "..")
$solutionPath = Join-Path $repoRoot "Moli.Desktop.slnx"
$projectPath = Join-Path $repoRoot "src\Moli.Desktop\Moli.Desktop.csproj"
$stagingRoot = Join-Path $repoRoot "artifacts\release"
$publishDir = Join-Path $stagingRoot "publish\$AppName"
$targetRootPath = Join-Path $TargetRoot ""
$targetDir = Join-Path $targetRootPath $AppName
$targetExePath = Join-Path $targetDir "$AppName.exe"
$zipPath = Join-Path $targetRootPath "$AppName-$Runtime.zip"
if (-not (Test-Path -LiteralPath $projectPath)) {
    throw "Project file not found: $projectPath"
}
if (-not (Test-Path -LiteralPath $TargetRoot)) {
    New-Item -ItemType Directory -Force -Path $TargetRoot | Out-Null
}
$resolvedTargetRoot = (Resolve-Path -LiteralPath $TargetRoot).Path
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
$resolvedTargetDir = (Resolve-Path -LiteralPath $targetDir).Path
if ($resolvedTargetDir -eq $resolvedTargetRoot) {
    throw "Refusing to publish directly into target root: $resolvedTargetRoot"
}
if (-not $resolvedTargetDir.StartsWith($resolvedTargetRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
    throw "Resolved target is outside target root: $resolvedTargetDir"
}
New-Item -ItemType Directory -Force -Path $stagingRoot | Out-Null
if (Test-Path -LiteralPath $publishDir) {
    Remove-Item -LiteralPath $publishDir -Recurse -Force
}
if (-not $SkipTests) {
    dotnet test $solutionPath --configuration $Configuration
}
$selfContainedValue = if ($SelfContained) { "true" } else { "false" }
dotnet publish $projectPath `
    --configuration $Configuration `
    --runtime $Runtime `
    --self-contained $selfContainedValue `
    -p:PublishSingleFile=false `
    --output $publishDir
Stop-PublishedApplication -ProcessName $AppName -ExecutablePath $targetExePath
if (Test-Path -LiteralPath $targetDir) {
    Write-Host "Removing old published files:"
    Write-Host $targetDir
    Remove-Item -LiteralPath $targetDir -Recurse -Force
}
New-Item -ItemType Directory -Force -Path $targetDir | Out-Null
Invoke-CheckedRobocopy -Source $publishDir -Destination $targetDir
if (-not $NoZip) {
    if (Test-Path -LiteralPath $zipPath) {
        Remove-Item -LiteralPath $zipPath -Force
    }
    Compress-Archive -Path (Join-Path $publishDir "*") -DestinationPath $zipPath -Force
}
if (-not $KeepStaging) {
    Remove-Item -LiteralPath $stagingRoot -Recurse -Force
}
Write-Host "Starting application:"
Write-Host $targetExePath
Start-Process -FilePath $targetExePath -WorkingDirectory $targetDir
Write-Host "Published application:"
Write-Host $targetDir
if (-not $NoZip) {
    Write-Host "Portable package:"
    Write-Host $zipPath
}
src/Moli.Desktop/Assets/1.icon.png
src/Moli.Desktop/Assets/2.icon.png
src/Moli.Desktop/Assets/Moli.Desktop - ¸±±¾.ico
src/Moli.Desktop/Assets/Moli.Desktop.ico

src/Moli.Desktop/Audio/AudioSpectrumAnalyzer.cs
@@ -5,7 +5,7 @@
public sealed class AudioSpectrumAnalyzer
{
    public const int DefaultFftSize = 1024;
    public const int DefaultLevelCount = 64;
    public const int DefaultLevelCount = 128;
    private readonly object _gate = new();
    private readonly int _fftSize;
    private readonly int _levelCount;
src/Moli.Desktop/Moli.Desktop.csproj
@@ -17,6 +17,13 @@
  </ItemGroup>
  <ItemGroup>
    <None Update="Assets\Moli.Desktop.ico">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </None>
  </ItemGroup>
  <ItemGroup>
    <Content Include="..\..\samples\plugins\**\*">
      <Link>samples\plugins\%(RecursiveDir)%(Filename)%(Extension)</Link>
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
src/Moli.Desktop/Tray/TrayShell.cs
@@ -44,7 +44,7 @@
    {
        _notifyIcon = new Forms.NotifyIcon
        {
            Icon = Drawing.SystemIcons.Application,
            Icon = LoadTrayIcon(),
            Text = "Moli Desktop",
            Visible = true,
            ContextMenuStrip = BuildMenu()
@@ -157,4 +157,35 @@
    }
    private static string TrimForTray(string text) => text.Length <= 63 ? text : text[..63];
    private static Drawing.Icon LoadTrayIcon()
    {
        try
        {
            var iconPath = Path.Combine(AppContext.BaseDirectory, "Assets", "Moli.Desktop.ico");
            if (File.Exists(iconPath))
            {
                return new Drawing.Icon(iconPath);
            }
        }
        catch (Exception)
        {
            // Fall back to the embedded executable icon below.
        }
        try
        {
            var executablePath = Environment.ProcessPath;
            if (!string.IsNullOrWhiteSpace(executablePath) && File.Exists(executablePath))
            {
                return Drawing.Icon.ExtractAssociatedIcon(executablePath) ?? Drawing.SystemIcons.Application;
            }
        }
        catch (Exception)
        {
            // Last resort keeps the tray available even if icon loading fails.
        }
        return Drawing.SystemIcons.Application;
    }
}