feat: add text annotation tool

This commit is contained in:
2026-07-07 23:49:24 +08:00
parent a15f5b2b78
commit f90612976f
6 changed files with 396 additions and 16 deletions
+114 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
// Inline SVG markup imported as raw strings via Vite's `?raw` suffix.
// Rationale: rendering through v-html lets the icon inherit `currentColor`
// from the toolbar button, so styling stays in CSS without bundling extra
@@ -23,7 +23,7 @@ interface Rect {
h: number
}
type Tool = 'pen' | 'rect' | 'ellipse'
type Tool = 'pen' | 'rect' | 'ellipse' | 'text'
interface Point {
x: number
y: number
@@ -32,6 +32,7 @@ interface Annotation {
tool: Tool
color: string
points: Point[]
text?: string
}
const emit = defineEmits<{
@@ -64,6 +65,8 @@ const draftAnnotation = ref<Annotation | null>(null)
const activeTool = ref<Tool>('pen')
const activeColor = ref('#ef4444')
const paletteOpen = ref(false)
const textDraft = ref<{ point: Point; value: string } | null>(null)
const textInputRef = ref<HTMLInputElement | null>(null)
type ResizeHandle = 'n' | 's' | 'e' | 'w' | 'nw' | 'ne' | 'sw' | 'se'
type DragMode = 'idle' | 'creating' | 'moving' | 'resizing' | 'annotating'
@@ -115,7 +118,7 @@ const sizeLabel = computed(() => {
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
})
const MARK_TOOLBAR_W = 190
const MARK_TOOLBAR_W = 222
const ACTION_TOOLBAR_W = 216
const TOOLBAR_GROUP_GAP = 8
@@ -227,6 +230,7 @@ function hitHandle(p: Point): ResizeHandle | null {
function onMouseDown(e: MouseEvent) {
if (e.button !== 0) return
commitTextDraft()
paletteOpen.value = false
const p = pointFromEvent(e)
const handle = hitHandle(p)
@@ -253,6 +257,10 @@ function onSelectionMouseDown(e: MouseEvent) {
if (e.button !== 0 || !rect.value) return
e.stopPropagation()
paletteOpen.value = false
if (activeTool.value === 'text') {
beginTextAnnotation(localPoint(pointFromEvent(e)))
return
}
if (e.detail >= 2) {
removeSinglePointAnnotation()
onCopy()
@@ -373,6 +381,7 @@ function onSummarize() {
function emitAction(action: 'confirm' | 'copy' | 'save' | 'save-remote' | 'summarize') {
if (!rect.value) return
commitTextDraft()
const payload = {
rect: { ...rect.value },
annotations: annotations.value,
@@ -389,6 +398,13 @@ function onCancel() {
}
function onKeydown(e: KeyboardEvent) {
if (textDraft.value) {
if (e.key === 'Escape') {
e.preventDefault()
cancelTextDraft()
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
onCancel()
@@ -399,6 +415,7 @@ function onKeydown(e: KeyboardEvent) {
}
function undoAnnotation() {
cancelTextDraft()
annotations.value.pop()
}
@@ -409,6 +426,45 @@ function removeSinglePointAnnotation() {
}
}
function beginTextAnnotation(point: Point) {
commitTextDraft()
dragMode.value = 'idle'
draftAnnotation.value = null
textDraft.value = { point, value: '' }
void nextTick(() => {
textInputRef.value?.focus()
textInputRef.value?.select()
})
}
function commitTextDraft() {
if (!textDraft.value) return
const text = textDraft.value.value.trim()
if (text !== '') {
annotations.value.push({
tool: 'text',
color: activeColor.value,
points: [textDraft.value.point],
text,
})
}
textDraft.value = null
}
function cancelTextDraft() {
textDraft.value = null
}
function onTextDraftKeydown(e: KeyboardEvent) {
if (e.key === 'Enter') {
e.preventDefault()
commitTextDraft()
} else if (e.key === 'Escape') {
e.preventDefault()
cancelTextDraft()
}
}
onMounted(() => {
window.addEventListener('keydown', onKeydown)
})
@@ -475,6 +531,17 @@ onUnmounted(() => {
stroke-width="3"
fill="none"
/>
<text
v-else-if="annotation.tool === 'text' && annotation.points.length >= 1"
:x="annotation.points[0].x"
:y="annotation.points[0].y"
:fill="annotation.color"
font-size="20"
font-weight="600"
dominant-baseline="hanging"
>
{{ annotation.text }}
</text>
</g>
</svg>
@@ -490,6 +557,22 @@ onUnmounted(() => {
@mousedown="onSelectionMouseDown"
/>
<input
v-if="rect && textDraft"
ref="textInputRef"
v-model="textDraft.value"
class="text-editor"
:style="{
left: rect.x + textDraft.point.x + 'px',
top: rect.y + textDraft.point.y + 'px',
color: activeColor,
}"
spellcheck="false"
@mousedown.stop
@keydown.stop="onTextDraftKeydown"
@blur="commitTextDraft"
/>
<div
v-for="handle in handles"
:key="handle.name"
@@ -554,6 +637,18 @@ onUnmounted(() => {
<circle cx="12" cy="12" r="7" />
</svg>
</button>
<button
class="icon-btn"
:class="{ active: activeTool === 'text' }"
title="文字标记"
@click="selectTool('text')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 5h14" />
<path d="M12 5v14" />
<path d="M9 19h6" />
</svg>
</button>
<div class="color-wrap">
<button
class="icon-btn color-btn"
@@ -671,6 +766,21 @@ onUnmounted(() => {
cursor: crosshair;
}
.text-editor {
position: absolute;
z-index: 6;
min-width: 120px;
max-width: 320px;
height: 28px;
padding: 2px 6px;
border: 1px solid currentColor;
border-radius: 4px;
outline: none;
background: rgba(15, 23, 42, 0.72);
box-shadow: 0 4px 18px rgba(0, 0, 0, 0.35);
font: 600 20px/1.2 -apple-system, BlinkMacSystemFont, "SF Pro Text", sans-serif;
}
.resize-handle {
position: absolute;
width: 10px;
@@ -725,7 +835,7 @@ onUnmounted(() => {
}
.mark-toolbar {
width: 190px;
width: 222px;
}
.action-toolbar {
width: 216px;
+2
View File
@@ -18,6 +18,7 @@ export namespace application {
tool: string;
color: string;
points: Point[];
text?: string;
static createFrom(source: any = {}) {
return new Annotation(source);
@@ -28,6 +29,7 @@ export namespace application {
this.tool = source["tool"];
this.color = source["color"];
this.points = this.convertValues(source["points"], Point);
this.text = source["text"];
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
+1 -1
View File
@@ -12,6 +12,7 @@ require (
golang.design/x/clipboard v0.7.0
golang.design/x/hotkey v0.4.1
golang.org/x/crypto v0.33.0
golang.org/x/image v0.12.0
)
require (
@@ -52,7 +53,6 @@ require (
github.com/wailsapp/go-webview2 v1.0.22 // indirect
github.com/wailsapp/mimetype v1.4.1 // indirect
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect
golang.org/x/image v0.12.0 // indirect
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect
golang.org/x/net v0.35.0 // indirect
golang.org/x/sys v0.30.0 // indirect
+97
View File
@@ -8,8 +8,15 @@ import (
"image/draw"
"image/png"
"math"
"os"
"strconv"
"strings"
"sync"
xfont "golang.org/x/image/font"
"golang.org/x/image/font/basicfont"
"golang.org/x/image/font/opentype"
"golang.org/x/image/math/fixed"
)
// Annotation describes a user-drawn mark relative to the selected screenshot.
@@ -18,6 +25,7 @@ type Annotation struct {
Tool string `json:"tool"`
Color string `json:"color"`
Points []Point `json:"points"`
Text string `json:"text,omitempty"`
}
type Point struct {
@@ -55,6 +63,8 @@ func ApplyAnnotations(pngBytes []byte, annotations []Annotation, scale float64)
drawRectOutline(dst, ann.Points, scale, width, c)
case "ellipse":
drawEllipseOutline(dst, ann.Points, scale, width, c)
case "text":
drawTextAnnotation(dst, ann, scale, c)
}
}
@@ -180,3 +190,90 @@ func ordered(a, b float64) (float64, float64) {
}
return b, a
}
func drawTextAnnotation(img *image.RGBA, ann Annotation, scale float64, c color.RGBA) {
if len(ann.Points) == 0 {
return
}
text := strings.TrimSpace(ann.Text)
if text == "" {
return
}
face := annotationFontFace(20 * scale)
if face == nil {
face = basicfont.Face7x13
}
origin := scalePoint(ann.Points[0], scale)
metrics := face.Metrics()
lineHeight := metrics.Height
if lineHeight <= 0 {
lineHeight = fixed.I(int(math.Ceil(24 * scale)))
}
d := &xfont.Drawer{
Dst: img,
Src: image.NewUniform(c),
Face: face,
}
baselineY := fixed.I(int(math.Round(origin.Y))) + metrics.Ascent
x := fixed.I(int(math.Round(origin.X)))
for _, line := range strings.Split(text, "\n") {
line = strings.TrimRight(line, "\r")
if line != "" {
d.Dot = fixed.Point26_6{X: x, Y: baselineY}
d.DrawString(line)
}
baselineY += lineHeight
}
}
var (
annotationFontOnce sync.Once
annotationFont *opentype.Font
)
func annotationFontFace(size float64) xfont.Face {
if size <= 0 {
size = 20
}
annotationFontOnce.Do(func() {
annotationFont = loadAnnotationFont()
})
if annotationFont == nil {
return basicfont.Face7x13
}
face, err := opentype.NewFace(annotationFont, &opentype.FaceOptions{
Size: size,
DPI: 72,
Hinting: xfont.HintingFull,
})
if err != nil {
return basicfont.Face7x13
}
return face
}
func loadAnnotationFont() *opentype.Font {
paths := []string{
"/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
"/Library/Fonts/Arial Unicode.ttf",
"/System/Library/Fonts/Hiragino Sans GB.ttc",
"/System/Library/Fonts/PingFang.ttc",
"/System/Library/Fonts/Helvetica.ttc",
}
for _, path := range paths {
data, err := os.ReadFile(path)
if err != nil {
continue
}
if collection, err := opentype.ParseCollection(data); err == nil && collection.NumFonts() > 0 {
if font, err := collection.Font(0); err == nil {
return font
}
}
if font, err := opentype.Parse(data); err == nil {
return font
}
}
return nil
}
+42
View File
@@ -51,3 +51,45 @@ func TestApplyAnnotationsNoAnnotationsReturnsOriginalBytes(t *testing.T) {
t.Fatalf("expected original bytes")
}
}
func TestApplyAnnotationsDrawsTextIntoPNG(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 120, 80))
draw.Draw(src, src.Bounds(), &image.Uniform{C: color.White}, image.Point{}, draw.Src)
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: "text",
Color: "#ef4444",
Points: []Point{
{X: 10, Y: 10},
},
Text: "T",
},
}, 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)
}
found := false
for y := 8; y < 40 && !found; y++ {
for x := 8; x < 40; x++ {
got := color.RGBAModel.Convert(img.At(x, y)).(color.RGBA)
if got.R > 180 && got.G < 180 && got.B < 180 {
found = true
break
}
}
}
if !found {
t.Fatalf("expected red text pixels near annotation point")
}
}
+140 -11
View File
@@ -108,20 +108,28 @@ static id nativeOverlayKeyMonitor = nil;
@property(strong) NSButton *penButton;
@property(strong) NSButton *rectButton;
@property(strong) NSButton *ellipseButton;
@property(strong) NSButton *textButton;
@property(strong) NSButton *colorButton;
@property(strong) NSButton *undoButton;
@property(strong) NSView *paletteView;
@property(strong) NSView *actionToolbarBg;
@property(strong) NSTextField *textEditor;
@property NSPoint textEditorLocalPoint;
@property(strong) NSTextField *sizeLabel;
@property(strong) NSTextField *hintLabel;
- (void)syncControls;
- (void)styleControls;
- (void)selectText;
- (void)confirmSelection;
- (void)copySelection;
- (void)saveSelection;
- (void)saveRemoteSelection;
- (void)summarizeSelection;
- (void)cancelSelection;
- (void)beginTextAnnotationAtPoint:(NSPoint)localPoint;
- (BOOL)isEditingText;
- (void)commitTextEditor;
- (void)cancelTextEditor;
@end
@implementation SnipNativeOverlayView
@@ -158,6 +166,7 @@ static id nativeOverlayKeyMonitor = nil;
_penButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectPen)];
_rectButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectRect)];
_ellipseButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectEllipse)];
_textButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectText)];
_colorButton = [NSButton buttonWithTitle:@"" target:self action:@selector(togglePalette)];
_undoButton = [NSButton buttonWithTitle:@"" target:self action:@selector(undoAnnotation)];
_paletteView = [[NSView alloc] initWithFrame:NSZeroRect];
@@ -174,10 +183,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, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _colorButton, _undoButton, _paletteView, _sizeLabel, _hintLabel]) {
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _colorButton, _undoButton, _paletteView, _sizeLabel, _hintLabel]) {
[self addSubview:view];
}
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _colorButton, _undoButton, _paletteView, _actionToolbarBg]) {
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _colorButton, _undoButton, _paletteView, _actionToolbarBg]) {
[view setHidden:YES];
}
[_sizeLabel setHidden:YES];
@@ -284,6 +293,7 @@ static id nativeOverlayKeyMonitor = nil;
[self styleIconButton:_penButton image:[self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M742.72 752.064c-29.696 28.576-42.976 48.96-42.976 77.12 0 98.4 143.776 142.464 229.728 65.536l-21.344-23.84c-66.976 59.936-176.384 26.4-176.384-41.696 0-16.832 9.28-31.104 33.184-54.08l13.44-12.736c61.024-58.016 75.328-102.72 29.312-179.84-43.84-73.44-96.8-88.288-162.784-50.56-47.232 27.04-68.64 47.456-208.32 190.4-70.624 72.288-153.92 77.088-217.344 26.784-59.712-47.328-79.872-127.36-42.176-188.64 24.512-39.84 62.656-72.896 136.64-124.48 5.952-4.192 27.04-18.816 31.104-21.664 12.16-8.448 21.536-15.104 30.4-21.536 107.552-78.272 140.8-139.136 86.048-219.904-76.992-113.472-202.304-90.016-367.744 61.472l21.6 23.616c153.088-140.224 256.896-159.616 319.68-67.104 41.632 61.408 16.896 106.688-78.4 176.032-8.64 6.304-17.92 12.832-29.888 21.184l-31.136 21.632c-77.504 54.08-117.984 89.184-145.536 133.984-46.784 76.032-22.176 173.664 49.536 230.496 76.224 60.416 177.952 54.56 260.096-29.504 136.16-139.36 158.08-160.224 201.312-184.96 50.656-28.96 84.416-19.52 119.424 39.168 36.896 61.824 27.52 91.392-23.808 140.16 0.096-0.064-10.976 10.368-13.632 12.96z' fill='white'/></svg>"]];
[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:_colorButton image:nil];
[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>"]];
[_paletteView setWantsLayer:YES];
@@ -366,6 +376,19 @@ static id nativeOverlayKeyMonitor = nil;
if (points.count == 0) {
continue;
}
if ([tool isEqualToString:@"text"]) {
NSString *text = item[@"text"];
if (text.length == 0) {
continue;
}
NSPoint p = [points[0] pointValue];
NSDictionary *attrs = @{
NSFontAttributeName: [NSFont systemFontOfSize:20 weight:NSFontWeightSemibold],
NSForegroundColorAttributeName: color ?: [NSColor whiteColor]
};
[text drawAtPoint:NSMakePoint(_selection.origin.x + p.x, _selection.origin.y + p.y) withAttributes:attrs];
continue;
}
[color setStroke];
NSBezierPath *path = [NSBezierPath bezierPath];
[path setLineWidth:3];
@@ -475,9 +498,8 @@ static id nativeOverlayKeyMonitor = nil;
- (void)mouseDown:(NSEvent *)event {
NSPoint p = [self convertPoint:[event locationInWindow] fromView:nil];
if ([event clickCount] == 2 && _hasSelection && NSPointInRect(p, _selection)) {
[self copySelection];
return;
if (_textEditor != nil) {
[self commitTextEditor];
}
NSString *handle = [self resizeHandleAtPoint:p];
if (handle != nil) {
@@ -487,7 +509,23 @@ static id nativeOverlayKeyMonitor = nil;
_annotating = NO;
_resizeHandle = handle;
_resizeStart = _selection;
} else if (_hasSelection && NSPointInRect(p, _selection) && _activeTool != nil) {
[self syncControls];
return;
}
if (_hasSelection && NSPointInRect(p, _selection) && [_activeTool isEqualToString:@"text"]) {
_creating = NO;
_moving = NO;
_resizing = NO;
_annotating = NO;
[self beginTextAnnotationAtPoint:[self localPoint:p]];
[self syncControls];
return;
}
if ([event clickCount] == 2 && _hasSelection && NSPointInRect(p, _selection)) {
[self copySelection];
return;
}
if (_hasSelection && NSPointInRect(p, _selection) && _activeTool != nil) {
_annotating = YES;
_creating = NO;
_moving = NO;
@@ -579,6 +617,16 @@ static id nativeOverlayKeyMonitor = nil;
}
- (void)keyDown:(NSEvent *)event {
if ([self isEditingText]) {
if ([event keyCode] == 53 || [[event charactersIgnoringModifiers] isEqualToString:@"\033"]) {
[self cancelTextEditor];
return;
}
if ([event keyCode] == 36 || [[event charactersIgnoringModifiers] isEqualToString:@"\r"]) {
[self commitTextEditor];
return;
}
}
if ([event keyCode] == 53 || [[event charactersIgnoringModifiers] isEqualToString:@"\033"]) {
[self cancelSelection];
} else if (([event keyCode] == 36 || [[event charactersIgnoringModifiers] isEqualToString:@"\r"]) && _hasSelection) {
@@ -604,6 +652,7 @@ static id nativeOverlayKeyMonitor = nil;
[_penButton setHidden:!visible];
[_rectButton setHidden:!visible];
[_ellipseButton setHidden:!visible];
[_textButton setHidden:!visible];
[_colorButton setHidden:!visible];
[_undoButton setHidden:!visible];
[_sizeLabel setHidden:!visible];
@@ -644,14 +693,15 @@ 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 = 170;
CGFloat markW = 202;
CGFloat markGap = 8;
CGFloat markX = MAX(0, x - markGap - markW);
[_penButton setFrame:NSMakeRect(markX + 4, y + 4, 28, 28)];
[_rectButton setFrame:NSMakeRect(markX + 36, y + 4, 28, 28)];
[_ellipseButton setFrame:NSMakeRect(markX + 68, y + 4, 28, 28)];
[_colorButton setFrame:NSMakeRect(markX + 104, y + 7, 22, 22)];
[_undoButton setFrame:NSMakeRect(markX + 134, y + 4, 28, 28)];
[_textButton setFrame:NSMakeRect(markX + 100, y + 4, 28, 28)];
[_colorButton setFrame:NSMakeRect(markX + 136, y + 7, 22, 22)];
[_undoButton setFrame:NSMakeRect(markX + 166, y + 4, 28, 28)];
[[_colorButton layer] setBackgroundColor:[_activeColor CGColor]];
[_undoButton setEnabled:_annotations.count > 0];
[_paletteView setFrame:NSMakeRect(markX, MAX(0, y - 78), 150, 70)];
@@ -659,7 +709,7 @@ static id nativeOverlayKeyMonitor = nil;
}
- (void)updateToolButtonStates {
NSDictionary *buttons = @{@"pen": _penButton, @"rect": _rectButton, @"ellipse": _ellipseButton};
NSDictionary *buttons = @{@"pen": _penButton, @"rect": _rectButton, @"ellipse": _ellipseButton, @"text": _textButton};
for (NSString *tool in buttons) {
NSButton *button = buttons[tool];
NSColor *bg = [tool isEqualToString:_activeTool]
@@ -676,7 +726,9 @@ static id nativeOverlayKeyMonitor = nil;
- (void)selectPen { [self toggleTool:@"pen"]; }
- (void)selectRect { [self toggleTool:@"rect"]; }
- (void)selectEllipse { [self toggleTool:@"ellipse"]; }
- (void)selectText { [self toggleTool:@"text"]; }
- (void)undoAnnotation {
[self cancelTextEditor];
if (_annotations.count > 0) {
[_annotations removeLastObject];
[self syncControls];
@@ -684,6 +736,68 @@ static id nativeOverlayKeyMonitor = nil;
}
}
- (void)beginTextAnnotationAtPoint:(NSPoint)localPoint {
[self cancelTextEditor];
_textEditorLocalPoint = localPoint;
NSRect frame = NSMakeRect(_selection.origin.x + localPoint.x, _selection.origin.y + localPoint.y, 180, 30);
CGFloat maxX = self.bounds.size.width - frame.size.width - 8;
CGFloat maxY = self.bounds.size.height - frame.size.height - 8;
frame.origin.x = MAX(8, MIN(frame.origin.x, maxX));
frame.origin.y = MAX(8, MIN(frame.origin.y, maxY));
_textEditor = [[NSTextField alloc] initWithFrame:frame];
[_textEditor setBezeled:YES];
[_textEditor setBordered:YES];
[_textEditor setDrawsBackground:YES];
[_textEditor setBackgroundColor:[NSColor colorWithCalibratedWhite:0.08 alpha:0.78]];
[_textEditor setTextColor:_activeColor];
[_textEditor setFont:[NSFont systemFontOfSize:20 weight:NSFontWeightSemibold]];
[_textEditor setFocusRingType:NSFocusRingTypeNone];
[_textEditor setTarget:self];
[_textEditor setAction:@selector(commitTextEditorFromSender:)];
[self addSubview:_textEditor];
[[self window] makeFirstResponder:_textEditor];
}
- (BOOL)isEditingText {
return _textEditor != nil;
}
- (void)commitTextEditorFromSender:(id)sender {
[self commitTextEditor];
}
- (void)commitTextEditor {
if (_textEditor == nil) {
return;
}
NSString *text = [[_textEditor stringValue] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (text.length > 0) {
[_annotations addObject:[@{
@"tool": @"text",
@"color": [self hexForColor:_activeColor],
@"nsColor": _activeColor,
@"points": [NSMutableArray arrayWithObject:[NSValue valueWithPoint:_textEditorLocalPoint]],
@"text": text
} mutableCopy]];
}
[_textEditor removeFromSuperview];
_textEditor = nil;
[[self window] makeFirstResponder:self];
[self syncControls];
[self setNeedsDisplay:YES];
}
- (void)cancelTextEditor {
if (_textEditor == nil) {
return;
}
[_textEditor removeFromSuperview];
_textEditor = nil;
[[self window] makeFirstResponder:self];
[self setNeedsDisplay:YES];
}
- (void)togglePalette {
[_paletteView setHidden:![_paletteView isHidden]];
if (![_paletteView isHidden] && _paletteView.subviews.count == 0) {
@@ -722,6 +836,7 @@ static id nativeOverlayKeyMonitor = nil;
}
- (NSString *)annotationsJSON {
[self commitTextEditor];
NSMutableArray *payload = [NSMutableArray array];
for (NSDictionary *item in _annotations) {
NSMutableArray *points = [NSMutableArray array];
@@ -729,7 +844,12 @@ static id nativeOverlayKeyMonitor = nil;
NSPoint p = [value pointValue];
[points addObject:@{@"x": @(p.x), @"y": @(p.y)}];
}
[payload addObject:@{@"tool": item[@"tool"], @"color": item[@"color"], @"points": points}];
NSMutableDictionary *entry = [@{@"tool": item[@"tool"], @"color": item[@"color"], @"points": points} mutableCopy];
NSString *text = item[@"text"];
if (text.length > 0) {
entry[@"text"] = text;
}
[payload addObject:entry];
}
NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil];
if (data == nil) {
@@ -792,6 +912,7 @@ static id nativeOverlayKeyMonitor = nil;
}
- (void)cancelSelection {
[self cancelTextEditor];
[self closeOverlayWindow];
nativeOverlayCancel();
}
@@ -880,10 +1001,18 @@ static void snipShowNativeOverlay(int width, int height) {
nativeOverlayKeyMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *(NSEvent *event) {
if ([event keyCode] == 53) {
if ([view isEditingText]) {
[view cancelTextEditor];
return nil;
}
[view cancelSelection];
return nil;
}
if ([event keyCode] == 36 && [view hasSelection]) {
if ([view isEditingText]) {
[view commitTextEditor];
return nil;
}
[view confirmSelection];
return nil;
}