feat: add mosaic screenshot annotations

This commit is contained in:
2026-07-12 20:40:05 +08:00
parent dd12521be2
commit b82108db38
4 changed files with 535 additions and 21 deletions
+167 -12
View File
@@ -24,7 +24,8 @@ interface Rect {
h: number
}
type Tool = 'pen' | 'rect' | 'ellipse' | 'text'
type Tool = 'pen' | 'rect' | 'ellipse' | 'text' | 'mosaic-brush' | 'mosaic-rect'
type MosaicMode = 'brush' | 'rect'
interface Point {
x: number
y: number
@@ -77,6 +78,8 @@ const activeTool = ref<Tool>('pen')
const activeColor = ref('#ef4444')
const activeStrokeWidth = ref(3)
const activeFontSize = ref(20)
const mosaicMode = ref<MosaicMode>('brush')
const mosaicBrushWidth = ref(24)
const textDraft = ref<{
point: Point
value: string
@@ -104,6 +107,7 @@ const textDragOriginalPoint = ref<Point | null>(null)
const DEFAULT_TEXT_FONT_SIZE = 20
const STROKE_WIDTHS = [2, 4, 6]
const MOSAIC_WIDTHS = [16, 24, 36, 52]
const FONT_SIZES = [16, 20, 28, 36]
const colors = [
@@ -146,17 +150,18 @@ const sizeLabel = computed(() => {
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
})
const MARK_TOOLBAR_W = 178
const MARK_TOOLBAR_W = 212
const ACTION_TOOLBAR_W = 288
const TOOLBAR_GROUP_GAP = 8
const toolOrder: Tool[] = ['pen', 'rect', 'ellipse', 'text']
const toolOrder: Tool[] = ['pen', 'rect', 'ellipse', 'text', 'mosaic-brush', 'mosaic-rect']
const toolSettingsPos = computed(() => {
if (!leftToolbarPos.value || !rect.value || !activeTool.value) return null
const menuW = activeTool.value === 'text' ? 462 : 398
const isMosaic = activeTool.value.startsWith('mosaic-')
const menuW = isMosaic ? (mosaicMode.value === 'brush' ? 328 : 112) : activeTool.value === 'text' ? 462 : 398
const menuH = 58
const buttonIndex = toolOrder.indexOf(activeTool.value)
const buttonIndex = isMosaic ? 4 : toolOrder.indexOf(activeTool.value)
const buttonCenter = 4 + buttonIndex * 34 + 14
let x = leftToolbarPos.value.x
let y = leftToolbarPos.value.y + 44
@@ -432,7 +437,7 @@ function onSelectionMouseDown(e: MouseEvent) {
draftAnnotation.value = {
tool: activeTool.value,
color: activeColor.value,
strokeWidth: activeStrokeWidth.value,
strokeWidth: activeTool.value === 'mosaic-brush' ? mosaicBrushWidth.value : activeStrokeWidth.value,
points: [local],
}
}
@@ -466,7 +471,7 @@ function onMouseMove(e: MouseEvent) {
annotation.points[0] = clampTextLocalPoint(next, annotation)
}
} else if (dragMode.value === 'annotating' && draftAnnotation.value) {
if (activeTool.value === 'pen') {
if (activeTool.value === 'pen' || activeTool.value === 'mosaic-brush') {
draftAnnotation.value.points.push(localPoint(p))
} else {
draftAnnotation.value.points = [
@@ -524,6 +529,19 @@ function selectTool(tool: Tool) {
activeTool.value = tool
}
function selectMosaic() {
activeTool.value = mosaicMode.value === 'brush' ? 'mosaic-brush' : 'mosaic-rect'
}
function chooseMosaicMode(mode: MosaicMode) {
mosaicMode.value = mode
selectMosaic()
}
function chooseMosaicWidth(width: number) {
mosaicBrushWidth.value = width
}
function chooseColor(color: string) {
activeColor.value = color
if (textDraft.value) {
@@ -748,6 +766,13 @@ onUnmounted(() => {
:viewBox="`0 0 ${width} ${height}`"
preserveAspectRatio="none"
>
<defs>
<pattern id="mosaic-preview" width="10" height="10" patternUnits="userSpaceOnUse">
<rect width="10" height="10" fill="rgba(71,85,105,.82)" />
<rect width="5" height="5" fill="rgba(203,213,225,.82)" />
<rect x="5" y="5" width="5" height="5" fill="rgba(148,163,184,.82)" />
</pattern>
</defs>
<path :d="maskPath" fill="rgba(0,0,0,0.45)" fill-rule="evenodd" />
<rect
v-if="rect"
@@ -811,6 +836,25 @@ onUnmounted(() => {
{{ annotation.text }}
</text>
</template>
<polyline
v-else-if="annotation.tool === 'mosaic-brush'"
:points="annotation.points.map((p) => `${p.x},${p.y}`).join(' ')"
stroke="url(#mosaic-preview)"
:stroke-width="annotation.strokeWidth || 24"
stroke-linecap="round"
stroke-linejoin="round"
fill="none"
/>
<rect
v-else-if="annotation.tool === 'mosaic-rect' && annotation.points.length >= 2"
:x="Math.min(annotation.points[0].x, annotation.points[1].x)"
:y="Math.min(annotation.points[0].y, annotation.points[1].y)"
:width="Math.abs(annotation.points[1].x - annotation.points[0].x)"
:height="Math.abs(annotation.points[1].y - annotation.points[0].y)"
fill="url(#mosaic-preview)"
stroke="rgba(255,255,255,.8)"
stroke-width="1"
/>
</g>
</svg>
@@ -922,6 +966,21 @@ onUnmounted(() => {
<path d="M9 19h6" />
</svg>
</button>
<button
class="icon-btn"
:class="{ active: activeTool.startsWith('mosaic-') }"
title="马赛克标记"
aria-label="马赛克标记"
:aria-expanded="activeTool.startsWith('mosaic-')"
@click="selectMosaic"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="4" y="4" width="6" height="6" />
<rect x="14" y="4" width="6" height="6" />
<rect x="4" y="14" width="6" height="6" />
<rect x="14" y="14" width="6" height="6" />
</svg>
</button>
<button
class="icon-btn"
:class="{ muted: annotations.length === 0 }"
@@ -947,7 +1006,55 @@ onUnmounted(() => {
}"
@mousedown.stop
>
<div v-if="activeTool !== 'text'" class="setting-group stroke-group">
<template v-if="activeTool.startsWith('mosaic-')">
<div class="setting-group mosaic-mode-group" role="group" aria-label="马赛克标记方式">
<button
class="mode-choice"
:class="{ active: mosaicMode === 'brush' }"
title="涂抹"
aria-label="涂抹马赛克"
:aria-pressed="mosaicMode === 'brush'"
@click="chooseMosaicMode('brush')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 11V5.5a2 2 0 0 1 4 0V10" />
<path d="M13 10V8a2 2 0 0 1 4 0v3" />
<path d="M17 10a2 2 0 0 1 4 0v4.5c0 4-2.5 6.5-6.5 6.5h-1.2a6 6 0 0 1-4.7-2.3L4 13.2a1.9 1.9 0 0 1 2.8-2.5L9 12.5" />
</svg>
</button>
<button
class="mode-choice"
:class="{ active: mosaicMode === 'rect' }"
title="框选"
aria-label="框选马赛克"
:aria-pressed="mosaicMode === 'rect'"
@click="chooseMosaicMode('rect')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="2.5" y="2.5" width="19" height="19" rx="2" />
<rect class="pixel-block" x="6" y="6" width="4" height="4" rx=".5" />
<rect class="pixel-block" x="14" y="6" width="4" height="4" rx=".5" />
<rect class="pixel-block" x="6" y="14" width="4" height="4" rx=".5" />
<rect class="pixel-block" x="14" y="14" width="4" height="4" rx=".5" />
</svg>
</button>
</div>
<template v-if="mosaicMode === 'brush'">
<div class="settings-divider" />
<span class="setting-label">粗细</span>
<div class="setting-group stroke-group">
<button
v-for="widthValue in MOSAIC_WIDTHS"
:key="widthValue"
class="stroke-choice"
:class="{ active: mosaicBrushWidth === widthValue }"
:title="`${widthValue}px`"
@click="chooseMosaicWidth(widthValue)"
><span :style="{ width: Math.min(22, widthValue / 2) + 'px', height: Math.min(22, widthValue / 2) + 'px' }" /></button>
</div>
</template>
</template>
<div v-else-if="activeTool !== 'text'" class="setting-group stroke-group">
<button
v-for="widthValue in STROKE_WIDTHS"
:key="widthValue"
@@ -971,8 +1078,8 @@ onUnmounted(() => {
{{ size }}
</button>
</div>
<div class="settings-divider" />
<div class="setting-group color-group">
<div v-if="!activeTool.startsWith('mosaic-')" class="settings-divider" />
<div v-if="!activeTool.startsWith('mosaic-')" class="setting-group color-group">
<button
v-for="color in colors"
:key="color"
@@ -1171,7 +1278,7 @@ onUnmounted(() => {
}
.mark-toolbar {
width: 178px;
width: 212px;
}
.action-toolbar {
box-sizing: border-box;
@@ -1183,7 +1290,8 @@ onUnmounted(() => {
.action-btn,
.swatch,
.stroke-choice,
.font-choice {
.font-choice,
.mode-choice {
font-family: inherit;
}
@@ -1341,6 +1449,53 @@ onUnmounted(() => {
background: transparent;
cursor: pointer;
}
.mosaic-mode-group {
gap: 0;
padding: 2px;
border-radius: 7px;
background: #e5e7eb;
}
.mode-choice {
display: grid;
place-items: center;
width: 36px;
min-width: 36px;
height: 30px;
padding: 0;
border: 0;
border-radius: 5px;
color: #475569;
background: transparent;
font-size: 13px;
font-weight: 600;
cursor: pointer;
}
.mode-choice svg {
width: 19px;
height: 19px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.mode-choice svg .pixel-block {
fill: currentColor;
stroke: none;
}
.mode-choice:hover,
.mode-choice.active {
color: #1d4ed8;
background: #fff;
box-shadow: 0 1px 3px rgba(15, 23, 42, 0.14);
}
.setting-label {
position: relative;
z-index: 1;
color: #64748b;
font-size: 12px;
white-space: nowrap;
}
.stroke-choice:hover,
.stroke-choice.active,
.font-choice:hover,
+91
View File
@@ -81,6 +81,10 @@ func ApplyAnnotationsWithScale(pngBytes []byte, annotations []Annotation, scaleX
drawEllipseOutline(dst, ann.Points, scaleX, scaleY, width, c)
case "text":
drawTextAnnotation(dst, ann, scaleX, scaleY, c)
case "mosaic-brush":
applyMosaicBrush(dst, ann.Points, scaleX, scaleY, width)
case "mosaic-rect":
applyMosaicRect(dst, ann.Points, scaleX, scaleY)
}
}
@@ -91,6 +95,93 @@ func ApplyAnnotationsWithScale(pngBytes []byte, annotations []Annotation, scaleX
return buf.Bytes(), nil
}
const mosaicBlockSize = 10
func applyMosaicBrush(img *image.RGBA, points []Point, scaleX, scaleY float64, width int) {
if len(points) == 0 {
return
}
mask := image.NewAlpha(img.Bounds())
maskColor := color.RGBA{A: 255}
if len(points) == 1 {
drawDotMask(mask, scalePoint(points[0], scaleX, scaleY), width, maskColor)
} else {
for i := 1; i < len(points); i++ {
drawMaskLine(mask, scalePoint(points[i-1], scaleX, scaleY), scalePoint(points[i], scaleX, scaleY), width, maskColor)
}
}
applyPixelation(img, img.Bounds(), mask)
}
func applyMosaicRect(img *image.RGBA, points []Point, scaleX, scaleY float64) {
if len(points) < 2 {
return
}
a := scalePoint(points[0], scaleX, scaleY)
b := scalePoint(points[len(points)-1], scaleX, scaleY)
x1, x2 := ordered(a.X, b.X)
y1, y2 := ordered(a.Y, b.Y)
r := image.Rect(int(math.Floor(x1)), int(math.Floor(y1)), int(math.Ceil(x2)), int(math.Ceil(y2))).Intersect(img.Bounds())
applyPixelation(img, r, nil)
}
func applyPixelation(img *image.RGBA, region image.Rectangle, mask *image.Alpha) {
if region.Empty() {
return
}
for y := region.Min.Y; y < region.Max.Y; y += mosaicBlockSize {
for x := region.Min.X; x < region.Max.X; x += mosaicBlockSize {
block := image.Rect(x, y, min(x+mosaicBlockSize, region.Max.X), min(y+mosaicBlockSize, region.Max.Y))
var r, g, b, a, count uint64
for py := block.Min.Y; py < block.Max.Y; py++ {
for px := block.Min.X; px < block.Max.X; px++ {
c := img.RGBAAt(px, py)
r += uint64(c.R)
g += uint64(c.G)
b += uint64(c.B)
a += uint64(c.A)
count++
}
}
if count == 0 {
continue
}
avg := color.RGBA{uint8(r / count), uint8(g / count), uint8(b / count), uint8(a / count)}
for py := block.Min.Y; py < block.Max.Y; py++ {
for px := block.Min.X; px < block.Max.X; px++ {
if mask == nil || mask.AlphaAt(px, py).A > 0 {
img.SetRGBA(px, py, avg)
}
}
}
}
}
}
func drawMaskLine(mask *image.Alpha, a, b Point, width int, c color.RGBA) {
dx, dy := b.X-a.X, b.Y-a.Y
steps := int(math.Max(math.Abs(dx), math.Abs(dy)))
if steps == 0 {
drawDotMask(mask, a, width, c)
return
}
for i := 0; i <= steps; i++ {
t := float64(i) / float64(steps)
drawDotMask(mask, Point{X: a.X + dx*t, Y: a.Y + dy*t}, width, c)
}
}
func drawDotMask(mask *image.Alpha, p Point, width int, c color.RGBA) {
radius := float64(width) / 2
for y := int(math.Floor(p.Y - radius)); y <= int(math.Ceil(p.Y+radius)); y++ {
for x := int(math.Floor(p.X - radius)); x <= int(math.Ceil(p.X+radius)); x++ {
if image.Pt(x, y).In(mask.Bounds()) && math.Hypot(float64(x)-p.X, float64(y)-p.Y) <= radius {
mask.SetAlpha(x, y, color.Alpha{A: c.A})
}
}
}
}
func parseHexColor(hex string) (color.RGBA, error) {
value := strings.TrimPrefix(strings.TrimSpace(hex), "#")
if len(value) != 6 {
+58
View File
@@ -171,3 +171,61 @@ func TestApplyAnnotationsUsesStrokeWidth(t *testing.T) {
t.Fatalf("expected thick rectangle stroke to cover y=24, got %#v", got)
}
}
func TestApplyAnnotationsPixelatesMosaicRectangle(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 40, 30))
for y := 0; y < 30; y++ {
for x := 0; x < 40; x++ {
src.SetRGBA(x, y, color.RGBA{R: uint8(x * 6), G: uint8(y * 8), B: uint8((x + y) * 3), A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, src); err != nil {
t.Fatalf("encode source: %v", err)
}
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
Tool: "mosaic-rect", Points: []Point{{X: 10, Y: 5}, {X: 30, Y: 25}},
}}, 1)
if err != nil {
t.Fatalf("apply annotations: %v", err)
}
img, err := png.Decode(bytes.NewReader(out))
if err != nil {
t.Fatalf("decode output: %v", err)
}
if img.At(12, 7) != img.At(18, 13) {
t.Fatalf("expected pixels in one mosaic block to share a color")
}
if img.At(5, 5) != src.At(5, 5) {
t.Fatalf("expected pixels outside mosaic rectangle to remain unchanged")
}
}
func TestApplyAnnotationsPixelatesOnlyMosaicBrushStroke(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 50, 30))
for y := 0; y < 30; y++ {
for x := 0; x < 50; x++ {
src.SetRGBA(x, y, color.RGBA{R: uint8(x * 5), G: uint8(y * 8), A: 255})
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, src); err != nil {
t.Fatalf("encode source: %v", err)
}
out, err := ApplyAnnotations(buf.Bytes(), []Annotation{{
Tool: "mosaic-brush", StrokeWidth: 12, Points: []Point{{X: 5, Y: 15}, {X: 45, Y: 15}},
}}, 1)
if err != nil {
t.Fatalf("apply annotations: %v", err)
}
img, err := png.Decode(bytes.NewReader(out))
if err != nil {
t.Fatalf("decode output: %v", err)
}
if img.At(12, 15) == src.At(12, 15) {
t.Fatalf("expected brush path to be pixelated")
}
if img.At(12, 2) != src.At(12, 2) {
t.Fatalf("expected pixels outside brush path to remain unchanged")
}
}
+219 -9
View File
@@ -142,8 +142,14 @@ static id nativeOverlayKeyMonitor = nil;
@property(strong) NSColor *activeColor;
@property CGFloat activeStrokeWidth;
@property CGFloat activeFontSize;
@property CGFloat mosaicBrushWidth;
@property NSString *mosaicMode;
@property(strong) NSMutableArray<NSDictionary *> *annotations;
@property(strong) NSMutableDictionary *draftAnnotation;
// A downsampled snapshot of the screen beneath the overlay. Drawing this
// image back at full size with interpolation disabled produces a genuine
// pixel-block preview instead of a translucent placeholder stroke.
@property(strong) NSImage *mosaicPreviewImage;
@property(strong) NSButton *cancelButton;
// Use `clipboardButton` (not `copyButton`) to avoid ARC's "copy" method
// family ownership rule which would otherwise treat the synthesized getter
@@ -159,12 +165,15 @@ static id nativeOverlayKeyMonitor = nil;
@property(strong) NSButton *rectButton;
@property(strong) NSButton *ellipseButton;
@property(strong) NSButton *textButton;
@property(strong) NSButton *mosaicButton;
@property(strong) NSButton *undoButton;
@property(strong) SnipToolSettingsView *toolSettingsView;
@property(strong) NSView *settingsDivider;
@property(strong) NSMutableArray<NSButton *> *strokeSettingButtons;
@property(strong) NSMutableArray<NSButton *> *fontSettingButtons;
@property(strong) NSMutableArray<NSButton *> *colorSettingButtons;
@property(strong) NSMutableArray<NSButton *> *mosaicModeButtons;
@property(strong) NSMutableArray<NSButton *> *mosaicWidthButtons;
@property(strong) NSView *actionToolbarBg;
@property(strong) NSTextField *textEditor;
@property NSPoint textEditorLocalPoint;
@@ -195,6 +204,8 @@ static id nativeOverlayKeyMonitor = nil;
- (void)selectStrokeWidth:(NSButton *)sender;
- (void)selectFontSize:(NSButton *)sender;
- (void)selectToolColor:(NSButton *)sender;
- (void)selectMosaicMode:(NSButton *)sender;
- (void)selectMosaicWidth:(NSButton *)sender;
- (BOOL)isEditingText;
- (void)commitTextEditor;
- (void)cancelTextEditor;
@@ -214,6 +225,8 @@ static id nativeOverlayKeyMonitor = nil;
_activeColor = [NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0];
_activeStrokeWidth = 3.0;
_activeFontSize = 20.0;
_mosaicBrushWidth = 24.0;
_mosaicMode = @"brush";
_annotations = [NSMutableArray array];
_textEditorAnnotationIndex = -1;
_selectedTextAnnotationIndex = -1;
@@ -243,12 +256,15 @@ static id nativeOverlayKeyMonitor = nil;
_rectButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectRect)];
_ellipseButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectEllipse)];
_textButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectText)];
_mosaicButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectMosaic)];
_undoButton = [NSButton buttonWithTitle:@"" target:self action:@selector(undoAnnotation)];
_toolSettingsView = [[SnipToolSettingsView alloc] initWithFrame:NSZeroRect];
_settingsDivider = [[NSView alloc] initWithFrame:NSZeroRect];
_strokeSettingButtons = [NSMutableArray array];
_fontSettingButtons = [NSMutableArray array];
_colorSettingButtons = [NSMutableArray array];
_mosaicModeButtons = [NSMutableArray array];
_mosaicWidthButtons = [NSMutableArray array];
// Dark rounded background container behind the action icon buttons,
// mirroring the look of `.action-toolbar` in the Vue overlay.
_actionToolbarBg = [[NSView alloc] initWithFrame:NSZeroRect];
@@ -262,10 +278,10 @@ static id nativeOverlayKeyMonitor = nil;
// Add the action toolbar background BEFORE the buttons so it sits
// behind them in the view hierarchy (AppKit z-order = subview order).
[self addSubview:_actionToolbarBg];
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _undoButton, _toolSettingsView, _sizeLabel, _hintLabel]) {
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _mosaicButton, _undoButton, _toolSettingsView, _sizeLabel, _hintLabel]) {
[self addSubview:view];
}
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _undoButton, _toolSettingsView, _actionToolbarBg]) {
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _mosaicButton, _undoButton, _toolSettingsView, _actionToolbarBg]) {
[view setHidden:YES];
}
[_sizeLabel setHidden:YES];
@@ -381,6 +397,8 @@ static id nativeOverlayKeyMonitor = nil;
[self styleIconButton:_rectButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M96 96h832v832H96V96z m32 32v768h768V128H128z' fill='white'/></svg>"]];
[self styleIconButton:_ellipseButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M512 928c229.76 0 416-186.24 416-416S741.76 96 512 96 96 282.24 96 512s186.24 416 416 416z m0-32C299.936 896 128 724.064 128 512S299.936 128 512 128s384 171.936 384 384-171.936 384-384 384z' fill='white'/></svg>"]];
[self styleIconButton:_textButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M224 160h576v96H560v608h-96V256H224V160zM384 864h256v64H384v-64z' fill='white'/></svg>"]];
[self styleIconButton:_mosaicButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M128 128h320v320H128V128zm448 0h320v320H576V128zM128 576h320v320H128V576zm448 0h320v320H576V576z' fill='white'/></svg>"]];
[_mosaicButton setToolTip:@"马赛克标记"];
[self styleIconButton:_undoButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><g transform='translate(1024 0) scale(-1 1)'><path d='M838.976 288l-169.344-162.56a16 16 0 1 1 22.144-23.04l213.632 204.992-213.312 215.84a16 16 0 0 1-22.784-22.464L847.936 320H454.56c-164.192 0-297.28 128.96-297.28 288s133.088 288 297.28 288H704v32h-242.784C266.88 928 128 784.736 128 608S266.88 288 461.248 288h377.728z' fill='white'/></g></svg>"]];
[_toolSettingsView setWantsLayer:NO];
@@ -415,6 +433,37 @@ static id nativeOverlayKeyMonitor = nil;
[_toolSettingsView addSubview:button];
}
for (NSUInteger i = 0; i < 2; i++) {
NSButton *button = [NSButton buttonWithTitle:@"" target:self action:@selector(selectMosaicMode:)];
[button setTag:(NSInteger)i];
[button setBordered:NO];
[button setWantsLayer:YES];
[[button layer] setCornerRadius:5];
NSString *svg = i == 0
? @"<svg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><g fill='none' stroke='black' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'><path d='M9 11V5.5a2 2 0 0 1 4 0V10'/><path d='M13 10V8a2 2 0 0 1 4 0v3'/><path d='M17 10a2 2 0 0 1 4 0v4.5c0 4-2.5 6.5-6.5 6.5h-1.2a6 6 0 0 1-4.7-2.3L4 13.2a1.9 1.9 0 0 1 2.8-2.5L9 12.5'/></g></svg>"
: @"<svg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><g fill='none' stroke='black' stroke-width='1.8' stroke-linejoin='round'><rect x='2.5' y='2.5' width='19' height='19' rx='2'/></g><g fill='black'><rect x='6' y='6' width='4' height='4' rx='.5'/><rect x='14' y='6' width='4' height='4' rx='.5'/><rect x='6' y='14' width='4' height='4' rx='.5'/><rect x='14' y='14' width='4' height='4' rx='.5'/></g></svg>";
[button setImage:[self iconFromSVG:svg]];
[button setImagePosition:NSImageOnly];
[button setImageScaling:NSImageScaleProportionallyDown];
NSString *accessibilityLabel = i == 0 ? @"涂抹马赛克" : @"框选马赛克";
[button setToolTip:accessibilityLabel];
[button setAccessibilityLabel:accessibilityLabel];
[_mosaicModeButtons addObject:button];
[_toolSettingsView addSubview:button];
}
for (NSNumber *width in @[@16, @24, @36, @52]) {
NSButton *button = [NSButton buttonWithTitle:@"●" target:self action:@selector(selectMosaicWidth:)];
[button setTag:[width integerValue]];
[button setBordered:NO];
[button setWantsLayer:YES];
[[button layer] setCornerRadius:6];
NSMutableAttributedString *title = [[NSMutableAttributedString alloc] initWithString:@"●"];
[title addAttribute:NSFontAttributeName value:[NSFont systemFontOfSize:MIN(22, 6 + [width doubleValue] / 3) weight:NSFontWeightBold] range:NSMakeRange(0, title.length)];
[button setAttributedTitle:title];
[_mosaicWidthButtons addObject:button];
[_toolSettingsView addSubview:button];
}
NSArray *colors = @[
[NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0],
[NSColor colorWithCalibratedRed:250.0/255.0 green:204.0/255.0 blue:21.0/255.0 alpha:1.0],
@@ -629,6 +678,63 @@ static id nativeOverlayKeyMonitor = nil;
}
continue;
}
if ([tool hasPrefix:@"mosaic-"]) {
[NSGraphicsContext saveGraphicsState];
NSBezierPath *clipPath = nil;
if ([tool isEqualToString:@"mosaic-brush"]) {
clipPath = [NSBezierPath bezierPath];
CGFloat radius = [self strokeWidthForItem:item] / 2.0;
for (NSUInteger i = 0; i < points.count; i++) {
NSPoint local = [points[i] pointValue];
NSPoint p = NSMakePoint(_selection.origin.x + local.x, _selection.origin.y + local.y);
[clipPath appendBezierPathWithOvalInRect:NSMakeRect(p.x - radius, p.y - radius, radius * 2, radius * 2)];
if (i == 0) continue;
NSPoint previousLocal = [points[i - 1] pointValue];
NSPoint previous = NSMakePoint(_selection.origin.x + previousLocal.x, _selection.origin.y + previousLocal.y);
CGFloat dx = p.x - previous.x, dy = p.y - previous.y;
CGFloat length = hypot(dx, dy);
if (length <= 0.001) continue;
CGFloat nx = -dy / length * radius, ny = dx / length * radius;
NSBezierPath *segment = [NSBezierPath bezierPath];
[segment moveToPoint:NSMakePoint(previous.x + nx, previous.y + ny)];
[segment lineToPoint:NSMakePoint(p.x + nx, p.y + ny)];
[segment lineToPoint:NSMakePoint(p.x - nx, p.y - ny)];
[segment lineToPoint:NSMakePoint(previous.x - nx, previous.y - ny)];
[segment closePath];
[clipPath appendBezierPath:segment];
}
} else if (points.count >= 2) {
NSPoint a = [points[0] pointValue], b = [[points lastObject] pointValue];
NSRect r = NSMakeRect(_selection.origin.x + MIN(a.x, b.x), _selection.origin.y + MIN(a.y, b.y), fabs(b.x-a.x), fabs(b.y-a.y));
clipPath = [NSBezierPath bezierPathWithRect:r];
}
if (clipPath != nil) {
[clipPath addClip];
if (_mosaicPreviewImage != nil) {
NSDictionary *hints = @{NSImageHintInterpolation: @(NSImageInterpolationNone)};
[_mosaicPreviewImage drawInRect:self.bounds
fromRect:NSMakeRect(0, 0, _mosaicPreviewImage.size.width, _mosaicPreviewImage.size.height)
operation:NSCompositingOperationCopy
fraction:1.0
respectFlipped:YES
hints:hints];
} else {
// Screen capture can be unavailable before Screen Recording
// permission is granted. A checkerboard fallback still reads
// as pixelation and never resembles a marker stroke.
CGFloat tile = 8.0;
for (CGFloat y = 0; y < self.bounds.size.height; y += tile) {
for (CGFloat x = 0; x < self.bounds.size.width; x += tile) {
BOOL alternate = (((NSInteger)(x / tile) + (NSInteger)(y / tile)) % 2) == 0;
[[NSColor colorWithCalibratedWhite:(alternate ? 0.42 : 0.68) alpha:1.0] setFill];
NSRectFill(NSMakeRect(x, y, tile, tile));
}
}
}
}
[NSGraphicsContext restoreGraphicsState];
continue;
}
[color setStroke];
CGFloat strokeWidth = [self strokeWidthForItem:item];
NSBezierPath *path = [NSBezierPath bezierPath];
@@ -805,7 +911,7 @@ static id nativeOverlayKeyMonitor = nil;
@"tool": _activeTool,
@"color": [self hexForColor:_activeColor],
@"nsColor": _activeColor,
@"strokeWidth": @(_activeStrokeWidth),
@"strokeWidth": @([_activeTool isEqualToString:@"mosaic-brush"] ? _mosaicBrushWidth : _activeStrokeWidth),
@"points": [NSMutableArray arrayWithObject:[NSValue valueWithPoint:local]]
} mutableCopy];
} else if (_hasSelection && NSPointInRect(p, _selection)) {
@@ -869,7 +975,7 @@ static id nativeOverlayKeyMonitor = nil;
} else if (_annotating && _draftAnnotation != nil) {
NSMutableArray *points = _draftAnnotation[@"points"];
NSPoint local = [self localPoint:p];
if ([_activeTool isEqualToString:@"pen"]) {
if ([_activeTool isEqualToString:@"pen"] || [_activeTool isEqualToString:@"mosaic-brush"]) {
[points addObject:[NSValue valueWithPoint:local]];
} else {
if (points.count == 1) {
@@ -939,6 +1045,7 @@ static id nativeOverlayKeyMonitor = nil;
[_rectButton setHidden:!visible];
[_ellipseButton setHidden:!visible];
[_textButton setHidden:!visible];
[_mosaicButton setHidden:!visible];
[_undoButton setHidden:!visible];
[_toolSettingsView setHidden:!visible || _activeTool == nil];
[_sizeLabel setHidden:!visible];
@@ -981,20 +1088,23 @@ static id nativeOverlayKeyMonitor = nil;
// Mark toolbar sits to the LEFT of the action toolbar (same row) with an
// 8px gap between the two groups, so they never overlap on tiny selections.
CGFloat markW = 178;
CGFloat markW = 212;
CGFloat markGap = 8;
CGFloat markX = MAX(0, x - markGap - markW);
[_penButton setFrame:NSMakeRect(markX + 4, y + 4, 28, 28)];
[_rectButton setFrame:NSMakeRect(markX + 38, y + 4, 28, 28)];
[_ellipseButton setFrame:NSMakeRect(markX + 72, y + 4, 28, 28)];
[_textButton setFrame:NSMakeRect(markX + 106, y + 4, 28, 28)];
[_undoButton setFrame:NSMakeRect(markX + 144, y + 4, 28, 28)];
[_mosaicButton setFrame:NSMakeRect(markX + 140, y + 4, 28, 28)];
[_undoButton setFrame:NSMakeRect(markX + 178, y + 4, 28, 28)];
[_undoButton setEnabled:YES];
[[_undoButton layer] setOpacity:_annotations.count > 0 ? 1.0 : 0.35];
if (_activeTool != nil) {
BOOL isText = [_activeTool isEqualToString:@"text"];
CGFloat settingsW = isText ? 462 : 398;
BOOL isMosaic = [_activeTool hasPrefix:@"mosaic-"];
BOOL mosaicBrush = [_mosaicMode isEqualToString:@"brush"];
CGFloat settingsW = isMosaic ? (mosaicBrush ? 304 : 112) : (isText ? 462 : 398);
CGFloat settingsH = 58;
CGFloat settingsX = MAX(8, MIN(markX, self.bounds.size.width - settingsW - 8));
CGFloat settingsY = y + toolbarH + 4;
@@ -1005,6 +1115,7 @@ static id nativeOverlayKeyMonitor = nil;
if ([_activeTool isEqualToString:@"rect"]) activeCenter = markX + 52;
if ([_activeTool isEqualToString:@"ellipse"]) activeCenter = markX + 86;
if ([_activeTool isEqualToString:@"text"]) activeCenter = markX + 120;
if (isMosaic) activeCenter = markX + 154;
[_toolSettingsView setFrame:NSMakeRect(settingsX, settingsY, settingsW, settingsH)];
[_toolSettingsView setArrowX:MAX(18, MIN(activeCenter - settingsX, settingsW - 18))];
[_toolSettingsView setNeedsDisplay:YES];
@@ -1012,21 +1123,34 @@ static id nativeOverlayKeyMonitor = nil;
CGFloat contentY = 18;
CGFloat xCursor = 14;
for (NSButton *button in _strokeSettingButtons) {
[button setHidden:isText];
[button setHidden:isText || isMosaic];
[button setFrame:NSMakeRect(xCursor, contentY, 32, 32)];
xCursor += 42;
}
xCursor = 14;
for (NSButton *button in _fontSettingButtons) {
[button setHidden:!isText];
[button setHidden:!isText || isMosaic];
[button setFrame:NSMakeRect(xCursor, contentY, 40, 32)];
xCursor += 48;
}
for (NSUInteger i = 0; i < _mosaicModeButtons.count; i++) {
NSButton *button = _mosaicModeButtons[i];
[button setHidden:!isMosaic];
[button setFrame:NSMakeRect(14 + i * 38, contentY + 1, 36, 30)];
}
for (NSUInteger i = 0; i < _mosaicWidthButtons.count; i++) {
NSButton *button = _mosaicWidthButtons[i];
[button setHidden:!isMosaic || !mosaicBrush];
[button setFrame:NSMakeRect(122 + i * 42, contentY, 32, 32)];
}
CGFloat groupW = isText ? (4 * 40 + 3 * 8) : (3 * 32 + 2 * 10);
CGFloat dividerX = 14 + groupW + 12;
[_settingsDivider setHidden:isMosaic && !mosaicBrush];
if (isMosaic) dividerX = 102;
[_settingsDivider setFrame:NSMakeRect(dividerX, contentY + 3, 1, 26)];
CGFloat colorX = dividerX + 18;
for (NSButton *button in _colorSettingButtons) {
[button setHidden:isMosaic];
[button setFrame:NSMakeRect(colorX, contentY + 5, 22, 22)];
colorX += 34;
}
@@ -1043,6 +1167,8 @@ static id nativeOverlayKeyMonitor = nil;
: [NSColor clearColor];
[[button layer] setBackgroundColor:[bg CGColor]];
}
BOOL mosaicActive = [_activeTool hasPrefix:@"mosaic-"];
[[_mosaicButton layer] setBackgroundColor:[(mosaicActive ? [NSColor colorWithCalibratedWhite:1.0 alpha:0.14] : [NSColor clearColor]) CGColor]];
[self updateToolSettingsStates];
}
@@ -1070,6 +1196,23 @@ static id nativeOverlayKeyMonitor = nil;
[button setAttributedTitle:title];
}
}
for (NSButton *button in _mosaicModeButtons) {
BOOL active = (button.tag == 0 && [_mosaicMode isEqualToString:@"brush"]) || (button.tag == 1 && [_mosaicMode isEqualToString:@"rect"]);
[self styleButton:button background:(active ? [NSColor whiteColor] : clear) foreground:(active ? activeFg : normalFg)];
if (@available(macOS 10.14, *)) {
[button setContentTintColor:(active ? activeFg : normalFg)];
}
[button setAccessibilityValue:(active ? @"已选择" : @"未选择")];
}
for (NSButton *button in _mosaicWidthButtons) {
BOOL active = fabs((CGFloat)button.tag - _mosaicBrushWidth) < 0.1;
[[button layer] setBackgroundColor:[(active ? activeBg : clear) CGColor]];
NSMutableAttributedString *title = [[button attributedTitle] mutableCopy];
if (title.length > 0) {
[title addAttribute:NSForegroundColorAttributeName value:(active ? activeFg : normalFg) range:NSMakeRange(0, title.length)];
[button setAttributedTitle:title];
}
}
NSString *activeHex = [self hexForColor:_activeColor];
NSArray *colors = objc_getAssociatedObject(_toolSettingsView, "snapgoColors");
@@ -1090,6 +1233,7 @@ static id nativeOverlayKeyMonitor = nil;
- (void)selectRect { [self selectTool:@"rect"]; }
- (void)selectEllipse { [self selectTool:@"ellipse"]; }
- (void)selectText { [self selectTool:@"text"]; }
- (void)selectMosaic { [self selectTool:[_mosaicMode isEqualToString:@"brush"] ? @"mosaic-brush" : @"mosaic-rect"]; }
- (void)undoAnnotation {
if (_annotations.count == 0 && _textEditor == nil) {
return;
@@ -1228,6 +1372,16 @@ static id nativeOverlayKeyMonitor = nil;
[self updateToolSettingsStates];
}
- (void)selectMosaicMode:(NSButton *)sender {
_mosaicMode = sender.tag == 0 ? @"brush" : @"rect";
[self selectMosaic];
}
- (void)selectMosaicWidth:(NSButton *)sender {
_mosaicBrushWidth = MAX(8.0, (CGFloat)sender.tag);
[self updateToolSettingsStates];
}
- (void)selectFontSize:(NSButton *)sender {
_activeFontSize = MAX(8.0, (CGFloat)sender.tag);
if (_textEditor != nil) {
@@ -1421,6 +1575,60 @@ static NSScreen *snipScreenContainingCursor(void) {
return [[NSScreen screens] firstObject];
}
// snipMosaicPreviewImage captures the target display before the transparent
// overlay becomes visible, then downsamples it to one sample per 10 logical
// points. The view scales this tiny image back with nearest-neighbour
// interpolation inside each mosaic mask, yielding stable, screen-derived
// pixel blocks while the pointer is moving.
static NSImage *snipMosaicPreviewImage(NSScreen *screen) {
NSSize fullSize = [screen frame].size;
NSUInteger screenIndex = [[NSScreen screens] indexOfObjectIdenticalTo:screen];
if (screenIndex == NSNotFound) screenIndex = 0;
NSString *temporaryPath = [NSTemporaryDirectory() stringByAppendingPathComponent:
[NSString stringWithFormat:@"snapgo-mosaic-%@.png", [[NSUUID UUID] UUIDString]]];
NSTask *captureTask = [[NSTask alloc] init];
[captureTask setExecutableURL:[NSURL fileURLWithPath:@"/usr/sbin/screencapture"]];
[captureTask setArguments:@[@"-x", @"-D", [NSString stringWithFormat:@"%lu", (unsigned long)screenIndex + 1], temporaryPath]];
NSError *launchError = nil;
if (![captureTask launchAndReturnError:&launchError]) return nil;
[captureTask waitUntilExit];
NSImage *fullImage = [[NSImage alloc] initWithContentsOfFile:temporaryPath];
[[NSFileManager defaultManager] removeItemAtPath:temporaryPath error:nil];
if ([captureTask terminationStatus] != 0 || fullImage == nil) return nil;
NSInteger pixelW = MAX(1, (NSInteger)ceil(fullSize.width / 10.0));
NSInteger pixelH = MAX(1, (NSInteger)ceil(fullSize.height / 10.0));
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:pixelW
pixelsHigh:pixelH
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:0
bitsPerPixel:0];
if (bitmap == nil) return nil;
NSGraphicsContext *context = [NSGraphicsContext graphicsContextWithBitmapImageRep:bitmap];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:context];
[context setImageInterpolation:NSImageInterpolationHigh];
[fullImage drawInRect:NSMakeRect(0, 0, pixelW, pixelH)
fromRect:NSMakeRect(0, 0, fullSize.width, fullSize.height)
operation:NSCompositingOperationCopy
fraction:1.0
respectFlipped:NO
hints:nil];
[context flushGraphics];
[NSGraphicsContext restoreGraphicsState];
NSImage *result = [[NSImage alloc] initWithSize:NSMakeSize(pixelW, pixelH)];
[result addRepresentation:bitmap];
return result;
}
static void snipShowNativeOverlay(int width, int height) {
dispatch_async(dispatch_get_main_queue(), ^{
NSScreen *screen = snipScreenContainingCursor();
@@ -1430,6 +1638,7 @@ static void snipShowNativeOverlay(int width, int height) {
}
NSRect frame = [screen frame];
NSImage *mosaicPreview = snipMosaicPreviewImage(screen);
[NSApp activateIgnoringOtherApps:YES];
nativeOverlayWindow = [[SnipNativeOverlayPanel alloc]
@@ -1450,6 +1659,7 @@ static void snipShowNativeOverlay(int width, int height) {
SnipNativeOverlayView *view = [[SnipNativeOverlayView alloc]
initWithFrame:NSMakeRect(0, 0, frame.size.width, frame.size.height)];
[view setMosaicPreviewImage:mosaicPreview];
[nativeOverlayWindow setContentView:view];
[nativeOverlayWindow makeKeyAndOrderFront:nil];
[nativeOverlayWindow makeFirstResponder:view];