Files
SodiumPet/src/main/index.ts
T
deepseek 91bb31b0e0 fix(linux): Wayland 下通过 KWin 桥接获取全局光标,修复视线跟随
XWayland 的 XQueryPointer 只在指针位于 X11 窗口上时更新,指针进入原生
Wayland 窗口后 screen.getCursorScreenPoint() 会冻结,导致视线停在最后位置。

- 新增 src/main/kwinCursor.ts:屏幕外的 16x16 辅助窗口(skipTaskbar/
  skipSwitcher/keepBelow),由 KWin 脚本移动到 (光标.x-20000, 光标.y)
- 新增 assets/kwin/sodiumpet-cursor.js:监听 workspace.cursorPosChanged
- globalCursor() 优先读取桥接结果,视线跟随与拖拽共用
- 通过 D-Bus 自动加载/补装 KWin 脚本,SODIUM_PET_KWIN_CURSOR=0 可关闭
- 视线复位哨兵从负数改为 NaN(窗口外负坐标是合法的)
- README / CHANGELOG 更新
2026-12-02 07:36:20 +09:00

2424 lines
83 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
app,
BrowserWindow,
Tray,
Menu,
ipcMain,
protocol,
net,
nativeImage,
screen,
type NativeImage
} from 'electron'
import * as fs from 'node:fs'
import * as path from 'node:path'
import { pathToFileURL } from 'node:url'
import { StateStore } from './stateStore'
import { MediaStore } from './mediaStore'
import { KnowledgeBase } from './knowledge'
import { rollAccident } from '../shared/accidents'
import { ITEMS, itemById, levelOf } from '../shared/petState'
import { barkText } from '../shared/barks'
import { findPreset } from '../shared/dialogue'
import { applyCatalog, snapshotCatalog } from '../shared/catalog'
import { mergeCatalog, type ModFile } from '../shared/mod'
import { elementOf } from '../shared/elements'
import { desktopCapturer } from 'electron'
import { shell, dialog } from 'electron'
import * as http from 'node:http'
import { DESIGN_H, DESIGN_W, type PetConfig } from '../shared/petState'
import { pickBark, pickClickBark, type BarkState } from '../shared/barks'
import { ChatService } from './llm'
import { chatEffect, suggestions } from '../shared/dialogue'
import {
bootstrapPlatform,
capabilities,
ensureOzoneBackend,
defaultHomeCandidates,
globalCursor,
placeWindow,
platformSummary,
raiseWindow,
showOnAllWorkspaces,
IS_LINUX
} from './platform'
import { startKwinCursorBridge } from './kwinCursor'
// Linux 下需要在 app ready 前指定 Ozone 后端(Wayland 会话默认走 XWayland)
bootstrapPlatform()
// 启动参数里没带 --ozone-platform 时,用一次 relaunch 补上(否则原生 Wayland 会直接崩)
ensureOzoneBackend()
// ---------------------------------------------------------------- 数据目录
// Windows:默认把「软件主体」放到 E:\SodiumPet,只有临时/GPU 缓存留在 C 盘。
// Linux:放到 $XDG_DATA_HOME/SodiumPet(~/.local/share/SodiumPet)。
// 沙箱里写不进去时,逐级回退,保证开发时也能跑。
function resolveHome(): string {
const candidates = [
process.env.SODIUM_PET_HOME,
...defaultHomeCandidates(),
// Windows 上仍然保留「exe 同级目录」这个习惯
...(IS_LINUX ? [] : [path.dirname(app.getPath('exe'))]),
path.join(app.getPath('appData'), 'SodiumPet'),
path.join(app.getAppPath(), '.devdata')
].filter(Boolean) as string[]
for (const dir of candidates) {
try {
fs.mkdirSync(path.join(dir, 'data'), { recursive: true })
const probe = path.join(dir, 'data', '.probe')
fs.writeFileSync(probe, 'ok')
fs.unlinkSync(probe)
return dir
} catch {
// 试下一个
}
}
return app.getPath('userData')
}
const HOME = resolveHome()
try {
app.setPath('userData', path.join(HOME, 'data'))
app.setPath('sessionData', path.join(HOME, 'cache'))
app.setPath('logs', path.join(HOME, 'logs'))
} catch {
// 极端情况下继续用默认路径
}
// ---------------------------------------------------------------- 自定义协议
// pet://skins/<id>/... -> <HOME>/skins(首次运行从内置皮肤播种)
// pet://lib/<file> -> node_modules/live2dcubismcore/<file>
protocol.registerSchemesAsPrivileged([
{
scheme: 'pet',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
stream: true
}
}
])
const APP_DIR = app.getAppPath()
let mainWindow: BrowserWindow | null = null
let panelWindow: BrowserWindow | null = null
let bubbleWindow: BrowserWindow | null = null
let bubbleTimer: NodeJS.Timeout | null = null
let tray: Tray | null = null
let quitting = false
function sanitizeId(name: string): string {
const s = String(name).replace(/[\\/:*?"<>|]/g, '_').trim()
return s || 'default'
}
function profileRoot(): string {
return path.join(HOME, 'data', 'profiles', profileId)
}
function readProfileFromConfig(): string {
try {
const raw = fs.readFileSync(path.join(HOME, 'data', 'config.json'), 'utf8')
const cfg = JSON.parse(raw) as { profile?: string }
return sanitizeId(cfg.profile || '')
} catch {
return ''
}
}
// 旧版数据迁移进 profiles/default
function migrateLegacyData(): void {
const baseDir = path.join(HOME, 'data')
const profilesDir = path.join(baseDir, 'profiles')
if (fs.existsSync(profilesDir)) return
if (!fs.existsSync(path.join(baseDir, 'save.json'))) return
const target = path.join(profilesDir, 'default')
fs.mkdirSync(target, { recursive: true })
for (const item of ['save.json', 'photos.json', 'files.json']) {
const src = path.join(baseDir, item)
if (fs.existsSync(src)) fs.renameSync(src, path.join(target, item))
}
{
const srcCfg = path.join(baseDir, 'config.json')
if (fs.existsSync(srcCfg)) fs.copyFileSync(srcCfg, path.join(target, 'config.json'))
}
for (const dir of ['photos', 'files', 'knowledge', 'workspace']) {
const src = path.join(baseDir, dir)
if (fs.existsSync(src)) fs.renameSync(src, path.join(target, dir))
}
console.log('[profile] 旧数据已迁移到 profiles/default')
}
migrateLegacyData()
// 载入用户编辑过的物品 / 活动目录
try {
const catalogPath = path.join(HOME, 'data', 'catalog.json')
if (fs.existsSync(catalogPath)) {
applyCatalog(JSON.parse(fs.readFileSync(catalogPath, 'utf8')))
console.log('[catalog] 已加载用户目录')
}
} catch (err) {
console.error('[catalog] 读取失败', err)
}
// 应用 MOD(data/mods/*.json)
try {
const modsDir = path.join(HOME, 'data', 'mods')
fs.mkdirSync(modsDir, { recursive: true })
let merged = snapshotCatalog()
for (const f of fs.readdirSync(modsDir).filter((n) => n.endsWith('.json'))) {
try {
const mod = JSON.parse(fs.readFileSync(path.join(modsDir, f), 'utf8')) as ModFile
merged = mergeCatalog({ items: merged.items ?? [], jobs: merged.jobs ?? [] }, mod)
} catch (err) {
console.error('[mod] 加载失败', f, err)
}
}
applyCatalog(merged)
console.log('[mod] 已应用,物品', ITEMS.length, '活动', merged.jobs?.length ?? 0)
} catch (err) {
console.error('[mod] 目录读取失败', err)
}
const initialProfile = readProfileFromConfig()
let profileId = sanitizeId(initialProfile)
let store = new StateStore(profileRoot())
let media = new MediaStore(profileRoot())
let kb = new KnowledgeBase(profileRoot())
fs.mkdirSync(path.join(HOME, 'data', 'profiles'), { recursive: true })
store.setConfig({ profile: profileId })
const chatService = new ChatService(() => store.getLlm(), () => store.snapshot())
function bundledDir(name: string): string {
return app.isPackaged
? path.join(process.resourcesPath, name)
: path.join(APP_DIR, 'assets', name)
}
function bundledSkins(): string {
return bundledDir('skins')
}
function userSkins(): string {
const dir = path.join(HOME, 'skins')
try {
if (!fs.existsSync(dir)) fs.cpSync(bundledSkins(), dir, { recursive: true })
} catch (err) {
console.warn('[skins] 播种失败,使用空目录', err)
}
try {
fs.mkdirSync(dir, { recursive: true })
} catch {
/* 忽略 */
}
return dir
}
function libRoot(): string {
return bundledDir('lib')
}
function isInside(root: string, target: string): boolean {
const rel = path.relative(path.resolve(root), path.resolve(target))
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel)
}
function registerProtocol(): void {
protocol.handle('pet', async (request) => {
try {
const url = new URL(request.url)
const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '')
let abs: string
let root: string
if (url.host === 'skins') {
abs = path.join(userSkins(), rel)
root = userSkins()
} else if (url.host === 'lib') {
abs = path.join(libRoot(), rel)
root = libRoot()
} else if (url.host === 'photos') {
abs = path.join(media.photoDir, rel)
root = media.photoDir
} else if (url.host === 'stickers') {
const dir = bundledDir('stickers')
abs = path.join(dir, rel)
root = dir
} else if (url.host === 'music') {
const dir = readMusicDir()
if (!dir) return new Response('no music dir', { status: 404 })
abs = path.join(dir, rel)
root = dir
} else if (url.host === 'data') {
abs = path.join(HOME, 'data', rel)
root = path.join(HOME, 'data')
} else {
return new Response('not found', { status: 404 })
}
if (!isInside(root, abs)) return new Response('forbidden', { status: 403 })
// 文件不存在时直接返回 404:net.fetch(file://) 会对缺失文件抛 ERR_FILE_NOT_FOUND,
// 日志里会刷一堆红色堆栈(比如首次启动还没有 data/catalog.json)
if (!fs.existsSync(abs)) return new Response('not found', { status: 404 })
// 音频需要 Range 支持,才能拖动进度条 / 正常播放
if (url.host === 'music' && fs.existsSync(abs) && fs.statSync(abs).isFile()) {
const data = fs.readFileSync(abs)
const ext = path.extname(abs).toLowerCase()
const mime =
ext === '.mp3'
? 'audio/mpeg'
: ext === '.flac'
? 'audio/flac'
: ext === '.wav'
? 'audio/wav'
: ext === '.ogg'
? 'audio/ogg'
: ext === '.m4a' || ext === '.aac'
? 'audio/mp4'
: 'application/octet-stream'
const range = request.headers.get('Range')
if (range) {
const m = /bytes=(\d*)-(\d*)/.exec(range)
const start = m && m[1] ? Number(m[1]) : 0
const end = m && m[2] ? Math.min(Number(m[2]), data.length - 1) : data.length - 1
const chunk = data.subarray(start, end + 1)
return new Response(chunk, {
status: 206,
headers: {
'Content-Type': mime,
'Accept-Ranges': 'bytes',
'Content-Range': `bytes ${start}-${end}/${data.length}`,
'Content-Length': String(chunk.length)
}
})
}
return new Response(data, {
status: 200,
headers: {
'Content-Type': mime,
'Accept-Ranges': 'bytes',
'Content-Length': String(data.length)
}
})
}
return await net.fetch(pathToFileURL(abs).toString())
} catch (err) {
console.error('[pet://]', err)
return new Response(`error: ${String(err)}`, { status: 500 })
}
})
}
// ---------------------------------------------------------------- 托盘图标
function buildTrayIcon(): NativeImage {
try {
const p = path.join(bundledDir('stickers'), '1.0.png')
if (fs.existsSync(p)) return nativeImage.createFromPath(p).resize({ width: 32, height: 32 })
} catch {
/* 回落 */
}
const S = 32
const buf = Buffer.alloc(S * S * 4)
const c = (S - 1) / 2
for (let y = 0; y < S; y++) {
for (let x = 0; x < S; x++) {
const d = Math.hypot(x - c, y - c)
if (d > 13.5) continue
const edge = d > 11.5
const i = (y * S + x) * 4
buf[i] = edge ? 30 : 90
buf[i + 1] = edge ? 160 : 215
buf[i + 2] = edge ? 240 : 255
buf[i + 3] = 255
}
}
return nativeImage.createFromBitmap(buf, { width: S, height: S })
}
// ---------------------------------------------------------------- 主窗口
function appIcon(): NativeImage | undefined {
try {
const p = path.join(bundledDir('stickers'), '1.0.png')
if (fs.existsSync(p)) return nativeImage.createFromPath(p).resize({ width: 256, height: 256 })
} catch {
/* 忽略 */
}
return undefined
}
function createWindow(): void {
const { workArea } = screen.getPrimaryDisplay()
const width = 190
const height = 450
const icon = appIcon()
mainWindow = new BrowserWindow({
width,
height,
// 原生 Wayland 会忽略坐标,由合成器决定位置;这里只对 X11/XWayland 生效
x: Math.round(workArea.x + workArea.width - width - 24),
y: Math.round(workArea.y + workArea.height - height),
show: false,
frame: false,
transparent: true,
backgroundColor: '#00000000',
resizable: false,
maximizable: false,
minimizable: false,
fullscreenable: false,
skipTaskbar: true,
hasShadow: false,
alwaysOnTop: true,
...(IS_LINUX ? { icon } : {}),
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
raiseWindow(mainWindow, true)
showOnAllWorkspaces(mainWindow)
// 部分 X11 窗口管理器不会在创建时应用 skipTaskbar,显式再设一次(Linux 桌宠不该出现在任务栏)
if (IS_LINUX) mainWindow.setSkipTaskbar(true)
mainWindow.loadFile(path.join(__dirname, '../renderer/index.html'))
mainWindow.once('ready-to-show', () => {
// 系统 DPI 缩放可能被带进页面,强制 1:1,避免内容被放大/裁切
mainWindow?.webContents.setZoomFactor(1)
mainWindow?.show()
raiseWindow(mainWindow, true)
})
mainWindow.on('show', () => {
raiseWindow(mainWindow, true)
if (capabilities.topmost) mainWindow?.moveTop()
})
// 有些全屏程序会抢置顶,定期重新申明一次(很轻,不影响性能)
if (capabilities.topmost) {
setInterval(() => {
if (!mainWindow?.isVisible()) return
raiseWindow(mainWindow, true)
}, 15000)
}
// 调试:把窗口内容截一张(不受窗口是否被遮挡影响)
if (process.env.PET_CAPTURE_ONCE) {
setTimeout(() => {
say('冒泡测试:你好呀', 8000)
}, 3200)
setTimeout(() => {
showMenu()
}, 4000)
setTimeout(() => {
fs.writeFileSync(
path.join(HOME, 'data', 'toggle.txt'),
'shown menu=' + (menuWindow?.isVisible() ?? false) + ' chat=' + (chatBar?.isVisible() ?? false)
)
}, 4300)
setTimeout(() => {
fs.appendFileSync(
path.join(HOME, 'data', 'toggle.txt'),
' | after-blur menu=' + (menuWindow?.isVisible() ?? false) + ' chat=' + (chatBar?.isVisible() ?? false)
)
}, 5500)
setTimeout(async () => {
const probe = async (w: any, sel: string): Promise<string> => {
try {
return String(
await w.webContents.executeJavaScript(
'JSON.stringify({t: document.documentElement.dataset.theme, bg: getComputedStyle(document.querySelector("' + sel + '")).backgroundColor, fg: getComputedStyle(document.querySelector("' + sel + '")).color})'
)
)
} catch (e) {
return 'ERR'
}
}
const lines = [
'menu: ' + (await probe(menuWindow, '.menu-bar')),
'chat: ' + (await probe(chatBar, '.chat-bar')),
'bubble: ' + (await probe(bubbleWindow, '.bubble-text')),
'cfgTheme: ' + store.getConfig().theme
]
fs.writeFileSync(path.join(HOME, 'data', 'theme-probe.txt'), lines.join('\n'))
}, 6400)
setTimeout(() => {
toggleMenu()
}, 6000)
setTimeout(() => {
fs.appendFileSync(
path.join(HOME, 'data', 'toggle.txt'),
' | toggled menu=' + (menuWindow?.isVisible() ?? false) + ' chat=' + (chatBar?.isVisible() ?? false)
)
}, 6300)
setTimeout(() => {
createPanel(process.env.PET_CAPTURE_TAB || undefined)
}, 7000)
setTimeout(() => {
createStorageWindow()
}, 4000)
setTimeout(() => {
createDetailWindow()
}, 4600)
setTimeout(() => {
createEditorWindow()
}, 5000)
setTimeout(() => {
createMusicWindow()
createLyricWindow()
}, 5400)
setTimeout(async () => {
if (!chatBar) return
const r = await chatBar.webContents.executeJavaScript(
"(async () => { const a = await window.pet.getChatPresets(); const before = a.presets.map(p => p.id); const first = a.presets[0]; let after = null; if (first) { await window.pet.chatPreset(first.id); const b = await window.pet.getChatPresets(); after = b.presets.map(p => p.id) } return JSON.stringify({ beforeCount: before.length, before, afterCount: after ? after.length : -1, after }); })()"
)
fs.writeFileSync(path.join(HOME, 'data', 'preset-click.txt'), String(r))
const fb = await chatBar.webContents.executeJavaScript(
"document.querySelector('.chat-feedback') ? document.querySelector('.chat-feedback').innerText : 'NO-FEEDBACK'"
)
fs.writeFileSync(path.join(HOME, 'data', 'chat-feedback.txt'), String(fb))
if (bubbleWindow) {
const b = await bubbleWindow.webContents.executeJavaScript(
"document.querySelector('.bubble-text') ? document.querySelector('.bubble-text').innerText : 'no-bubble'"
)
fs.writeFileSync(path.join(HOME, 'data', 'preset-bubble.txt'), String(b))
// 强制刷新周期,验证重新随机
if (store['save'].presets) store['save'].presets.cycleAt = Date.now() - 1
const regen = await chatBar.webContents.executeJavaScript(
"window.pet.getChatPresets().then(r => JSON.stringify({ count: r.presets.length, ids: r.presets.map(p => p.id) }))"
)
fs.writeFileSync(path.join(HOME, 'data', 'preset-regen.txt'), String(regen))
}
}, 5900)
setTimeout(async () => {
if (!musicWindow) return
const st = await musicWindow.webContents.executeJavaScript(
"(async () => { const rows = document.querySelectorAll('.music-row'); if (rows[0]) rows[0].click(); await new Promise(r => setTimeout(r, 2500)); const a = document.querySelector('audio'); return JSON.stringify({ rows: rows.length, attr: a ? a.getAttribute('src') : '', src: a ? a.currentSrc : '', ready: a ? a.readyState : -1, err: a && a.error ? a.error.code + ':' + a.error.message : '', dur: a ? a.duration : -1, paused: a ? a.paused : true }); })()"
)
fs.writeFileSync(path.join(HOME, 'data', 'audio-state.txt'), String(st))
}, 6500)
setTimeout(() => {
void (async () => {
if (!musicWindow) return
const txt = await musicWindow.webContents.executeJavaScript(
"document.querySelector('.music') ? document.querySelector('.music').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'music.txt'), String(txt).slice(0, 400))
if (lyricWindow) {
const ly = await lyricWindow.webContents.executeJavaScript(
"document.querySelector('.lyric-box') ? document.querySelector('.lyric-box').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'lyric.txt'), String(ly).slice(0, 200))
}
})()
}, 9200)
setTimeout(() => {
void (async () => {
if (!editorWindow) return
await editorWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.detail-tabs .set-tab')].find(b => b.textContent === '界面')?.click()"
)
await new Promise((r) => setTimeout(r, 400))
const txt = await editorWindow.webContents.executeJavaScript(
"document.querySelector('.editor') ? document.querySelector('.editor').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'editor.txt'), String(txt).slice(0, 800))
const stickerCount = await editorWindow.webContents.executeJavaScript(
"document.querySelectorAll('.sticker-cell').length"
)
fs.writeFileSync(path.join(HOME, 'data', 'stickers.txt'), String(stickerCount))
})()
}, 9000)
setTimeout(() => {
void (async () => {
if (!detailWindow) return
const txt = await detailWindow.webContents.executeJavaScript(
"document.querySelector('.detail') ? document.querySelector('.detail').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'detail.txt'), String(txt).slice(0, 600))
await detailWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.detail-tabs .set-tab')].find(b => b.textContent === '等级预览')?.click()"
)
await new Promise((r) => setTimeout(r, 400))
await detailWindow.webContents.executeJavaScript(
"[...document.querySelectorAll('.level-mode .set-tab')].find(b => b.textContent.includes('化学'))?.click()"
)
await new Promise((r) => setTimeout(r, 400))
const online = await detailWindow.webContents.executeJavaScript(
"document.querySelector('.element-online') ? document.querySelector('.element-online').innerText : 'NO-ONLINE-BLOCK'"
)
fs.writeFileSync(path.join(HOME, 'data', 'online.txt'), String(online).slice(0, 500))
await new Promise((r) => setTimeout(r, 500))
const lvTxt = await detailWindow.webContents.executeJavaScript(
"document.querySelector('.detail').innerText"
)
fs.writeFileSync(path.join(HOME, 'data', 'levels.txt'), String(lvTxt).slice(0, 1200))
const style = await detailWindow.webContents.executeJavaScript(
"JSON.stringify({theme: document.documentElement.dataset.theme, row: document.querySelector('.row-title') ? getComputedStyle(document.querySelector('.row-title')).color : 'none', mini: document.querySelector('.mini') ? getComputedStyle(document.querySelector('.mini')).backgroundColor : 'none'})"
)
fs.writeFileSync(path.join(HOME, 'data', 'detail-style.txt'), String(style))
})()
}, 8600)
setTimeout(() => {
void (async () => {
if (!storageWindow) return
const txt = await storageWindow.webContents.executeJavaScript(
"document.querySelector('.storage') ? document.querySelector('.storage').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'storage.txt'), String(txt).slice(0, 800))
})()
}, 8000)
setTimeout(async () => {
try {
if (panelWindow) {
const img = await panelWindow.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'panel.png'), img.toPNG())
const txt = await panelWindow.webContents.executeJavaScript(
"document.querySelector('.panel') ? document.querySelector('.panel').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'panel.txt'), String(txt).slice(0, 2000))
const iconCount = await panelWindow.webContents.executeJavaScript(
"document.querySelectorAll('img.tab-icon').length + '/' + [...document.querySelectorAll('img.tab-icon')].map(i => i.src.split('stickers/')[1] || i.src).join(',')"
)
fs.writeFileSync(path.join(HOME, 'data', 'tabicons.txt'), String(iconCount))
const photoInfo = await panelWindow.webContents.executeJavaScript(
"document.querySelector('.photo') ? document.querySelector('.photo').naturalWidth + 'x' + document.querySelector('.photo').naturalHeight : 'no-img'"
)
fs.writeFileSync(path.join(HOME, 'data', 'photo.txt'), String(photoInfo))
}
if (bubbleWindow) {
const img3 = await bubbleWindow.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'bubble.png'), img3.toPNG())
const txt = await bubbleWindow.webContents.executeJavaScript(
"document.querySelector('.bubble-text') ? document.querySelector('.bubble-text').innerText : ''"
)
fs.writeFileSync(path.join(HOME, 'data', 'bubble.txt'), String(txt))
}
if (menuWindow && menuWindow.isVisible()) {
const img4 = await menuWindow.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'menu.png'), img4.toPNG())
}
if (chatBar && chatBar.isVisible()) {
const img5 = await chatBar.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'chatbar.png'), img5.toPNG())
}
const img2 = await mainWindow!.webContents.capturePage()
fs.writeFileSync(path.join(HOME, 'data', 'capture.png'), img2.toPNG())
const diag = await mainWindow!.webContents.executeJavaScript(
"JSON.stringify({ body: document.body.innerText.slice(0,200), err: document.querySelector('.pet-error') ? document.querySelector('.pet-error').textContent : '', canvas: !!document.querySelector('canvas'), hint: document.querySelector('.pet-hint') ? document.querySelector('.pet-hint').textContent : '' })"
)
fs.writeFileSync(path.join(HOME, 'data', 'diag.txt'), String(diag))
const probe = await mainWindow!.webContents.executeJavaScript(
"fetch('pet://skins/xiaona/skin.json').then(r => 'skin-ok ' + r.status).catch(e => 'skin-FAIL ' + e.message)"
)
fs.writeFileSync(path.join(HOME, 'data', 'probe.txt'), String(probe))
const petTxt = await mainWindow!.webContents.executeJavaScript('document.body.innerText')
fs.writeFileSync(path.join(HOME, 'data', 'pet.txt'), String(petTxt).slice(0, 400))
{
const size = img2.getSize()
const buf = img2.toBitmap()
let minX = 1e9
let minY = 1e9
let maxX = -1
let maxY = -1
for (let y = 0; y < size.height; y++) {
for (let x = 0; x < size.width; x++) {
if (buf[(y * size.width + x) * 4 + 3] > 16) {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
}
}
}
fs.writeFileSync(
path.join(HOME, 'data', 'bbox.txt'),
`bbox=(${minX},${minY})-(${maxX},${maxY}) in ${size.width}x${size.height}`
)
}
console.log('[debug] capture saved')
} catch (err) {
console.error('[debug] capture failed', err)
}
}, 8000)
}
// 诊断:让窗口自己来回移动,观察视口是否被重新计算
if (process.env.PET_DRAG_TEST) {
setTimeout(() => {
let dir = 1
let n = 0
const timer = setInterval(() => {
if (!mainWindow) return
const [x, y] = mainWindow.getPosition()
mainWindow.setPosition(x + dir * 12, y)
n += 1
if (n % 10 === 0) dir *= -1
if (n > 40) clearInterval(timer)
}, 50)
}, 3000)
}
mainWindow.on('resize', () => {
console.log('[main] window resized ->', mainWindow?.getSize(), 'dpr=', screen.getPrimaryDisplay().scaleFactor)
})
mainWindow.on('close', (event) => {
if (!quitting) {
event.preventDefault()
mainWindow?.hide()
}
})
mainWindow.webContents.on('console-message', (_e, _level, message) => {
console.log('[renderer]', message)
})
mainWindow.on('closed', () => {
mainWindow = null
})
}
// ---------------------------------------------------------------- 外观配置
// 设计稿是 288×678 CSS;窗口尺寸 = 设计尺寸 × scale − 裁剪量。
// 这台机器上 CSS 像素是 DIP 的 1.5 倍,所以再除 1.5。
const CSS_PER_DIP = 1
function applyConfig(cfg: PetConfig): void {
if (!mainWindow || mainWindow.isDestroyed()) return
const width = Math.max(80, Math.round(DESIGN_W * cfg.scale - cfg.cropLeft - cfg.cropRight))
const height = Math.max(80, Math.round(DESIGN_H * cfg.scale - cfg.cropTop - cfg.cropBottom))
const b = mainWindow.getBounds()
// 右下角锚定,缩放/裁剪时不会跑位
placeWindow(mainWindow, {
x: Math.round(b.x + (b.width - width)),
y: Math.round(b.y + (b.height - height)),
width,
height
})
console.log('[config] bounds', mainWindow.getBounds(), 'dpr', screen.getPrimaryDisplay().scaleFactor)
raiseWindow(mainWindow, cfg.topmost)
if (capabilities.clickThrough) {
mainWindow.setIgnoreMouseEvents(cfg.clickThrough, { forward: true })
}
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:config:update', cfg)
}
positionChatBar()
}
// ---------------------------------------------------------------- 气泡窗口
const barkState: BarkState = { lastSaid: {} }
let bubbleReady = false
let pendingBubble: { text: string; duration: number } | null = null
let streamBuffer: Array<{ channel: string; payload: unknown }> | null = null
let currentBubble: { text: string; duration: number; at: number } | null = null
function createBubbleWindow(): void {
if (bubbleWindow && !bubbleWindow.isDestroyed()) return
bubbleWindow = new BrowserWindow({
width: 440,
height: 96,
show: false,
frame: false,
transparent: true,
resizable: false,
focusable: false,
skipTaskbar: true,
hasShadow: false,
alwaysOnTop: true,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
if (capabilities.clickThrough) bubbleWindow.setIgnoreMouseEvents(true, { forward: true })
raiseWindow(bubbleWindow, true)
bubbleWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'bubble' }
})
bubbleReady = false
bubbleWindow.webContents.on('did-finish-load', () => {
bubbleReady = true
if (pendingBubble) {
bubbleWindow?.webContents.send('pet:bubble', pendingBubble)
pendingBubble = null
}
if (streamBuffer) {
for (const item of streamBuffer) {
bubbleWindow?.webContents.send(item.channel, item.payload)
}
streamBuffer = null
}
})
bubbleWindow.on('closed', () => {
bubbleWindow = null
bubbleReady = false
})
}
function positionBubble(): void {
if (!mainWindow || !bubbleWindow) return
const b = mainWindow.getBounds()
const h = bubbleWindow.getBounds().height
placeWindow(bubbleWindow, {
x: Math.round(b.x + (b.width - 440) / 2),
y: b.y - (h - 10),
width: 440,
height: h
})
}
function say(text: string, duration = 6500): void {
createBubbleWindow()
if (bubbleWindow) placeWindow(bubbleWindow, { ...bubbleWindow.getBounds(), width: 440, height: 96 })
positionBubble()
const payload = { text, duration }
currentBubble = { text, duration, at: Date.now() }
if (bubbleReady) {
bubbleWindow?.webContents.send('pet:bubble', payload)
} else {
pendingBubble = payload
}
bubbleWindow?.showInactive()
if (bubbleTimer) clearTimeout(bubbleTimer)
bubbleTimer = setTimeout(() => bubbleWindow?.hide(), duration)
}
let bubbleStreamLen = 0
function sendBubbleStream(channel: string, payload?: unknown): void {
if (!bubbleWindow) return
if (bubbleReady) {
bubbleWindow.webContents.send(channel, payload)
} else {
if (!streamBuffer) streamBuffer = []
streamBuffer.push({ channel, payload })
}
}
function bubbleStreamStart(): void {
createBubbleWindow()
bubbleStreamLen = 0
if (bubbleTimer) clearTimeout(bubbleTimer)
if (bubbleWindow) placeWindow(bubbleWindow, { ...bubbleWindow.getBounds(), width: 440, height: 96 })
positionBubble()
bubbleWindow?.showInactive()
sendBubbleStream('pet:bubble:stream:start')
}
function bubbleStreamChunk(chunk: string): void {
if (!bubbleWindow) return
bubbleStreamLen += chunk.length
const lines = Math.ceil(bubbleStreamLen / 22)
const h = Math.min(300, Math.max(96, 44 + lines * 26))
const b = mainWindow?.getBounds()
if (b) {
placeWindow(bubbleWindow, {
x: Math.round(b.x + (b.width - 440) / 2),
y: b.y - (h - 10),
width: 440,
height: h
})
}
sendBubbleStream('pet:bubble:stream:chunk', { text: chunk })
}
function bubbleStreamEnd(full: string): void {
const duration = Math.min(20_000, 2500 + full.length * 90)
sendBubbleStream('pet:bubble:stream:end', { duration })
if (bubbleTimer) clearTimeout(bubbleTimer)
bubbleTimer = setTimeout(() => bubbleWindow?.hide(), duration)
}
function dailySpecial(): { itemId: string; price: number; day: string } {
const day = new Date().toISOString().slice(0, 10)
let h = 0
for (const ch of day) h = (h * 31 + ch.charCodeAt(0)) % 100000
const item = ITEMS[h % ITEMS.length]
return { itemId: item.id, price: Math.round(item.price * 0.7), day }
}
async function webSearchBing(q: string): Promise<string> {
try {
const res = await fetch(
'https://cn.bing.com/search?q=' + encodeURIComponent(q) + '&setlang=zh-hans',
{
signal: AbortSignal.timeout(8000),
headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)' }
}
)
if (!res.ok) return ''
const html = await res.text()
const items: string[] = []
const re = /<li class="b_algo"[\s\S]*?<h2><a[^>]*href="[^"]*"[^>]*>([\s\S]*?)<\/a><\/h2>[\s\S]*?<p[^>]*>([\s\S]*?)<\/p>/g
let m
let n = 0
while ((m = re.exec(html)) !== null && n < 4) {
const title = m[1].replace(/<[^>]+>/g, '').replace(/&[a-z]+;/gi, ' ').trim()
const snip = m[2].replace(/<[^>]+>/g, '').replace(/&[a-z]+;/gi, ' ').trim()
if (title || snip) items.push((title ? title + ':' : '') + snip)
n++
}
return items.join('\n').slice(0, 1500)
} catch (err) {
console.warn('[web] bing 失败', err)
return ''
}
}
async function webSearch(q: string): Promise<string> {
try {
const url = `https://api.duckduckgo.com/?q=${encodeURIComponent(q)}&format=json&no_html=1&skip_disambig=1`
const res = await fetch(url, { signal: AbortSignal.timeout(8000) })
if (!res.ok) return ''
const json = (await res.json()) as {
AbstractText?: string
RelatedTopics?: Array<string | { Text?: string }>
}
const parts: string[] = []
if (json.AbstractText) parts.push(json.AbstractText)
for (const r of (json.RelatedTopics ?? []).slice(0, 4)) {
if (typeof r === 'string') parts.push(r)
else if (r?.Text) parts.push(r.Text)
}
return parts.join('\n').slice(0, 1500)
} catch (err) {
console.warn('[web] 搜索失败', err)
return ''
}
}
// 统一搜索:DDG 失败再试 Bing
async function webSearchAll(q: string): Promise<string> {
const r1 = await webSearch(q)
if (r1) return r1
return webSearchBing(q)
}
async function captureScreenDataUrl(): Promise<string> {
try {
const sources = await desktopCapturer.getSources({
types: ['screen'],
thumbnailSize: { width: 1280, height: 720 }
})
if (!sources.length) return ''
const img = sources[0].thumbnail
return 'data:image/png;base64,' + img.toPNG().toString('base64')
} catch (err) {
console.warn('[screen] 截屏失败', err)
return ''
}
}
function imageToDataUrl(file: string): string {
try {
const ext = file.toLowerCase().match(/\.(png|jpe?g|gif|webp|bmp)$/)?.[1] ?? 'png'
const mime = ext === 'jpg' ? 'jpeg' : ext
return 'data:image/' + mime + ';base64,' + fs.readFileSync(file).toString('base64')
} catch {
return ''
}
}
async function capturePhoto(): Promise<void> {
try {
const img = await mainWindow!.webContents.capturePage()
const name = `photo-${Date.now()}.png`
fs.writeFileSync(path.join(media.photoDir, name), img.toPNG())
media.addPhoto(name)
store['save'].counters['photo:capture'] = (store['save'].counters['photo:capture'] ?? 0) + 1
store.checkAchievements()
broadcastMedia()
say('(摆了个姿势)拍好了! (๑•̀ㅂ•́)و✧', 5000)
} catch (err) {
console.error('[photo] 拍照失败', err)
}
}
function broadcastMedia(): void {
for (const w of BrowserWindow.getAllWindows()) {
if (w.isDestroyed()) continue
w.webContents.send('pet:photos:update', media.photos)
w.webContents.send('pet:files:update', media.files)
}
}
let nextBarkAt = Date.now() + 25_000
let activeEvent: { id: string; until: number } | null = null
let nextEventAt = Date.now() + 120_000
let lastChargeBark = 0
function startWaterEvent(): void {
if (activeEvent) return
const id = String(Date.now())
activeEvent = { id, until: Date.now() + 10_000 }
mainWindow?.webContents.send('pet:event', { id, type: 'water', until: activeEvent.until })
mainWindow?.webContents.send('pet:motion', 'shake')
say(
currentFlavor() === 'normal'
? '(惊慌)桌上怎么会有水?!呜哇,快帮我擦干!(>﹏<)'
: '(惊慌)桌上怎么有水?!呜哇,快帮我擦干!(>﹏<)',
6000
)
setTimeout(() => {
if (activeEvent?.id === id) {
activeEvent = null
store.applyChatEffect({ mood: -10, oxidation: 15 })
mainWindow?.webContents.send('pet:event', null)
say('(低头看了看手臂)呜……还是沾到了,表面有点发灰 (´・ω・) ', 7000)
}
}, 10_000)
}
function scheduleEvents(): void {
lastJobsDone = store.snapshot().jobsDone
setInterval(() => {
const snapNow = store.snapshot()
if (snapNow.jobsDone > lastJobsDone) {
lastJobsDone = snapNow.jobsDone
const acc = rollAccident()
if (acc) {
if (store.forgiveAccident()) {
say(
'(身后传来老师的声音)「第一次翻车就不罚你了,回去把操作规范抄一遍。」……我记住了 (´-ω-)',
7000
)
return
}
store.applyJobPenalty({
money: acc.money,
mood: acc.mood,
oxidation: acc.oxidation
})
mainWindow?.webContents.send('pet:motion', 'shake')
mainWindow?.webContents.send('pet:toast', `${acc.name}:${acc.money ? ' 经费 ' + acc.money : ''}${acc.mood ? ' 心情 ' + acc.mood : ''}`)
say(acc.bark, 7000)
}
}
// 自动购买:饿了自己买饭团
const cfgNow = store.getConfig()
if (cfgNow.autoBuy && snapNow.stats.satiety < 25 && snapNow.money >= 12) {
const r = store.autoBuy('riceball')
if (r.ok) say('(自己翻出钱包)肚子好饿……我先买个饭团垫一下 (๑´ڡ`๑)', 6000)
}
// 作息:到点自动睡觉 / 起床
const hhmm = new Date().toTimeString().slice(0, 5)
if (hhmm === cfgNow.sleepAt && !snapNow.sleeping && !snapNow.job) {
store.action('sleep')
say('(看了眼时间)到点了,我去睡啦,晚安~ (。-ω-)zzz', 6000)
} else if (hhmm === cfgNow.wakeAt && snapNow.sleeping) {
store.action('sleep')
say('(伸了个懒腰)早上好呀,我醒啦 ( ̄▽ ̄)', 6000)
}
if (Date.now() < nextEventAt) return
const snap = store.snapshot()
// 遇水危机:醒着、没在打工时随机出现(可整体关闭)
if (cfgNow.eventsEnabled && !snap.sleeping && !snap.job && Math.random() < 0.35) {
startWaterEvent()
}
// 正电荷过载:电子过低时提醒(10 分钟冷却)
if (cfgNow.eventsEnabled && snap.stats.electron < 18 && Date.now() > lastChargeBark) {
lastChargeBark = Date.now() + 10 * 60_000
mainWindow?.webContents.send('pet:motion', 'shake')
say('(晃了晃)不行了……正电荷太多了,我要接地一下 (´-ω-)', 6000)
}
nextEventAt = Date.now() + 150_000 + Math.random() * 150_000
}, 30_000)
}
let lastJobsDone = -1
let nextSuggestAt = Date.now() + 180_000
function scheduleSuggestions(): void {
setInterval(() => {
if (Date.now() < nextSuggestAt) return
const snap = store.snapshot()
const pool = suggestions(snap)
const q = pool[Math.floor(Math.random() * pool.length)]
if (q) say(`(凑过来)要不要聊聊天呀?比如——「${q}」`, 7000)
nextSuggestAt = Date.now() + 210_000 + Math.random() * 180_000
}, 30_000)
}
function scheduleBarks(): void {
setInterval(() => {
if (Date.now() < nextBarkAt) return
const snap = store.snapshot()
const bark = pickBark(snap, snap.job, barkState, Date.now())
if (bark) say(barkText(bark.id, bark.text, currentFlavor()))
nextBarkAt = Date.now() + 55_000 + Math.random() * 80_000
}, 15_000)
}
// ---------------------------------------------------------------- 右键菜单
let menuWindow: BrowserWindow | null = null
let chatBar: BrowserWindow | null = null
let storageWindow: BrowserWindow | null = null
let detailWindow: BrowserWindow | null = null
let editorWindow: BrowserWindow | null = null
let musicWindow: BrowserWindow | null = null
let lyricWindow: BrowserWindow | null = null
function createMenuWindow(): void {
if (menuWindow && !menuWindow.isDestroyed()) return
menuWindow = new BrowserWindow({
width: 400,
height: 380,
show: false,
frame: false,
transparent: true,
resizable: false,
skipTaskbar: true,
hasShadow: false,
alwaysOnTop: true,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
raiseWindow(menuWindow, true)
menuWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'menu' }
})
menuWindow.on('blur', () => {
setTimeout(() => {
const mf = menuWindow?.isFocused() ?? false
const cf = chatBar?.isFocused() ?? false
if (!mf && !cf) hideMenu()
}, 350)
})
menuWindow.on('closed', () => {
menuWindow = null
})
}
// ---------------------------------------------------------------- 本地音乐
const MUSIC_EXT = /.(mp3|flac|wav|ogg|m4a|aac|opus)$/i
function musicConfigPath(): string {
return path.join(HOME, 'data', 'music.json')
}
function readMusicDir(): string {
try {
const cfg = JSON.parse(fs.readFileSync(musicConfigPath(), 'utf8')) as { dir?: string }
if (cfg.dir && fs.existsSync(cfg.dir)) return cfg.dir
} catch {
/* 忽略 */
}
return ''
}
function scanMusic(): { dir: string; tracks: Array<{ name: string; file: string }> } {
const dir = readMusicDir()
if (!dir) return { dir: '', tracks: [] }
const tracks: Array<{ name: string; file: string }> = []
const walk = (folder: string, rel: string): void => {
let entries: fs.Dirent[] = []
try {
entries = fs.readdirSync(folder, { withFileTypes: true })
} catch {
return
}
for (const e of entries) {
if (e.isDirectory()) walk(path.join(folder, e.name), rel + e.name + '/')
else if (MUSIC_EXT.test(e.name)) {
tracks.push({ name: e.name.replace(MUSIC_EXT, ''), file: rel + e.name })
}
}
}
walk(dir, '')
return { dir, tracks }
}
let musicServerPort = 0
function startMusicServer(): void {
const server = http.createServer((req, res) => {
try {
const dir = readMusicDir()
if (!dir) {
res.writeHead(404)
res.end()
return
}
const rel = decodeURIComponent((req.url ?? '/').split('?')[0]).replace(/^\/+/, '')
const abs = path.join(dir, rel)
if (!isInside(dir, abs) || !fs.existsSync(abs) || !fs.statSync(abs).isFile()) {
res.writeHead(404)
res.end()
return
}
const ext = path.extname(abs).toLowerCase()
const mime =
ext === '.mp3'
? 'audio/mpeg'
: ext === '.flac'
? 'audio/flac'
: ext === '.wav'
? 'audio/wav'
: ext === '.ogg'
? 'audio/ogg'
: ext === '.m4a' || ext === '.aac'
? 'audio/mp4'
: 'application/octet-stream'
const size = fs.statSync(abs).size
const range = req.headers.range
if (range) {
const m = /bytes=(\d*)-(\d*)/.exec(range)
const start = m && m[1] ? Number(m[1]) : 0
const end = m && m[2] ? Math.min(Number(m[2]), size - 1) : size - 1
res.writeHead(206, {
'Content-Type': mime,
'Accept-Ranges': 'bytes',
'Content-Range': `bytes ${start}-${end}/${size}`,
'Content-Length': String(end - start + 1)
})
fs.createReadStream(abs, { start, end }).pipe(res)
} else {
res.writeHead(200, {
'Content-Type': mime,
'Accept-Ranges': 'bytes',
'Content-Length': String(size)
})
fs.createReadStream(abs).pipe(res)
}
} catch (err) {
console.error('[music server]', err)
try {
res.writeHead(500)
res.end()
} catch {
/* 忽略 */
}
}
})
server.listen(0, '127.0.0.1', () => {
const addr = server.address()
if (addr && typeof addr === 'object') {
musicServerPort = addr.port
console.log('[music server] http://127.0.0.1:' + musicServerPort)
}
})
}
function createMusicWindow(): void {
if (musicWindow && !musicWindow.isDestroyed()) {
musicWindow.show()
musicWindow.focus()
return
}
musicWindow = new BrowserWindow({
width: 880,
height: 600,
minWidth: 700,
minHeight: 460,
show: false,
frame: false,
resizable: true,
backgroundColor: '#0d1017',
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false,
webSecurity: false
}
})
musicWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'music' }
})
musicWindow.once('ready-to-show', () => musicWindow?.show())
musicWindow.on('closed', () => {
musicWindow = null
})
}
function createLyricWindow(): void {
if (lyricWindow && !lyricWindow.isDestroyed()) return
lyricWindow = new BrowserWindow({
width: 560,
height: 110,
show: true,
frame: false,
transparent: true,
resizable: false,
alwaysOnTop: true,
skipTaskbar: true,
hasShadow: false,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
raiseWindow(lyricWindow, true)
if (capabilities.clickThrough) lyricWindow.setIgnoreMouseEvents(false)
lyricWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'lyric' }
})
lyricWindow.on('closed', () => {
lyricWindow = null
})
}
function createEditorWindow(): void {
if (editorWindow && !editorWindow.isDestroyed()) {
editorWindow.show()
editorWindow.focus()
return
}
editorWindow = new BrowserWindow({
width: 780,
height: 560,
minWidth: 640,
minHeight: 420,
show: false,
frame: false,
resizable: true,
backgroundColor: '#0d1017',
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
editorWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'editor' }
})
editorWindow.once('ready-to-show', () => editorWindow?.show())
editorWindow.on('closed', () => {
editorWindow = null
})
}
function createDetailWindow(): void {
if (detailWindow && !detailWindow.isDestroyed()) {
detailWindow.show()
detailWindow.focus()
return
}
detailWindow = new BrowserWindow({
width: 720,
height: 520,
minWidth: 520,
minHeight: 380,
show: false,
frame: false,
resizable: true,
backgroundColor: '#0d1017',
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
detailWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'detail' }
})
detailWindow.once('ready-to-show', () => detailWindow?.show())
detailWindow.on('closed', () => {
detailWindow = null
})
}
function createStorageWindow(): void {
if (storageWindow && !storageWindow.isDestroyed()) {
storageWindow.show()
storageWindow.focus()
return
}
storageWindow = new BrowserWindow({
width: 780,
height: 660,
minWidth: 560,
minHeight: 480,
show: false,
frame: false,
resizable: true,
backgroundColor: '#0d1017',
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
storageWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'storage' }
})
storageWindow.once('ready-to-show', () => storageWindow?.show())
storageWindow.on('closed', () => {
storageWindow = null
})
}
function bindStoreBroadcast(): void {
store.subscribe((s) => {
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:state:update', s)
}
})
store.onConfig((cfg) => applyConfig(cfg))
}
function readProfileMeta(id: string): { name: string; skinId: string; flavor: string } {
try {
const raw = fs.readFileSync(path.join(HOME, 'data', 'profiles', id, 'profile.json'), 'utf8')
const m = JSON.parse(raw) as { name?: string; skinId?: string; flavor?: string }
return { name: m.name || id, skinId: m.skinId || 'xiaona', flavor: m.flavor || 'chemistry' }
} catch {
return { name: id, skinId: 'xiaona', flavor: 'chemistry' }
}
}
function writeProfileMeta(id: string, meta: { name?: string; skinId?: string; flavor?: string }): void {
const dir = path.join(HOME, 'data', 'profiles', id)
fs.mkdirSync(dir, { recursive: true })
const cur = readProfileMeta(id)
fs.writeFileSync(
path.join(dir, 'profile.json'),
JSON.stringify({ ...cur, ...meta }, null, 2),
'utf8'
)
}
function skinFlavorOf(skinId: string): string {
try {
const m = JSON.parse(fs.readFileSync(path.join(userSkins(), skinId, 'skin.json'), 'utf8'))
return m.flavor === 'normal' ? 'normal' : 'chemistry'
} catch {
return 'chemistry'
}
}
function listProfiles(): Array<{ id: string; name: string; active: boolean; level: string }> {
const dir = path.join(HOME, 'data', 'profiles')
fs.mkdirSync(dir, { recursive: true })
return fs
.readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => {
let level = ''
try {
const raw = fs.readFileSync(path.join(dir, d.name, 'save.json'), 'utf8')
const sv = JSON.parse(raw) as { exp?: number }
const lv = levelOf(sv.exp ?? 0)
const el = elementOf(lv)
level = 'Lv.' + lv + ' · ' + el.symbol + ' ' + el.configSuper
} catch {
level = ''
}
const meta = readProfileMeta(d.name)
return { id: d.name, name: meta.name, active: d.name === profileId, level }
})
}
function loadProfile(id: string): void {
profileId = sanitizeId(id)
store.dispose()
store = new StateStore(profileRoot())
media = new MediaStore(profileRoot())
kb = new KnowledgeBase(profileRoot())
bindStoreBroadcast()
}
function scanSkinsForNew(): boolean {
const root = userSkins()
let changed = false
let entries: fs.Dirent[] = []
try {
entries = fs.readdirSync(root, { withFileTypes: true })
} catch {
return false
}
for (const d of entries) {
if (!d.isDirectory()) continue
const dir = path.join(root, d.name)
if (fs.existsSync(path.join(dir, 'skin.json'))) continue
const modelFile = fs.readdirSync(dir).find((f) => f.endsWith('.model3.json'))
if (!modelFile) continue
const skin = {
id: d.name,
name: d.name,
version: '1.0.0',
flavor: 'normal',
avatar: { type: 'live2d', entry: modelFile, scale: 0.4 },
motions: {},
expressions: {}
}
fs.writeFileSync(path.join(dir, 'skin.json'), JSON.stringify(skin, null, 2), 'utf8')
console.log('[skin] 自动生成预设:', d.name)
changed = true
}
return changed
}
function listSkins(): Array<{ id: string; name: string; active: boolean }> {
const root = userSkins()
const cur = store.getConfig().currentSkin || 'xiaona'
return fs
.readdirSync(root, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => {
let name = d.name
try {
const m = JSON.parse(fs.readFileSync(path.join(root, d.name, 'skin.json'), 'utf8'))
if (m.name) name = m.name
} catch {
/* 用目录名 */
}
return { id: d.name, name, active: cur === d.name }
})
}
function currentFlavor(): string {
const mode = store.getConfig().flavorMode || 'auto'
if (mode === 'chemistry') return 'chemistry'
if (mode === 'normal') return 'normal'
try {
const root = userSkins()
const m = JSON.parse(
fs.readFileSync(path.join(root, store.getConfig().currentSkin || 'xiaona', 'skin.json'), 'utf8')
)
return m.flavor === 'normal' ? 'normal' : 'chemistry'
} catch {
return 'chemistry'
}
}
function positionMenu(): void {
if (!mainWindow || !menuWindow) return
const b = mainWindow.getBounds()
placeWindow(menuWindow, {
x: Math.round(b.x + b.width / 2 - 200),
y: Math.round(b.y + b.height - 388),
width: 400,
height: 380
})
}
function toggleMenu(): void {
if (menuWindow?.isVisible()) hideMenu()
else showMenu()
}
function showMenu(): void {
createMenuWindow()
positionMenu()
menuWindow?.show()
menuWindow?.focus()
positionChatBar()
chatBar?.showInactive()
}
function hideMenu(): void {
menuWindow?.hide()
chatBar?.hide()
}
// ---------------------------------------------------------------- 对话输入条
let chatExpanded = false
function createChatBar(): void {
if (chatBar && !chatBar.isDestroyed()) return
chatBar = new BrowserWindow({
width: 420,
height: 54,
show: false,
frame: false,
transparent: true,
resizable: false,
skipTaskbar: true,
hasShadow: false,
alwaysOnTop: true,
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
raiseWindow(chatBar, true)
chatBar.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: { view: 'chat' }
})
chatBar.once('ready-to-show', () => {
if (menuWindow?.isVisible()) chatBar?.showInactive()
})
chatBar.on('blur', () => {
setTimeout(() => {
const mf = menuWindow?.isFocused() ?? false
const cf = chatBar?.isFocused() ?? false
if (!mf && !cf) hideMenu()
}, 350)
})
chatBar.on('closed', () => {
chatBar = null
})
}
function positionChatBar(): void {
if (!mainWindow || !chatBar) return
const b = mainWindow.getBounds()
const h = chatExpanded ? 274 : 54
placeWindow(chatBar, {
x: Math.round(b.x + b.width / 2 - 210),
y: Math.max(0, b.y - 118) + 54 - h,
width: 420,
height: h
})
}
// ---------------------------------------------------------------- 面板窗口
function createPanel(tab?: string, arg?: string): void {
if (panelWindow && !panelWindow.isDestroyed()) {
panelWindow.show()
panelWindow.focus()
if (tab) panelWindow.webContents.send('pet:panel:navigate', { tab, arg })
return
}
panelWindow = new BrowserWindow({
width: 640,
height: 430,
show: false,
frame: false,
resizable: false,
maximizable: false,
backgroundColor: '#0d1017',
webPreferences: {
preload: path.join(__dirname, '../preload/index.js'),
contextIsolation: true,
nodeIntegration: false,
sandbox: false
}
})
panelWindow.loadFile(path.join(__dirname, '../renderer/index.html'), {
query: tab ? (arg ? { view: 'panel', tab, arg } : { view: 'panel', tab }) : { view: 'panel' }
})
panelWindow.webContents.on('console-message', (_e, _l, msg) => console.log('[panel]', msg))
panelWindow.once('ready-to-show', () => panelWindow?.show())
panelWindow.on('closed', () => {
panelWindow = null
})
// 面板放在宠物左边,避免挡住她
if (capabilities.positionWindows) {
const saved = store.getConfig().panelPos
if (saved) {
panelWindow.setPosition(saved.x, saved.y)
} else if (mainWindow) {
const b = mainWindow.getBounds()
panelWindow.setPosition(Math.max(20, b.x - 420), Math.max(20, b.y - 100))
}
// 原生 Wayland 下窗口位置由合成器决定,记录「移动」没有意义
panelWindow.on('moved', () => {
if (!panelWindow) return
const [x, y] = panelWindow.getPosition()
store.setConfig({ panelPos: { x, y } })
})
}
}
// ---------------------------------------------------------------- 托盘
function createTray(): void {
// Linux 下托盘依赖 StatusNotifierItem(KDE/GNOME 扩展),个别精简桌面可能不可用,
// 失败时不要让整个应用起不来——右键菜单依然可以打开面板/退出。
try {
tray = new Tray(buildTrayIcon())
} catch (err) {
console.warn('[tray] 当前桌面不支持托盘,已跳过:', err)
return
}
tray.setToolTip('小钠 · 桌宠')
tray.setContextMenu(
Menu.buildFromTemplate([
{
label: '打开面板',
click: () => createPanel()
},
{
label: '显示 / 隐藏',
click: () => {
if (!mainWindow) return
if (mainWindow.isVisible()) mainWindow.hide()
else mainWindow.show()
}
},
{ type: 'separator' },
{
label: `数据目录:${HOME}`,
enabled: false
},
{ type: 'separator' },
{
label: '退出',
click: () => {
quitting = true
app.quit()
}
}
])
)
tray.on('click', () => {
if (!mainWindow) return
if (mainWindow.isVisible()) mainWindow.hide()
else mainWindow.show()
})
}
// ---------------------------------------------------------------- IPC
function registerIpc(): void {
ipcMain.on('pet:drag:start', () => startDrag())
ipcMain.on('pet:drag:end', () => stopDrag())
ipcMain.handle('pet:state:get', () => store.snapshot())
ipcMain.handle('pet:action', (_e, name: string, payload?: unknown) => {
const result = store.action(String(name), payload)
if (String(name) === 'use' && result.ok) {
const item = itemById(String(payload))
if (item?.category === 'gift') {
say('(眼睛亮了)这是给我的吗?……谢谢你!(⁄ ⁄•⁄ω⁄•⁄ ⁄)', 6000)
} else if (item?.liked) {
say('(开心地眯起眼)这个我最喜欢了 (๑´ڡ`๑)', 5000)
}
}
if (String(name) === 'sleep' && result.ok) {
const asleep = store.snapshot().sleeping
say(asleep ? '(钻进被窝)我眯一会儿……晚安 (。-ω-)zzz' : '(揉眼睛)唔…我醒了,刚才好像梦到电子飞来飞去', 6000)
}
return result
})
ipcMain.handle('pet:mods:list', () => {
const modsDir = path.join(HOME, 'data', 'mods')
fs.mkdirSync(modsDir, { recursive: true })
return fs.readdirSync(modsDir).filter((n) => n.endsWith('.json'))
})
ipcMain.handle('pet:mods:add', async () => {
const res = await dialog.showOpenDialog({
title: '选择 MOD 文件(.json)',
properties: ['openFile'],
filters: [{ name: 'MOD', extensions: ['json'] }]
})
if (res.canceled || !res.filePaths.length) return { ok: false, message: '已取消', mods: [] }
try {
const src = res.filePaths[0]
const raw = JSON.parse(fs.readFileSync(src, 'utf8')) as ModFile
if (!raw.items && !raw.jobs && !raw.removeItems && !raw.removeJobs) {
return { ok: false, message: '这个 MOD 里没有物品或活动', mods: [] }
}
const modsDir = path.join(HOME, 'data', 'mods')
fs.mkdirSync(modsDir, { recursive: true })
const name = path.basename(src)
fs.copyFileSync(src, path.join(modsDir, name))
return {
ok: true,
message: '已添加 MOD:' + (raw.name || name) + '(重启后生效)',
mods: fs.readdirSync(modsDir).filter((n) => n.endsWith('.json'))
}
} catch (err) {
return { ok: false, message: 'MOD 解析失败:' + String(err), mods: [] }
}
})
ipcMain.handle('pet:mods:remove', (_e, name: string) => {
const modsDir = path.join(HOME, 'data', 'mods')
const target = path.join(modsDir, String(name))
if (target.startsWith(modsDir)) fs.rmSync(target, { force: true })
return fs.readdirSync(modsDir).filter((n) => n.endsWith('.json'))
})
ipcMain.handle('pet:chat:presets', () => store.getAvailablePresets(currentFlavor()))
ipcMain.handle('pet:chat:preset', (_e, id: string) => {
const preset = findPreset(String(id))
if (!preset) return { ok: false, message: '没有这个预设' }
const snap = store.snapshot()
const s = snap.stats
const score = (s.mood + s.electron + s.satiety + s.paraffin) / 4
const pGood =
preset.kind === 'random'
? 0.5
: Math.max(0.15, Math.min(0.85, 0.35 + (score - 50) / 125))
const good = Math.random() < pGood
store.applyChatEffect(good ? preset.good : preset.bad)
store.markPresetUsed(String(id))
const reply = good ? preset.replyGood : preset.replyBad
bubbleStreamStart()
bubbleStreamChunk(reply)
bubbleStreamEnd(reply)
const { presets } = store.getAvailablePresets(currentFlavor())
return {
ok: true,
message: (good ? '🎲 ' : '💧 ') + (good ? preset.good.toast : preset.bad.toast),
reply,
presets: presets.map((p) => ({
id: p.id,
text: p.text,
textNormal: p.textNormal,
kind: p.kind
}))
}
})
ipcMain.handle('pet:bubble:current', () => currentBubble)
ipcMain.handle('pet:llm:get', () => store.maskedLlm())
ipcMain.handle('pet:llm:set', (_e, patch: Record<string, unknown>) => store.setLlm(patch as never))
ipcMain.handle('pet:chat', async (_e, text: string) => {
const t = String(text ?? '').trim().slice(0, 300)
if (!t) return { ok: false, reply: '' }
say('(思考中…)', 1200)
const eff = chatEffect(t)
if (eff) {
store.applyChatEffect(eff)
mainWindow?.webContents.send('pet:toast', eff.toast)
}
bubbleStreamStart()
try {
let reply: string
// 识图 / 看屏幕
const visionM = t.match(/^(?:识图|看看这张图|这张图|这是什么图|看图)/i)
const screenM = t.match(
/^(?:看看屏幕|看下屏幕|看桌面|看看桌面|识别屏幕|识别屏幕文本|屏幕文字|屏幕文本|读屏|屏幕|桌面)/
)
if (visionM || screenM) {
const dataUrl = screenM ? await captureScreenDataUrl() : imageToDataUrl(lastImagePath)
if (!dataUrl) {
reply = screenM
? '(挠头)截不到屏幕诶…… (・_・;)'
: '(歪头)还没有图哦,先把图片拖到我身上,再说「识图」~'
bubbleStreamChunk(reply)
} else {
try {
reply = await chatService.askStream(
'请用桌宠的语气、五句话以内描述你看到的内容,如果图里有文字也读出来',
(chunk) => bubbleStreamChunk(chunk),
'',
dataUrl,
currentFlavor()
)
} catch (err) {
reply = '(小声)这个模型好像不支持看图片……换个支持视觉的模型试试? (´・ω・) '
bubbleStreamChunk(reply)
}
}
bubbleStreamEnd(reply)
return { ok: true, reply }
}
const m = t.match(/^(?:搜索|帮我查|查一下|search)[::\s]+(.+)$/i)
if (m) {
const q = m[1].trim()
const results = await webSearchAll(q)
if (!results) {
reply = '(挠头)没查到诶,网络好像不太配合 (・_・;)'
bubbleStreamChunk(reply)
} else {
reply = await chatService.askStream(
`搜索结果:\n${results}\n\n请用小钠的语气、三句话以内总结回答这个问题:「${q}」`,
(chunk) => bubbleStreamChunk(chunk)
)
}
} else {
const kbCtx = kb.search(t)
reply = await chatService.askStream(
t,
(chunk) => bubbleStreamChunk(chunk),
kbCtx,
'',
currentFlavor()
)
}
// 保存成工作区文件:保存 xxx.md / 写成 xxx.txt
const saveM = t.match(
/(?:保存|写成|写到|创建)[^\n]{0,20}?([\w\u4e00-\u9fa5][\w\u4e00-\u9fa5.-]*\.(?:md|txt|py|js|ts|html|css|cpp|c|java|json))/
)
if (saveM) {
try {
const name = saveM[1].replace(/[\\/:*?"<>|]/g, '_')
const dir = path.join(HOME, 'data', 'workspace')
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(path.join(dir, name), reply, 'utf8')
say(`写好了,放在工作区的「${name}」里 ( ̄▽ ̄)~*`, 6000)
} catch (err) {
console.error('[ws] 保存失败', err)
}
}
bubbleStreamEnd(reply)
return { ok: true, reply, effect: eff?.toast ?? '' }
} catch (err) {
console.error('[llm] 流式失败', err)
const fallback = '(缩了缩)网络好像不太通……等我一下下 (・_・;)'
bubbleStreamChunk(fallback)
bubbleStreamEnd(fallback)
return { ok: false, reply: fallback }
}
})
ipcMain.handle('pet:config:get', () => store.getConfig())
ipcMain.handle('pet:config:set', (_e, patch: Partial<PetConfig>) => store.setConfig(patch))
ipcMain.handle('pet:photos:list', () => media.photos)
ipcMain.handle('pet:photos:import', async () => {
const res = await dialog.showOpenDialog({
title: '导入照片',
properties: ['openFile', 'multiSelections'],
filters: [{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp'] }]
})
if (res.canceled) return media.photos
for (const src of res.filePaths) {
try {
const ext = path.extname(src) || '.png'
const name = `import-${Date.now()}-${Math.floor(Math.random() * 10000)}${ext}`
fs.copyFileSync(src, path.join(media.photoDir, name))
media.addPhoto(name)
} catch (err) {
console.error('[photo] 导入失败', src, err)
}
}
broadcastMedia()
return media.photos
})
ipcMain.handle('pet:photos:capture', async () => {
await capturePhoto()
return media.photos
})
ipcMain.handle('pet:photos:fav', (_e, id: string) => {
media.toggleFavorite(String(id))
broadcastMedia()
return media.photos
})
ipcMain.handle('pet:photos:del', (_e, id: string) => {
media.removePhoto(String(id))
broadcastMedia()
return media.photos
})
ipcMain.handle('pet:photos:cat', (_e, id: string, cat: string) => {
media.setCategory(String(id), String(cat))
broadcastMedia()
return media.photos
})
ipcMain.handle('pet:photos:open', (_e, id: string) => {
const p = media.photos.find((x) => x.id === String(id))
if (p) shell.showItemInFolder(path.join(media.photoDir, p.file))
})
ipcMain.handle('pet:files:list', () => media.files)
ipcMain.handle('pet:files:open', (_e, name: string) => {
const target = path.join(media.fileDir, String(name))
if (target.startsWith(media.fileDir)) void shell.openPath(target)
})
ipcMain.handle('pet:files:del', (_e, name: string) => {
media.removeFile(String(name))
broadcastMedia()
return media.files
})
ipcMain.handle('pet:daily:special', () => {
const sp = dailySpecial()
const item = itemById(sp.itemId)
return { ...sp, name: item?.name ?? '', origin: item?.price ?? 0, claimed: store.snapshot().dailyGiftDay === sp.day }
})
ipcMain.handle('pet:daily:gift', () => store.claimDaily())
ipcMain.handle('pet:birthday:set', (_e, day: string) => store.setBirthday(String(day)))
let elementInfoCache: Record<string, string> = {}
try {
const cachePath = path.join(HOME, 'data', 'element-info.json')
if (fs.existsSync(cachePath)) elementInfoCache = JSON.parse(fs.readFileSync(cachePath, 'utf8'))
} catch {
elementInfoCache = {}
}
ipcMain.handle('pet:element:info', async (_e, z: number, name: string, symbol: string) => {
const key = String(z)
if (elementInfoCache[key]) return { text: elementInfoCache[key], cached: true }
const q = `${name}元素 ${symbol} 物理性质 化学性质 特征`
const raw = await webSearchAll(q)
const text = raw
? raw.replace(/&#?\\w+;/g, ' ').replace(/\\s+/g, ' ').slice(0, 400)
: '(暂时没查到,网络可能不通)'
if (raw) {
elementInfoCache[key] = text
try {
fs.writeFileSync(path.join(HOME, 'data', 'element-info.json'), JSON.stringify(elementInfoCache, null, 2), 'utf8')
} catch {
/* 忽略 */
}
}
return { text, cached: false }
})
ipcMain.handle('pet:icon:import', async () => {
const res = await dialog.showOpenDialog({
title: '选择图标图片',
properties: ['openFile'],
filters: [{ name: '图片', extensions: ['png', 'jpg', 'jpeg', 'gif', 'webp'] }]
})
if (res.canceled || !res.filePaths.length) return ''
try {
const src = res.filePaths[0]
const dir = path.join(HOME, 'data', 'icons')
fs.mkdirSync(dir, { recursive: true })
const ext = path.extname(src) || '.png'
const name = 'icon-' + Date.now() + ext
fs.copyFileSync(src, path.join(dir, name))
return 'img:icons/' + name
} catch (err) {
console.error('[icon] 导入失败', err)
return ''
}
})
ipcMain.handle('pet:catalog:get', () => snapshotCatalog())
ipcMain.handle('pet:catalog:save', (_e, data: unknown) => {
try {
const catalogPath = path.join(HOME, 'data', 'catalog.json')
fs.writeFileSync(catalogPath, JSON.stringify(data, null, 2), 'utf8')
applyCatalog(data as never)
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:catalog:changed')
}
return { ok: true, message: '目录已保存' }
} catch (err) {
console.error('[catalog] 保存失败', err)
return { ok: false, message: '保存失败:' + String(err) }
}
})
ipcMain.on('pet:editor:open', () => createEditorWindow())
ipcMain.handle('pet:daily:buy', () => {
const sp = dailySpecial()
return store.buySpecial(sp.itemId, sp.price)
})
ipcMain.handle('pet:profiles:list', () => listProfiles())
ipcMain.handle('pet:profiles:create', (_e, name: string, skinId: string) => {
const id = sanitizeId(String(name))
const skin = sanitizeId(String(skinId)) || 'xiaona'
fs.mkdirSync(path.join(HOME, 'data', 'profiles', id), { recursive: true })
writeProfileMeta(id, { name: String(name).trim() || id, skinId: skin, flavor: skinFlavorOf(skin) })
return listProfiles()
})
ipcMain.handle('pet:profiles:rename', (_e, id: string, name: string) => {
const pid = sanitizeId(String(id))
writeProfileMeta(pid, { name: String(name).trim() || pid })
if (pid === profileId) store.renamePet(String(name))
return listProfiles()
})
ipcMain.handle('pet:profiles:del', (_e, id: string) => {
const pid = sanitizeId(String(id))
if (pid === profileId) return listProfiles()
const target = path.join(HOME, 'data', 'profiles', pid)
if (target.startsWith(path.join(HOME, 'data', 'profiles'))) {
fs.rmSync(target, { recursive: true, force: true })
}
return listProfiles()
})
ipcMain.handle('pet:profiles:switch', (_e, id: string) => {
const target = path.join(HOME, 'data', 'profiles', sanitizeId(String(id)))
if (!fs.existsSync(target)) return listProfiles()
store.setConfig({ profile: sanitizeId(String(id)) })
try {
const globalCfg = path.join(HOME, 'data', 'config.json')
const existing = fs.existsSync(globalCfg)
? JSON.parse(fs.readFileSync(globalCfg, 'utf8'))
: {}
existing.profile = sanitizeId(String(id))
fs.writeFileSync(globalCfg, JSON.stringify(existing, null, 2), 'utf8')
} catch (err) {
console.error('[profile] 指针写入失败', err)
}
loadProfile(String(id))
store.start()
const meta = readProfileMeta(sanitizeId(String(id)))
store.renamePet(meta.name)
store.setConfig({ currentSkin: meta.skinId })
applyConfig(store.getConfig())
const pname = meta.name || sanitizeId(String(id))
mainWindow?.setTitle(pname)
panelWindow?.setTitle(pname + '-' + lastPanelLabel)
if (storageWindow) storageWindow.setTitle(pname + '-资料库')
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:state:update', store.snapshot())
}
broadcastMedia()
chatService.reset()
return listProfiles()
})
ipcMain.handle('pet:skins:list', () => listSkins())
ipcMain.handle('pet:skins:import', () => {
void shell.openPath(userSkins())
scanSkinsForNew()
return listSkins()
})
ipcMain.handle('pet:skins:import:legacy', async () => {
const res = await dialog.showOpenDialog({
title: '选择 Live2D 模型文件夹(需包含 .model3.json)',
properties: ['openDirectory']
})
if (res.canceled || !res.filePaths.length) return listSkins()
const src = res.filePaths[0]
const modelFile = fs.readdirSync(src).find((f) => f.endsWith('.model3.json'))
if (!modelFile) return listSkins()
const id = sanitizeId(path.basename(src))
const target = path.join(userSkins(), id)
fs.mkdirSync(target, { recursive: true })
for (const f of fs.readdirSync(src)) {
const full = path.join(src, f)
if (fs.statSync(full).isDirectory()) {
fs.cpSync(full, path.join(target, f), { recursive: true })
} else if (/\.(moc3|model3\.json|physics3\.json|cdi3\.json|motion3\.json|exp3\.json|png)$/i.test(f)) {
fs.copyFileSync(full, path.join(target, f))
}
}
const skin = {
id,
name: id,
version: '1.0.0',
flavor: 'normal',
avatar: { type: 'live2d', entry: modelFile, scale: 0.4 },
motions: {},
expressions: {}
}
fs.writeFileSync(path.join(target, 'skin.json'), JSON.stringify(skin, null, 2), 'utf8')
return listSkins()
})
ipcMain.handle('pet:skin:calibrate', (_e, id: string, cal: unknown) => {
const p = path.join(userSkins(), sanitizeId(String(id)), 'skin.json')
try {
const m = JSON.parse(fs.readFileSync(p, 'utf8'))
m.avatar = { ...(m.avatar || {}), calibration: cal }
fs.writeFileSync(p, JSON.stringify(m, null, 2), 'utf8')
console.log('[skin] 校准已保存:', String(id))
} catch (err) {
console.error('[skin] 校准保存失败', err)
}
})
ipcMain.handle('pet:skins:rename', (_e, id: string, name: string) => {
const p = path.join(userSkins(), sanitizeId(String(id)), 'skin.json')
try {
const m = JSON.parse(fs.readFileSync(p, 'utf8'))
m.name = String(name).trim() || m.id
fs.writeFileSync(p, JSON.stringify(m, null, 2), 'utf8')
} catch {
/* 忽略 */
}
return listSkins()
})
ipcMain.handle('pet:skins:switch', (_e, id: string) => {
if (!listSkins().some((s) => s.id === String(id))) return listSkins()
store.setConfig({ currentSkin: String(id) })
applyConfig(store.getConfig())
chatService.reset()
return listSkins()
})
ipcMain.handle('pet:ws:list', () => {
const dir = path.join(HOME, 'data', 'workspace')
fs.mkdirSync(dir, { recursive: true })
return fs.readdirSync(dir).map((name) => ({
name,
size: fs.statSync(path.join(dir, name)).size
}))
})
ipcMain.handle('pet:ws:del', (_e, name: string) => {
const dir = path.join(HOME, 'data', 'workspace')
const target = path.join(dir, String(name))
if (target.startsWith(dir)) fs.rmSync(target, { force: true })
return fs.readdirSync(dir).map((n) => ({ name: n, size: fs.statSync(path.join(dir, n)).size }))
})
ipcMain.handle('pet:ws:open', () => {
const dir = path.join(HOME, 'data', 'workspace')
fs.mkdirSync(dir, { recursive: true })
void shell.openPath(dir)
})
ipcMain.handle('pet:kb:list', () => kb.list())
ipcMain.handle('pet:kb:add', (_e, name: string) => {
const src = path.join(media.fileDir, String(name))
if (src.startsWith(media.fileDir) && fs.existsSync(src)) kb.addFromFile(src)
return kb.list()
})
ipcMain.handle('pet:kb:del', (_e, name: string) => {
kb.remove(String(name))
return kb.list()
})
let lastImagePath = ''
ipcMain.on('pet:file:drop', (_e, src: string) => {
try {
if (!src || !fs.existsSync(src)) return
const base = path.basename(src)
const stored = `${Date.now()}-${base}`
if (/\.(png|jpe?g|gif|webp|bmp)$/i.test(base)) lastImagePath = src
fs.copyFileSync(src, path.join(media.fileDir, stored))
media.addFile(stored, src)
broadcastMedia()
say('(把东西收进抽屉)放好了,要用的时候跟我说~ ( ̄▽ ̄)', 5000)
} catch (err) {
console.error('[file] 收纳失败', err)
}
})
ipcMain.on('pet:event:resolve', (_e, id: string) => {
if (activeEvent?.id === String(id)) {
activeEvent = null
store.applyChatEffect({ mood: 3 })
mainWindow?.webContents.send('pet:event', null)
say('(拍拍胸口)呼……差一点,谢谢你~ ( ̄▽ ̄)', 5000)
}
})
ipcMain.on('pet:bark', (_e, kind: string) => {
if (kind === 'click') {
const b = pickClickBark(barkState, Date.now())
say(barkText(b.id, b.text, currentFlavor()), 4200)
}
})
ipcMain.on('pet:menu:show', () => showMenu())
ipcMain.on('pet:menu:toggle', () => toggleMenu())
ipcMain.on('pet:chat:expand', (_e, open: boolean) => {
chatExpanded = Boolean(open)
positionChatBar()
})
let lastPanelLabel = '面板'
ipcMain.on('pet:panel:title', (e, label: string) => {
const w = BrowserWindow.fromWebContents(e.sender)
if (!w) return
const name = store.snapshot().name || profileId
w.setTitle(name + '-' + String(label))
if (w === panelWindow) lastPanelLabel = String(label)
})
ipcMain.on('pet:storage:open', () => createStorageWindow())
ipcMain.on('pet:music:open', () => createMusicWindow())
ipcMain.on('pet:lyric:open', () => createLyricWindow())
ipcMain.on('pet:lyric:close', () => {
lyricWindow?.close()
})
ipcMain.handle('pet:music:choose', async () => {
const res = await dialog.showOpenDialog({
title: '选择本地音乐文件夹',
properties: ['openDirectory']
})
if (res.canceled || !res.filePaths.length) return scanMusic()
try {
fs.writeFileSync(
musicConfigPath(),
JSON.stringify({ dir: res.filePaths[0] }, null, 2),
'utf8'
)
} catch (err) {
console.error('[music] 保存目录失败', err)
}
const data = scanMusic()
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:music:list', data)
}
return data
})
ipcMain.handle('pet:music:list', () => scanMusic())
ipcMain.handle('pet:music:base', () => (musicServerPort ? 'http://127.0.0.1:' + musicServerPort + '/' : ''))
const playlistPath = () => path.join(HOME, 'data', 'music-playlist.json')
const readPlaylist = (): Array<{ name: string; file: string }> => {
try {
return JSON.parse(fs.readFileSync(playlistPath(), 'utf8')) as Array<{
name: string
file: string
}>
} catch {
return []
}
}
ipcMain.handle('pet:music:playlist', () => readPlaylist())
ipcMain.handle('pet:music:playlist:add', (_e, track: { name: string; file: string }) => {
const list = readPlaylist()
if (!list.some((t) => t.file === track.file)) list.push({ name: track.name, file: track.file })
fs.writeFileSync(playlistPath(), JSON.stringify(list, null, 2), 'utf8')
return list
})
ipcMain.handle('pet:music:playlist:remove', (_e, file: string) => {
const list = readPlaylist().filter((t) => t.file !== String(file))
fs.writeFileSync(playlistPath(), JSON.stringify(list, null, 2), 'utf8')
return list
})
ipcMain.handle('pet:music:lyric', (_e, file: string) => {
try {
const dir = readMusicDir()
if (!dir) return ''
const rel = String(file).replace(MUSIC_EXT, '.lrc')
const p = path.join(dir, rel)
if (!isInside(dir, p)) return ''
if (!fs.existsSync(p)) return ''
return fs.readFileSync(p, 'utf8')
} catch {
return ''
}
})
ipcMain.on('pet:music:now', (_e, payload: unknown) => {
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:music:now', payload)
}
})
ipcMain.on('pet:detail:open', () => createDetailWindow())
ipcMain.on('pet:menu:hide', () => hideMenu())
ipcMain.on('pet:menu:select', (_e, tab: string) => {
hideMenu()
createPanel(String(tab))
})
ipcMain.on('pet:panel:open', (_e, tab?: string, arg?: string) => createPanel(tab || undefined, arg || undefined))
ipcMain.on('pet:panel:close', () => {
panelWindow?.close()
})
ipcMain.on('pet:quit', () => {
quitting = true
app.quit()
})
ipcMain.on('pet:log', (_e, msg: string) => {
console.log('[renderer]', msg)
})
}
// ---------------------------------------------------------------- 拖拽
// 用主进程轮询鼠标屏幕坐标来移动窗口。
// 渲染层的 screenX/clientX 会被页面缩放影响,和 setPosition 的 DIP 不是同一套坐标,
// 直接相减会出现「越拖越偏」的漂移,所以拖拽逻辑完全不经过渲染层坐标。
let dragTimer: NodeJS.Timeout | null = null
let dragStartCursor: [number, number] = [0, 0]
let dragStartWin: [number, number] = [0, 0]
function startDrag(): void {
if (!mainWindow) return
// 原生 Wayland 下既读不到全局光标,也不能由客户端移动窗口,拖拽只能禁用
if (!capabilities.positionWindows || !capabilities.cursor) return
dragStartWin = mainWindow.getPosition() as [number, number]
const p = globalCursor()
if (!p) return
dragStartCursor = [p.x, p.y]
if (dragTimer) clearInterval(dragTimer)
// 30Hz 足够跟手;太快会让 DWM 对透明窗口做拉伸预览,看起来像"缩放"
let lastX = dragStartWin[0]
let lastY = dragStartWin[1]
dragTimer = setInterval(() => {
if (!mainWindow) return
const c = globalCursor()
if (!c) return
const x = Math.round(dragStartWin[0] + (c.x - dragStartCursor[0]))
const y = Math.round(dragStartWin[1] + (c.y - dragStartCursor[1]))
if (x === lastX && y === lastY) return // 没动就不调用,减少无效 setPosition
lastX = x
lastY = y
mainWindow.setPosition(x, y)
positionBubble()
positionChatBar()
if (menuWindow?.isVisible()) positionMenu()
}, 33)
}
function stopDrag(): void {
if (dragTimer) {
clearInterval(dragTimer)
dragTimer = null
}
}
// ---------------------------------------------------------------- 生命周期
const gotLock = app.requestSingleInstanceLock()
if (!gotLock) {
app.quit()
} else {
app.on('second-instance', () => mainWindow?.show())
app.whenReady().then(() => {
console.log('[pet] platform =', platformSummary())
console.log('[pet] home =', HOME)
registerProtocol()
registerIpc()
// KDE/Wayland:用 KWin 脚本桥接真实的全局光标(否则指针离开 X11 窗口后就读不到位置)
startKwinCursorBridge(path.join(bundledDir('kwin'), 'sodiumpet-cursor.js'))
createWindow()
createTray()
applyConfig(store.getConfig())
createChatBar()
setTimeout(() => positionChatBar(), 600)
bindStoreBroadcast()
store.onAchievement((a) => {
say('(举起小牌子)解锁成就:' + a.title + '!', 6000)
})
store.start()
scheduleBarks()
scheduleSuggestions()
scheduleEvents()
startMusicServer()
// 皮肤目录扫描:手动放入的模型自动生成预设
setInterval(() => {
if (!scanSkinsForNew()) return
for (const w of BrowserWindow.getAllWindows()) {
if (!w.isDestroyed()) w.webContents.send('pet:skins:update', listSkins())
}
}, 3000)
// 全屏视线跟随:主进程按 50ms 轮询光标位置,发给宠物窗口
// 原生 Wayland 读不到全局光标,改为只跟随窗口内的鼠标(渲染层已处理)
let lastLookLogAt = 0
if (capabilities.cursor) {
setInterval(() => {
const cfgNow = store.getConfig()
if (!cfgNow.eyeFollow || !mainWindow || !mainWindow.isVisible()) return
const p = globalCursor()
if (!p) return
if (process.env.SODIUM_PET_LOOK_DEBUG === '1') {
const now = Date.now()
if (now - lastLookLogAt > 1000) {
lastLookLogAt = now
console.log('[look] cursor =', p.x, p.y)
}
}
const b = mainWindow.getBounds()
mainWindow.webContents.send('pet:look', {
x: p.x - b.x + cfgNow.cropLeft,
y: p.y - b.y + cfgNow.cropTop
})
}, 50)
}
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
})
app.on('window-all-closed', () => {
// 常驻托盘
})
app.on('before-quit', () => {
quitting = true
store.dispose()
})
}