Files
iwb-plugins-desktop/image-annotate/plugin/editor/history.js
T
qiqi 240d02684a feat(image-annotate): v1.15.0 右侧栏「图片调节」11 项 + 快速效果强度修正
用户要「添加基本的图片调节能力到右边栏,同时优化现在的效果,效果现在弱了一些」。

## 图片调节(新 adjust.js,作用于当前位图图层,默认原图)
曝光 ±100(±2EV)/ 明度 / 对比度 / 阴影 / 高光 / 色相 ±180° /
饱和度 / 温度 / 色调 / 锐度 / 清晰度,单行紧凑布局(240px 侧栏 11 项只占约 240px 高)。
拖滑杆实时预览、松手精细、双击归零、右上全部复位。

## 为什么走 getImageData 而不是 ctx.filter
CSS filter 只有 brightness/contrast/saturate/hue-rotate/blur,做不到:
阴影/高光(要按亮度开软蒙版分区)、白平衡(要 R/B、G/M 通道分别增益)、
锐化(要 USM 卷积)。所以只能逐像素。

## 性能:拖动降到 900 长边预览,松手才全量
实测全量耗时(边长 / 像素 / 毫秒):800²/0.6M/6.7 · 1200²/1.4M/12.8 ·
2000²/4.0M/36.8 · 4000²/16M/144.6。
4000×3000 实测:纯调色全量 64ms;叠锐度 287ms;叠清晰度 343ms;
首次(建 source + preview 缓存)256ms。锐度默认 0,不主动拉就不走 USM。

## 两个必须守住的坑(都写成用例了)
1. 不叠加:source 存调节前像素,每次从它重算;每层 sourceCache 另存,切层往返
   也不会拿「调过的像素」当新基准。
2. 撤销后归零:历史只存像素快照、不存调节基准。撤销还原了像素而滑块还停 +80 的话,
   再拖一次就从错误基准算,等于调两遍。规则:撤销一步 = 调整作废、滑块归零、基准重拍。

## 效果强度
「增强」原 brightness(1.12) contrast(1.1) saturate(1.06),截图对比几乎看不出变化 ——
这就是用户说的「效果弱」。改 1.4 / 1.25 / 1.2;「高对比」contrast 1.4 → 1.6。

回归:harness 199 → 208 全通(新增 9 条),validate 9/9。
踩到的用例坑:① 前面效果用例把原图栅格化并隐藏,调色要先用「还原原图」回到单层;
② 历史栈有容量上限,push 到底后「进一条淘汰一条」,长度永远不变,数标签次数才准。
2026-11-09 17:05:23 +08:00

369 lines
13 KiB
JavaScript
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.
/* history.js - 历史快照与撤销/重做
*
* v1.1:快照升级为「完整图层集合」——除了像素,还记录图层的类型、名称、z、
* image/sourceCanvas 引用等元数据。恢复时能删掉后来新增的层、重建被删掉的层,
* 于是「复制/剪切到新层」「还原原图」这类会改变图层数量的操作也能 Ctrl+Z。
* 快照只存在于会话内存里(ImageData / Image 引用都可以直接持有,不需要序列化)。
*
* 约定:快照端 needsPixelSnapshot() 与恢复端 restorePath() 共用 vendor/layer-logic.js,
* 两边判定必须一致,否则会出现「没拍却要读」的像素丢失。
*/
'use strict'
import { S } from './state.js'
import { clearOverlay, updateCropInfo } from './crop.js'
import { hideTextInput, renderObjects } from './objects.js'
import {
createLayerCanvas, purgeVectorCanvases, redrawBitmapLayer,
renderLayerPanel, reorderLayerCanvas, updateLayerCanvasStyles
} from './layers.js'
import { resizeWorkspace, setupCanvas } from './viewport.js'
import { updateAllUI } from './events.js'
import { isDrawableLayer, needsPixelSnapshot, restorePath } from '../vendor/layer-logic.js'
import { toast } from './commands.js'
// ============ 历史快照(所有位图图层 + 矢量对象) ============
export const snapshotStats = { snapshots: 0, getImageDataCalls: 0, bytesWritten: 0 }
/**
* 矢量对象上挂着运行时 DOM 画布(_canvas / _ctx)。JSON 深拷贝会把 canvas
* 序列化成 {},撤销恢复后 reorderLayerCanvas() 就会拿 {} 去 insertBefore →
* "parameter 1 is not of type 'Node'"。快照必须把这些运行时字段剔干净。
*/
function cloneVectors(arr) {
return JSON.parse(JSON.stringify(arr || [], (key, value) => {
if (key === '_canvas' || key === '_ctx') return undefined
return value
}))
}
/**
* 捕获当前状态
* @param {{metaOnly?: boolean}} [opts]
* metaOnly=true:只取几何/矢量/图层元数据,用于拖拽结束时「有没有变化」的比对。
*/
export function snapshotState(opts) {
const metaOnly = !!(opts && opts.metaOnly)
const bitmaps = S.layers.map(layer => {
let data = null
if (!metaOnly && needsPixelSnapshot(layer)) {
try { data = layer.ctx.getImageData(0, 0, S.imgW, S.imgH) } catch (e) { /* ignore */ }
if (data) {
snapshotStats.getImageDataCalls++
snapshotStats.bytesWritten += data.data.byteLength
}
}
return {
id: layer.id,
data,
// ---- 图层重建所需元数据(v1.1)----
name: layer.name,
z: layer.z,
opacity: layer.opacity,
visible: layer.visible,
locked: !!layer.locked,
transformable: !!layer.transformable,
color: layer.color,
lineWidth: layer.lineWidth,
imageRef: layer.image || null,
sourceRef: layer.sourceCanvas || null,
sourceBox: layer._srcBox ? { ...layer._srcBox } : null,
x: layer.x, y: layer.y, w: layer.w, h: layer.h,
rotation: layer.rotation || 0
}
})
snapshotStats.snapshots++
return {
imgW: S.imgW,
imgH: S.imgH,
activeLayerId: S.activeLayerId,
bitmaps,
texts: cloneVectors(S.textLayers),
shapes: cloneVectors(S.shapeLayers),
layerOrder: S.layers.map(l => ({ id: l.id, name: l.name, z: l.z, opacity: l.opacity, visible: l.visible, locked: !!l.locked, x: l.x, y: l.y, w: l.w, h: l.h }))
}
}
export const HISTORY_MAX_ENTRIES = 50
export const HISTORY_MAX_BYTES = 128 * 1024 * 1024
const HISTORY_MIN_BYTES = 32 * 1024 * 1024
export function historyBudgetBytes() {
const px = (S.imgW || 0) * (S.imgH || 0) * 4
if (!px) return HISTORY_MAX_BYTES
return Math.min(HISTORY_MAX_BYTES, Math.max(HISTORY_MIN_BYTES, px * 4))
}
function stateBytes(state) {
let n = 0
if (state && state.bitmaps) {
for (const b of state.bitmaps) {
if (b.data && b.data.data) n += b.data.data.byteLength
}
}
if (state) {
n += state.texts ? JSON.stringify(state.texts).length * 2 : 0
n += state.shapes ? JSON.stringify(state.shapes).length * 2 : 0
}
return n
}
export function pushHistory(stack, state, label) {
state.__bytes = stateBytes(state)
if (label) state.__label = label
stack.push(state)
const budget = historyBudgetBytes()
let total = stack.reduce((sum, s) => sum + (s.__bytes || 0), 0)
while (stack.length > 1 && (stack.length > HISTORY_MAX_ENTRIES || total > budget)) {
total -= stack.shift().__bytes || 0
}
return state
}
/** 操作前调用:压入历史,清空重做栈 */
export function saveSnapshot(label) {
pushHistory(S.history, snapshotState(), label)
S.redoStack = []
}
/** 按快照元数据重建一个已被删除的位图图层 */
function recreateLayer(bm) {
const canvas = createLayerCanvas()
const ctx = canvas.getContext('2d', { willReadFrequently: true })
return {
id: bm.id,
name: bm.name || ('图层 ' + bm.id),
canvas,
ctx,
opacity: bm.opacity == null ? 1 : bm.opacity,
visible: bm.visible !== false,
locked: !!bm.locked,
transformable: !!bm.transformable,
color: bm.color,
lineWidth: bm.lineWidth,
image: bm.imageRef || null,
sourceCanvas: bm.sourceRef || null,
_srcBox: bm.sourceBox || null,
x: bm.x, y: bm.y, w: bm.w, h: bm.h,
rotation: bm.rotation || 0,
z: bm.z || 0
}
}
function releaseLayer(layer) {
try {
if (layer.canvas && layer.canvas.parentNode) layer.canvas.parentNode.removeChild(layer.canvas)
if (layer.canvas) { layer.canvas.width = 0; layer.canvas.height = 0 }
} catch (e) { /* 单个图层释放失败不阻断其余 */ }
}
/** 恢复到指定状态(含图层增删) */
function restoreState(state) {
// v1.2:裁剪也进历史链,所以快照的画布尺寸可能与当前不同,必须先把尺寸复位。
// 尺寸一变,现有图层对象的像素缓冲已被 resizeWorkspace 清空、几何元数据也失效,
// 直接「复用现有图层再 putImageData」会让走过 redraw 路径的图片层彻底丢内容;
// 因此全部释放、让下面的「按快照重建」分支统一重建(它会按 bm 的 imageRef/sourceRef
// 选择 redraw 还是 pixels)。
if (state.imgW && state.imgH && (state.imgW !== S.imgW || state.imgH !== S.imgH)) {
purgeVectorCanvases()
for (const l of S.layers) releaseLayer(l)
S.layers = []
resizeWorkspace(state.imgW, state.imgH)
}
purgeVectorCanvases()
for (const l of S.layers) l._bounds = undefined
const snaps = state.bitmaps || []
const want = new Set(snaps.map(b => b.id))
// ① 删掉「快照里没有」的层(撤销复制/粘贴/选区新层)
for (let i = S.layers.length - 1; i >= 0; i--) {
if (!want.has(S.layers[i].id)) {
releaseLayer(S.layers[i])
S.layers.splice(i, 1)
}
}
// ② 按快照顺序补齐/恢复
const ordered = []
for (const bm of snaps) {
let layer = S.layers.find(l => l.id === bm.id)
if (!layer) {
layer = recreateLayer(bm)
S.layers.push(layer)
if (bm.data) {
try { layer.ctx.putImageData(bm.data, 0, 0) } catch (e) { /* ignore */ }
} else if (restorePath(layer) === 'redraw') {
redrawBitmapLayer(layer)
}
} else {
layer.x = bm.x
layer.y = bm.y
layer.w = bm.w
layer.h = bm.h
layer.locked = !!bm.locked
layer.rotation = bm.rotation || 0
if (isDrawableLayer(layer)) {
layer._srcBox = null
layer.sourceCanvas = null
layer.rotation = 0
layer.x = 0
layer.y = 0
layer.w = S.imgW
layer.h = S.imgH
layer._bounds = undefined
}
if (restorePath(layer) === 'redraw') {
redrawBitmapLayer(layer)
} else if (bm.data) {
try {
layer.ctx.clearRect(0, 0, S.imgW, S.imgH)
layer.ctx.putImageData(bm.data, 0, 0)
} catch (e) { /* ignore */ }
}
}
ordered.push(layer)
}
S.layers = ordered
if (state.layerOrder) {
for (const meta of state.layerOrder) {
const layer = S.layers.find(l => l.id === meta.id)
if (layer) {
layer.name = meta.name
layer.z = meta.z
layer.opacity = meta.opacity == null ? 1 : meta.opacity
layer.visible = meta.visible !== false
}
}
}
if (!S.layers.some(l => l.id === S.activeLayerId)) S.activeLayerId = S.layers.length ? S.layers[S.layers.length - 1].id : null
if (state.activeLayerId && S.layers.some(l => l.id === state.activeLayerId)) S.activeLayerId = state.activeLayerId
S.zCounter = Math.max(S.zCounter, ...S.layers.map(l => l.z || 0), ...(state.texts || []).map(t => t.z || 0), ...(state.shapes || []).map(s => s.z || 0))
S.textLayers = cloneVectors(state.texts)
S.shapeLayers = cloneVectors(state.shapes)
S.selectedTextId = null
S.textDrag = null
S.selectedShapeId = null
S.shapeDrag = null
S.selectedLayerId = null
S.bitmapDrag = null
S.penPath = null
S.penEditId = null
S.layerMulti.length = 0
// 撤销不动选区:选区是「视图状态」,不是像素状态,避免 Ctrl+Z 后框消失还要重画
reorderLayerCanvas()
updateLayerCanvasStyles()
renderObjects()
renderLayerPanel()
updateCropInfo()
}
export function undo() {
if (S.placingImage) return
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.history.length === 0) { toast('没有可撤销的操作'); return }
pushHistory(S.redoStack, snapshotState())
restoreState(S.history.pop())
if (S.onHistoryRestore) S.onHistoryRestore()
if (S.renderAll) S.renderAll()
}
export function redo() {
if (S.placingImage) return
if (S.isDrawing || S.textDrag || S.shapeDrag || S.bitmapDrag) return
if (S.redoStack.length === 0) { toast('没有可重做的操作'); return }
pushHistory(S.history, snapshotState())
restoreState(S.redoStack.pop())
if (S.onHistoryRestore) S.onHistoryRestore()
if (S.renderAll) S.renderAll()
}
/**
* 还原原图(用户 2026-11-04 裁定):清空标注 = 全部还原到刚打开时的状态 ——
* 删掉所有非原图图层、清掉所有绘制/矢量、复位变换与选区,只留「原图」。
* 整步记一个快照,Ctrl+Z 可完整恢复(包括被删的粘贴层与图形)。
* 旧版 resetDraw() 只清像素、留下空白层且清空撤销栈,已废弃。
*/
export function restoreAll() {
if (!S.originalImage) return
const img = S.originalImage
const ow = img.naturalWidth || img.width
const oh = img.naturalHeight || img.height
const sizeChanged = ow !== S.imgW || oh !== S.imgH
// 裁剪会改变画布尺寸且(P2 之前)会清空历史,此路径无法用像素快照回退;
// 明确 toast 告知,不做「假的可撤销」。
if (sizeChanged) {
S.imgW = ow
S.imgH = oh
S.zoom = 1
setupCanvas(img)
S.history = []
S.redoStack = []
clearAllEditState()
updateAllUI()
// 尺寸变了就必须走统一重绘出口:输出摘要/状态栏读 S.imgW/imgH,
// clearAllEditState 只清选区不停止蚂蚁线 rAF(唯一停止点是 renderAll/clearMarquee)
if (S.renderAll) S.renderAll()
toast('已还原为原图(裁剪后的画布尺寸已复位)', 'success')
return
}
saveSnapshot('还原原图')
const base = S.layers.find(l => l.id === 'base')
for (const layer of S.layers) {
if (layer !== base) releaseLayer(layer)
}
if (base) {
base.ctx.clearRect(0, 0, S.imgW, S.imgH)
base.ctx.drawImage(img, 0, 0)
base.locked = true
base.visible = true
base.opacity = 1
base.z = 0
}
S.layers = base ? [base] : []
// 默认无画笔层(用户裁定),活动层回到原图;再画时 ensureWritableLayer 兜底建层
S.activeLayerId = base ? 'base' : null
S.zCounter = 1
clearAllEditState()
if (S.renderAll) S.renderAll()
renderLayerPanel()
hideTextInput()
toast('已还原为原图,Ctrl+Z 可撤销', 'success')
}
function clearAllEditState() {
S.textLayers = []
S.selectedTextId = null
S.textDrag = null
S.textEditingId = null
S.shapeLayers = []
S.selectedShapeId = null
S.shapeDrag = null
S.selectedLayerId = null
S.bitmapDrag = null
S.penPath = null
S.penEditId = null
S.layerMulti.length = 0
S.cropRect = null
S.cropHandle = null
S.cropMoving = false
S.moveStart = null
S.selection = null
S.marquee = null
S.lassoPts = null
S.pickerComposite = null
clearOverlay()
updateCropInfo()
reorderLayerCanvas()
updateLayerCanvasStyles()
renderObjects()
}
/** 兼容旧入口:清空标注按钮 / 更多菜单都指向 restoreAll */
export function resetDraw() { restoreAll() }
export function restoreOriginal() { restoreAll() }