截图模块调整
This commit is contained in:
+226
-76
@@ -2,16 +2,11 @@ import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { invoke } from '@tauri-apps/api/core'
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { PhysicalPosition, PhysicalSize } from '@tauri-apps/api/dpi'
|
||||
import { availableMonitors } from '@tauri-apps/api/window'
|
||||
import { listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { emit, listen, type UnlistenFn } from '@tauri-apps/api/event'
|
||||
import { toast } from 'vue-sonner'
|
||||
|
||||
interface CaptureData {
|
||||
pngBase64: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export interface RecentCapture {
|
||||
id: string
|
||||
pngBase64: string
|
||||
@@ -21,104 +16,186 @@ export interface RecentCapture {
|
||||
mode: string
|
||||
}
|
||||
|
||||
export type CaptureMode = 'region' | 'window' | 'fullscreen'
|
||||
/** 截图设置(localStorage 持久化) */
|
||||
export interface ScreenshotSettings {
|
||||
/** 截图完成后自动保存到目录 */
|
||||
autoSave: boolean
|
||||
/** 自动保存目录 */
|
||||
saveDir: string
|
||||
/** 历史记录保留条数 */
|
||||
historyLimit: number
|
||||
/** 全局截图快捷键(空字符串表示禁用) */
|
||||
shortcut: string
|
||||
/** 截图延时(秒),0 表示立即截图 */
|
||||
delay: number
|
||||
}
|
||||
|
||||
const OVERLAY_LABEL = 'screenshot-overlay'
|
||||
const EDITOR_LABEL = 'screenshot-editor'
|
||||
const SETTINGS_KEY = 'screenshot-settings'
|
||||
const DEFAULT_SETTINGS: ScreenshotSettings = {
|
||||
autoSave: false,
|
||||
saveDir: '',
|
||||
historyLimit: 12,
|
||||
shortcut: 'ctrl+alt+a',
|
||||
delay: 0,
|
||||
}
|
||||
|
||||
export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
const capturing = ref(false)
|
||||
const recent = ref<RecentCapture[]>([])
|
||||
let exportUnlisten: UnlistenFn | null = null
|
||||
const settings = ref<ScreenshotSettings>({ ...DEFAULT_SETTINGS })
|
||||
|
||||
/** 计算所有显示器的逻辑像素联合矩形(用于覆盖层窗口定位/尺寸) */
|
||||
async function computeVirtualLogicalRect() {
|
||||
let exportUnlisten: UnlistenFn | null = null
|
||||
let shortcutUnlisten: UnlistenFn | null = null
|
||||
/** 常驻截图覆盖层窗口(启动时创建,之后每次截图复用,避免重复 WebView 初始化) */
|
||||
const OVERLAY_LABEL = 'screenshot-overlay'
|
||||
let overlayWin: WebviewWindow | null = null
|
||||
let overlayReadyResolve: (() => void) | null = null
|
||||
let overlayReadyPromise: Promise<void> | null = null
|
||||
let readyListenerInit = false
|
||||
|
||||
// ===== 设置持久化 =====
|
||||
function loadSettings() {
|
||||
try {
|
||||
const raw = localStorage.getItem(SETTINGS_KEY)
|
||||
if (raw) {
|
||||
const parsed = JSON.parse(raw) as Partial<ScreenshotSettings>
|
||||
settings.value = { ...DEFAULT_SETTINGS, ...parsed }
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 加载设置失败', e)
|
||||
localStorage.removeItem(SETTINGS_KEY)
|
||||
}
|
||||
}
|
||||
|
||||
function saveSettings() {
|
||||
try {
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings.value))
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 保存设置失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
function setSettings(patch: Partial<ScreenshotSettings>) {
|
||||
settings.value = { ...settings.value, ...patch }
|
||||
saveSettings()
|
||||
}
|
||||
|
||||
// ===== 窗口定位 =====
|
||||
/** 计算所有显示器的物理像素联合矩形(覆盖层必须用物理尺寸,保证底图 1:1 与坐标一致) */
|
||||
async function computeVirtualPhysicalRect() {
|
||||
const monitors = await availableMonitors()
|
||||
let minX = Infinity
|
||||
let minY = Infinity
|
||||
let maxX = -Infinity
|
||||
let maxY = -Infinity
|
||||
for (const m of monitors) {
|
||||
const s = m.scaleFactor || 1
|
||||
const lx = m.position.x / s
|
||||
const ly = m.position.y / s
|
||||
const lw = m.size.width / s
|
||||
const lh = m.size.height / s
|
||||
if (lx < minX) minX = lx
|
||||
if (ly < minY) minY = ly
|
||||
if (lx + lw > maxX) maxX = lx + lw
|
||||
if (ly + lh > maxY) maxY = ly + lh
|
||||
}
|
||||
if (!Number.isFinite(minX)) {
|
||||
minX = 0
|
||||
minY = 0
|
||||
maxX = 800
|
||||
maxY = 600
|
||||
if (m.position.x < minX) minX = m.position.x
|
||||
if (m.position.y < minY) minY = m.position.y
|
||||
if (m.position.x + m.size.width > maxX) maxX = m.position.x + m.size.width
|
||||
if (m.position.y + m.size.height > maxY) maxY = m.position.y + m.size.height
|
||||
}
|
||||
if (!Number.isFinite(minX)) return { x: 0, y: 0, width: 800, height: 600 }
|
||||
return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }
|
||||
}
|
||||
|
||||
/** 启动截图:region=区域选择,window=窗口拾取,fullscreen=直接进编辑器 */
|
||||
async function startCapture(mode: CaptureMode) {
|
||||
// ===== 截图流程 =====
|
||||
/** 启动截图:延时倒计时 → 捕获虚拟屏 → 定位常驻覆盖层 → 通知覆盖层开始 */
|
||||
async function startCapture() {
|
||||
if (capturing.value) return
|
||||
capturing.value = true
|
||||
try {
|
||||
// 1. 捕获虚拟屏(覆盖层尚未创建 → 不会出现在截图中)
|
||||
const data = await invoke<CaptureData>('screenshot_capture_fullscreen')
|
||||
|
||||
if (mode === 'fullscreen') {
|
||||
// 全屏截图直接送入编辑器
|
||||
await invoke('screenshot_set_editor_image', { pngBase64: data.pngBase64 })
|
||||
// 清掉静态全屏缓存(编辑器用 cropped/全图,不再需要原始 BGRA)
|
||||
await invoke('screenshot_take_fullscreen').catch(() => {})
|
||||
await openEditor()
|
||||
return
|
||||
await ensureOverlay()
|
||||
// 若覆盖层当前可见(上一次会话未结束),先隐藏再捕获,避免覆盖层自身出现在截图里
|
||||
if (overlayWin) {
|
||||
try {
|
||||
if (await overlayWin.isVisible()) await overlayWin.hide()
|
||||
} catch {
|
||||
/* 窗口可能尚未就绪,忽略 */
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 区域/窗口模式:创建覆盖层选区窗口
|
||||
await openOverlay(mode)
|
||||
// 延时倒计时(>0 时逐秒提示,避免用户错过截图时机)
|
||||
const delaySec = Math.max(0, Math.floor(settings.value.delay || 0))
|
||||
if (delaySec > 0) {
|
||||
for (let i = delaySec; i > 0; i--) {
|
||||
toast(`${i} 秒后开始截图`, { duration: 1000 })
|
||||
await new Promise<void>((r) => setTimeout(r, 1000))
|
||||
}
|
||||
}
|
||||
// 捕获虚拟屏(覆盖层隐藏 → 不会出现在截图中),仅存原始像素,不做 PNG 编码
|
||||
await invoke('screenshot_capture_fullscreen')
|
||||
// 用物理像素把覆盖层对齐到虚拟屏(多显示器/混合 DPI 下保证底图 1:1 与坐标一致)
|
||||
const rect = await computeVirtualPhysicalRect()
|
||||
await overlayWin?.setPosition(new PhysicalPosition(rect.x, rect.y))
|
||||
await overlayWin?.setSize(new PhysicalSize(rect.width, rect.height))
|
||||
await waitOverlayReady()
|
||||
await emit('screenshot-begin')
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 捕获失败', e)
|
||||
toast.error('截图启动失败:' + (e as Error).message)
|
||||
// 失败时清理静态缓存
|
||||
await invoke('screenshot_take_fullscreen').catch(() => {})
|
||||
await invoke('screenshot_clear_fullscreen').catch(() => {})
|
||||
} finally {
|
||||
capturing.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openOverlay(mode: CaptureMode) {
|
||||
const existing = await WebviewWindow.getByLabel(OVERLAY_LABEL)
|
||||
if (existing) await existing.close()
|
||||
|
||||
const rect = await computeVirtualLogicalRect()
|
||||
const url = `index.html#screenshot-overlay?mode=${mode}`
|
||||
new WebviewWindow(OVERLAY_LABEL, {
|
||||
url,
|
||||
title: '截图',
|
||||
x: rect.x,
|
||||
y: rect.y,
|
||||
width: rect.width,
|
||||
height: rect.height,
|
||||
decorations: false,
|
||||
transparent: true,
|
||||
alwaysOnTop: true,
|
||||
skipTaskbar: true,
|
||||
resizable: false,
|
||||
shadow: false,
|
||||
focus: true,
|
||||
visible: true,
|
||||
function resetOverlayReady() {
|
||||
overlayReadyPromise = new Promise<void>((resolve) => {
|
||||
overlayReadyResolve = resolve
|
||||
})
|
||||
}
|
||||
|
||||
async function openEditor() {
|
||||
const existing = await WebviewWindow.getByLabel(EDITOR_LABEL)
|
||||
if (existing) {
|
||||
await existing.show()
|
||||
await existing.setFocus()
|
||||
return
|
||||
/** 等待覆盖层就绪(首次创建时等 onMounted 完成,之后立即返回) */
|
||||
async function waitOverlayReady() {
|
||||
await Promise.race([
|
||||
overlayReadyPromise,
|
||||
new Promise<void>((r) => setTimeout(r, 3000)),
|
||||
])
|
||||
}
|
||||
|
||||
/** 创建常驻覆盖层窗口(隐藏、透明、置顶、无任务栏;启动时创建,复用直到应用退出) */
|
||||
async function ensureOverlay() {
|
||||
if (overlayWin) {
|
||||
const existing = await WebviewWindow.getByLabel(OVERLAY_LABEL).catch(() => null)
|
||||
if (existing) {
|
||||
overlayWin = existing
|
||||
return
|
||||
}
|
||||
overlayWin = null
|
||||
}
|
||||
new WebviewWindow(EDITOR_LABEL, {
|
||||
resetOverlayReady()
|
||||
overlayWin = new WebviewWindow(OVERLAY_LABEL, {
|
||||
url: 'index.html#screenshot-overlay',
|
||||
title: '截图',
|
||||
x: 0,
|
||||
y: 0,
|
||||
width: 800,
|
||||
height: 600,
|
||||
// 必须 true:resizable:false 在 Windows 上会导致 setSize 失效,
|
||||
// 覆盖层无法铺满虚拟屏,选区被 clamp 到初始 800x600 区域(表现为工具栏始终停在左上角)
|
||||
resizable: true,
|
||||
decorations: false,
|
||||
alwaysOnTop: true,
|
||||
skipTaskbar: true,
|
||||
transparent: true,
|
||||
shadow: false,
|
||||
focus: false,
|
||||
visible: false,
|
||||
})
|
||||
}
|
||||
|
||||
/** 初始化:注册覆盖层就绪监听并预创建常驻覆盖层窗口(应用启动时调用) */
|
||||
async function initOverlay() {
|
||||
if (readyListenerInit) return
|
||||
readyListenerInit = true
|
||||
resetOverlayReady()
|
||||
await listen('screenshot-overlay-ready', () => {
|
||||
overlayReadyResolve?.()
|
||||
})
|
||||
await ensureOverlay()
|
||||
}
|
||||
|
||||
async function openEditor() {
|
||||
new WebviewWindow(`screenshot-editor-${Date.now()}`, {
|
||||
url: 'index.html#screenshot-editor',
|
||||
title: '截图编辑器',
|
||||
width: 960,
|
||||
@@ -136,6 +213,7 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 历史 / 导出 =====
|
||||
function addRecent(pngBase64: string, width: number, height: number, mode: string) {
|
||||
recent.value.unshift({
|
||||
id: crypto.randomUUID(),
|
||||
@@ -145,7 +223,12 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
time: Date.now(),
|
||||
mode,
|
||||
})
|
||||
if (recent.value.length > 12) recent.value.pop()
|
||||
const limit = Math.max(1, settings.value.historyLimit)
|
||||
if (recent.value.length > limit) recent.value.length = limit
|
||||
}
|
||||
|
||||
function clearHistory() {
|
||||
recent.value = []
|
||||
}
|
||||
|
||||
async function copyImage(pngBase64: string) {
|
||||
@@ -168,7 +251,26 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
toast.success('已保存到文件')
|
||||
}
|
||||
|
||||
/** 监听编辑器导出事件(主窗口记录历史 + 提示) */
|
||||
/** 覆盖层/编辑器导出处理:记录历史 + 按设置自动保存 */
|
||||
async function handleExport(payload: { pngBase64: string; width: number; height: number }) {
|
||||
const { pngBase64, width, height } = payload
|
||||
addRecent(pngBase64, width, height, 'capture')
|
||||
// 自动保存到指定目录
|
||||
if (settings.value.autoSave && settings.value.saveDir) {
|
||||
const ts = new Date()
|
||||
.toISOString()
|
||||
.replace(/[:.]/g, '-')
|
||||
.slice(0, 19)
|
||||
const path = `${settings.value.saveDir.replace(/\\$/, '')}\\screenshot_${ts}.png`
|
||||
try {
|
||||
await invoke('screenshot_save_png', { pngBase64, path })
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 自动保存失败', e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 监听覆盖层/编辑器导出事件(主窗口记录历史 + 自动保存) */
|
||||
async function initExportListener() {
|
||||
if (exportUnlisten) return
|
||||
exportUnlisten = await listen<{
|
||||
@@ -176,10 +278,41 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
width: number
|
||||
height: number
|
||||
}>('screenshot-exported', (e) => {
|
||||
addRecent(e.payload.pngBase64, e.payload.width, e.payload.height, 'edited')
|
||||
void handleExport(e.payload)
|
||||
})
|
||||
}
|
||||
|
||||
// ===== 全局快捷键 =====
|
||||
/** 监听 Rust 侧 emit 的 'screenshot-shortcut' 事件(快捷键按下时触发) */
|
||||
async function initShortcutListener() {
|
||||
if (shortcutUnlisten) return
|
||||
shortcutUnlisten = await listen('screenshot-shortcut', () => {
|
||||
void startCapture()
|
||||
})
|
||||
}
|
||||
|
||||
/** 应用启动时按已保存的快捷键注册全局热键(支持自定义,默认 Ctrl+Alt+A) */
|
||||
async function initShortcutRegistration() {
|
||||
try {
|
||||
await invoke('screenshot_register_shortcut', { shortcut: settings.value.shortcut })
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 快捷键注册失败', e)
|
||||
}
|
||||
}
|
||||
|
||||
/** 修改快捷键:持久化 + 重新注册(传空字符串禁用) */
|
||||
async function setShortcut(shortcut: string) {
|
||||
const next = shortcut.trim()
|
||||
setSettings({ shortcut: next })
|
||||
try {
|
||||
await invoke('screenshot_register_shortcut', { shortcut: next })
|
||||
return true
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 快捷键注册失败', e)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
function destroyExportListener() {
|
||||
if (exportUnlisten) {
|
||||
exportUnlisten()
|
||||
@@ -187,15 +320,32 @@ export const useScreenshotStore = defineStore('screenshot', () => {
|
||||
}
|
||||
}
|
||||
|
||||
function destroyShortcutListener() {
|
||||
if (shortcutUnlisten) {
|
||||
shortcutUnlisten()
|
||||
shortcutUnlisten = null
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
capturing,
|
||||
recent,
|
||||
settings,
|
||||
startCapture,
|
||||
initOverlay,
|
||||
openEditor,
|
||||
addRecent,
|
||||
clearHistory,
|
||||
copyImage,
|
||||
saveImage,
|
||||
handleExport,
|
||||
loadSettings,
|
||||
setSettings,
|
||||
setShortcut,
|
||||
initExportListener,
|
||||
destroyExportListener,
|
||||
initShortcutListener,
|
||||
initShortcutRegistration,
|
||||
destroyShortcutListener,
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user