feat(app): support to edit screenshot area

- relocate or resize the area
- add anotations on the area
This commit is contained in:
2026-06-01 23:12:54 +08:00
parent ceecbb6af4
commit c45864e44c
9 changed files with 1234 additions and 133 deletions
+40 -4
View File
@@ -4,6 +4,7 @@ package main
import (
"context"
"encoding/json"
"fmt"
"image"
"log/slog"
@@ -43,11 +44,11 @@ type App struct {
// capturing prevents re-entrant capture sessions when the user mashes
// the hotkey while a previous one is still running. It stays true for
// the entire lifecycle of one capture: from overlay start until the
// the entire lifecycle of one capture: from overlay start until the
// overlay is either confirmed (ConfirmRegion) or discarded (CancelRegion).
capturing atomic.Bool
// pendingMu guards `pending`. We keep this separate from `mu` so that
// pendingMu guards `pending`. We keep this separate from `mu` so that
// frontend-triggered RPC handlers (which may run concurrently with the
// capture goroutine) can take it cheaply.
pendingMu sync.Mutex
@@ -80,6 +81,13 @@ type RegionRect struct {
H int `json:"h"`
}
// CaptureResult is returned by the overlay with the final selection and any
// annotations drawn inside the selected area.
type CaptureResult struct {
Rect RegionRect `json:"rect"`
Annotations []application.Annotation `json:"annotations"`
}
// NewApp creates a new App with collaborators already initialised.
func NewApp() *App {
store, err := config.NewFileStore()
@@ -357,7 +365,7 @@ func (a *App) CaptureNow() {
// Returning the error to the frontend lets the overlay decide whether to
// keep showing the screenshot (e.g. for a retry) — currently it just
// dismisses regardless and surfaces the error via the upload:failure toast.
func (a *App) ConfirmRegion(rect RegionRect) error {
func (a *App) ConfirmRegion(result CaptureResult) error {
a.pendingMu.Lock()
pc := a.pending
a.pending = nil
@@ -371,6 +379,7 @@ func (a *App) ConfirmRegion(rect RegionRect) error {
a.dismissOverlay()
}()
rect := result.Rect
captureRect := image.Rect(rect.X, rect.Y, rect.X+rect.W, rect.Y+rect.H)
a.dismissOverlay()
flushFrame()
@@ -380,6 +389,13 @@ func (a *App) ConfirmRegion(rect RegionRect) error {
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
return err
}
if len(result.Annotations) > 0 {
cropped, err = application.ApplyAnnotations(cropped, result.Annotations, pc.Display.Scale)
if err != nil {
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
return err
}
}
if err := a.runUploadPipeline(pc.Provider, cropped); err != nil {
return err
}
@@ -389,7 +405,7 @@ func (a *App) ConfirmRegion(rect RegionRect) error {
// ConfirmNativeRegion mirrors ConfirmRegion for the macOS native overlay.
// The native AppKit panel has already been closed by the time this method is
// called, so we must not dismiss/restore the Wails overlay window here.
func (a *App) ConfirmNativeRegion(rect RegionRect) error {
func (a *App) ConfirmNativeRegion(result CaptureResult) error {
a.pendingMu.Lock()
pc := a.pending
a.pending = nil
@@ -403,6 +419,7 @@ func (a *App) ConfirmNativeRegion(rect RegionRect) error {
hideDockIcon()
}()
rect := result.Rect
captureRect := image.Rect(rect.X, rect.Y, rect.X+rect.W, rect.Y+rect.H)
flushFrame()
cropped, err := a.capturer.CaptureRegion(captureRect)
@@ -410,9 +427,28 @@ func (a *App) ConfirmNativeRegion(rect RegionRect) error {
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
return err
}
if len(result.Annotations) > 0 {
cropped, err = application.ApplyAnnotations(cropped, result.Annotations, pc.Display.Scale)
if err != nil {
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
return err
}
}
return a.runUploadPipeline(pc.Provider, cropped)
}
func parseNativeAnnotations(raw string) []application.Annotation {
if raw == "" {
return nil
}
var annotations []application.Annotation
if err := json.Unmarshal([]byte(raw), &annotations); err != nil {
slog.Warn("parse native annotations failed", "err", err)
return nil
}
return annotations
}
// CancelRegion is invoked when the user dismisses the overlay (Esc /
// Cancel button / right-click). Frees the pending PNG, releases the
// capture lock, and hides the overlay.
+12 -5
View File
@@ -62,17 +62,24 @@ async function retryHotkey() {
}
async function onOverlayConfirm(rect: {
x: number
y: number
w: number
h: number
rect: {
x: number
y: number
w: number
h: number
}
annotations: Array<{
tool: string
color: string
points: Array<{ x: number; y: number }>
}>
}) {
// Optimistically swap back so the window does not visually lag the
// Go-side hide. If upload fails, the toast surfaces the reason.
mode.value = 'settings'
overlayPayload.value = null
try {
await ConfirmRegion(rect)
await ConfirmRegion(rect as any)
} catch {
/* Surfaced via upload:failure */
}
+509 -101
View File
@@ -1,142 +1,322 @@
<script setup lang="ts">
/*
* CaptureOverlay — Snipaste-style region picker.
*
* Three layers, painted in order:
* 1. Dark mask + selection : a single SVG that draws a 0.4 alpha
* black rectangle over the whole screen
* with the selection cut out via fill-rule
* evenodd. The Wails window itself is
* transparent, so the cut-out shows the live
* desktop rather than a stale screenshot.
* 2. Toolbar : floats just outside the bottom-right of
* the selection rectangle (Snipaste rule).
*
* Interaction model (kept minimal per user choice):
* • If no selection yet: mousedown drags out a new rectangle.
* • If selection exists: mousedown INSIDE moves it; OUTSIDE re-drags.
* • Esc / Cancel button → emit('cancel')
* • Enter / Upload button → emit('confirm', rect)
*/
import { computed, onMounted, onUnmounted, ref } from 'vue'
interface Props {
/** Logical (CSS) width of the primary display. */
width: number
/** Logical (CSS) height of the primary display. */
height: number
}
const props = defineProps<Props>()
const emit = defineEmits<{
(e: 'confirm', rect: { x: number; y: number; w: number; h: number }): void
(e: 'cancel'): void
}>()
// Selection rect stored in CSS pixels. null = nothing selected yet.
interface Rect {
x: number
y: number
w: number
h: number
}
type Tool = 'pen' | 'rect' | 'ellipse'
interface Point {
x: number
y: number
}
interface Annotation {
tool: Tool
color: string
points: Point[]
}
const emit = defineEmits<{
(
e: 'confirm',
payload: { rect: Rect; annotations: Annotation[] }
): void
(e: 'cancel'): void
}>()
const rect = ref<Rect | null>(null)
const annotations = ref<Annotation[]>([])
const draftAnnotation = ref<Annotation | null>(null)
const activeTool = ref<Tool>('pen')
const activeColor = ref('#ef4444')
const paletteOpen = ref(false)
// Drag state machine.
type DragMode = 'idle' | 'creating' | 'moving'
type ResizeHandle = 'n' | 's' | 'e' | 'w' | 'nw' | 'ne' | 'sw' | 'se'
type DragMode = 'idle' | 'creating' | 'moving' | 'resizing' | 'annotating'
const dragMode = ref<DragMode>('idle')
// For 'creating': the anchor where mousedown started.
// For 'moving' : the mouse offset relative to the rect's top-left.
const resizeHandle = ref<ResizeHandle | null>(null)
const dragAnchor = ref({ x: 0, y: 0 })
const startRect = ref<Rect | null>(null)
const colors = [
'#ef4444',
'#f97316',
'#facc15',
'#22c55e',
'#06b6d4',
'#3b82f6',
'#8b5cf6',
'#ec4899',
'#ffffff',
'#111827',
]
// SVG path for "the entire screen with the selection rect cut out".
// We rely on fill-rule:evenodd to subtract the inner rectangle.
const maskPath = computed(() => {
const outer = `M0 0 H${props.width} V${props.height} H0 Z`
if (!rect.value) return outer
const r = rect.value
// Inner rect drawn in the OPPOSITE winding order so evenodd cuts it.
const inner = `M${r.x} ${r.y} H${r.x + r.w} V${r.y + r.h} H${r.x} Z`
return outer + ' ' + inner
})
// Toolbar placement: anchor to bottom-right of the selection, but shove
// it to the inside top-right if the selection is too close to the screen
// edge to keep the buttons visible.
const TOOLBAR_W = 220
const TOOLBAR_H = 40
const GAP = 8
const toolbarPos = computed(() => {
if (!rect.value) return null
const r = rect.value
let x = r.x + r.w - TOOLBAR_W
let y = r.y + r.h + GAP
if (y + TOOLBAR_H > props.height) {
// No room below: put it inside the selection's bottom-right.
y = r.y + r.h - TOOLBAR_H - GAP
}
if (x < 0) x = 0
if (x + TOOLBAR_W > props.width) x = props.width - TOOLBAR_W
return { x, y }
const allAnnotations = computed(() => {
return draftAnnotation.value
? [...annotations.value, draftAnnotation.value]
: annotations.value
})
const insideRect = (px: number, py: number, r: Rect | null) => {
const selectionAnnotations = computed(() => {
if (!rect.value) return []
return allAnnotations.value.map((annotation) => ({
...annotation,
points: annotation.points.map((point) => ({
x: rect.value!.x + point.x,
y: rect.value!.y + point.y,
})),
}))
})
const sizeLabel = computed(() => {
if (!rect.value) return ''
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
})
const rightToolbarPos = computed(() => {
if (!rect.value) return null
return placeToolbar(rect.value, 220, 40, 'right')
})
const leftToolbarPos = computed(() => {
if (!rect.value) return null
return placeToolbar(rect.value, 190, 40, 'left')
})
const handles = computed(() => {
if (!rect.value) return []
const r = rect.value
const cx = r.x + r.w / 2
const cy = r.y + r.h / 2
return [
{ name: 'nw', x: r.x, y: r.y },
{ name: 'n', x: cx, y: r.y },
{ name: 'ne', x: r.x + r.w, y: r.y },
{ name: 'e', x: r.x + r.w, y: cy },
{ name: 'se', x: r.x + r.w, y: r.y + r.h },
{ name: 's', x: cx, y: r.y + r.h },
{ name: 'sw', x: r.x, y: r.y + r.h },
{ name: 'w', x: r.x, y: cy },
] as Array<{ name: ResizeHandle; x: number; y: number }>
})
function placeToolbar(
r: Rect,
toolbarW: number,
toolbarH: number,
side: 'left' | 'right'
) {
const gap = 8
let x =
side === 'right'
? r.x + r.w - toolbarW
: r.x
let y = r.y + r.h + gap
if (y + toolbarH > props.height) {
y = r.y + r.h - toolbarH - gap
}
x = clamp(x, 0, props.width - toolbarW)
return { x, y }
}
function clamp(value: number, min: number, max: number) {
return Math.max(min, Math.min(value, max))
}
function normalizeRect(a: Point, b: Point): Rect {
return {
x: clamp(Math.min(a.x, b.x), 0, props.width),
y: clamp(Math.min(a.y, b.y), 0, props.height),
w: Math.abs(b.x - a.x),
h: Math.abs(b.y - a.y),
}
}
function pointFromEvent(e: MouseEvent): Point {
return {
x: clamp(e.clientX, 0, props.width),
y: clamp(e.clientY, 0, props.height),
}
}
function localPoint(p: Point) {
if (!rect.value) return p
return {
x: clamp(p.x - rect.value.x, 0, rect.value.w),
y: clamp(p.y - rect.value.y, 0, rect.value.h),
}
}
function insideRect(p: Point, r: Rect | null) {
if (!r) return false
return px >= r.x && px <= r.x + r.w && py >= r.y && py <= r.y + r.h
return p.x >= r.x && p.x <= r.x + r.w && p.y >= r.y && p.y <= r.y + r.h
}
function hitHandle(p: Point): ResizeHandle | null {
if (!rect.value) return null
const tolerance = 9
for (const handle of handles.value) {
if (
Math.abs(p.x - handle.x) <= tolerance &&
Math.abs(p.y - handle.y) <= tolerance
) {
return handle.name
}
}
const r = rect.value
const nearX = p.x >= r.x - tolerance && p.x <= r.x + r.w + tolerance
const nearY = p.y >= r.y - tolerance && p.y <= r.y + r.h + tolerance
if (nearX && Math.abs(p.y - r.y) <= tolerance) return 'n'
if (nearX && Math.abs(p.y - (r.y + r.h)) <= tolerance) return 's'
if (nearY && Math.abs(p.x - r.x) <= tolerance) return 'w'
if (nearY && Math.abs(p.x - (r.x + r.w)) <= tolerance) return 'e'
return null
}
function onMouseDown(e: MouseEvent) {
if (e.button !== 0) return
const px = e.clientX
const py = e.clientY
if (rect.value && insideRect(px, py, rect.value)) {
// Move existing selection.
paletteOpen.value = false
const p = pointFromEvent(e)
const handle = hitHandle(p)
if (handle && rect.value) {
dragMode.value = 'resizing'
resizeHandle.value = handle
dragAnchor.value = p
startRect.value = { ...rect.value }
return
}
if (rect.value && insideRect(p, rect.value)) {
dragMode.value = 'moving'
dragAnchor.value = { x: px - rect.value.x, y: py - rect.value.y }
} else {
// Start a new selection.
dragMode.value = 'creating'
dragAnchor.value = { x: px, y: py }
rect.value = { x: px, y: py, w: 0, h: 0 }
dragAnchor.value = { x: p.x - rect.value.x, y: p.y - rect.value.y }
return
}
dragMode.value = 'creating'
dragAnchor.value = p
rect.value = { x: p.x, y: p.y, w: 0, h: 0 }
annotations.value = []
draftAnnotation.value = null
}
function onSelectionMouseDown(e: MouseEvent) {
if (e.button !== 0 || !rect.value) return
e.stopPropagation()
paletteOpen.value = false
const p = pointFromEvent(e)
const handle = hitHandle(p)
if (handle) {
dragMode.value = 'resizing'
resizeHandle.value = handle
dragAnchor.value = p
startRect.value = { ...rect.value }
return
}
dragMode.value = 'annotating'
const local = localPoint(p)
draftAnnotation.value = {
tool: activeTool.value,
color: activeColor.value,
points: [local],
}
}
function onMouseMove(e: MouseEvent) {
if (dragMode.value === 'idle') return
const px = e.clientX
const py = e.clientY
const p = pointFromEvent(e)
if (dragMode.value === 'creating') {
const ax = dragAnchor.value.x
const ay = dragAnchor.value.y
rect.value = {
x: Math.min(ax, px),
y: Math.min(ay, py),
w: Math.abs(px - ax),
h: Math.abs(py - ay),
}
rect.value = normalizeRect(dragAnchor.value, p)
} else if (dragMode.value === 'moving' && rect.value) {
let nx = px - dragAnchor.value.x
let ny = py - dragAnchor.value.y
// Clamp inside the screen so the selection cannot be dragged off-canvas.
nx = Math.max(0, Math.min(nx, props.width - rect.value.w))
ny = Math.max(0, Math.min(ny, props.height - rect.value.h))
rect.value = { ...rect.value, x: nx, y: ny }
rect.value = {
...rect.value,
x: clamp(p.x - dragAnchor.value.x, 0, props.width - rect.value.w),
y: clamp(p.y - dragAnchor.value.y, 0, props.height - rect.value.h),
}
} else if (dragMode.value === 'resizing') {
resizeSelection(p)
} else if (dragMode.value === 'annotating' && draftAnnotation.value) {
if (activeTool.value === 'pen') {
draftAnnotation.value.points.push(localPoint(p))
} else {
draftAnnotation.value.points = [
draftAnnotation.value.points[0],
localPoint(p),
]
}
}
}
function onMouseUp() {
if (dragMode.value === 'creating' && rect.value) {
// Discard zero/tiny selections — the user probably clicked accidentally.
if (rect.value.w < 4 || rect.value.h < 4) {
rect.value = null
}
}
if (dragMode.value === 'annotating' && draftAnnotation.value) {
if (draftAnnotation.value.points.length > 0) {
annotations.value.push(draftAnnotation.value)
}
draftAnnotation.value = null
}
dragMode.value = 'idle'
resizeHandle.value = null
startRect.value = null
}
function resizeSelection(p: Point) {
if (!startRect.value || !resizeHandle.value) return
const r = startRect.value
let left = r.x
let top = r.y
let right = r.x + r.w
let bottom = r.y + r.h
if (resizeHandle.value.includes('w')) left = p.x
if (resizeHandle.value.includes('e')) right = p.x
if (resizeHandle.value.includes('n')) top = p.y
if (resizeHandle.value.includes('s')) bottom = p.y
left = clamp(left, 0, props.width)
right = clamp(right, 0, props.width)
top = clamp(top, 0, props.height)
bottom = clamp(bottom, 0, props.height)
rect.value = {
x: Math.min(left, right),
y: Math.min(top, bottom),
w: Math.abs(right - left),
h: Math.abs(bottom - top),
}
}
function selectTool(tool: Tool) {
activeTool.value = tool
}
function chooseColor(color: string) {
activeColor.value = color
paletteOpen.value = false
}
function onConfirm() {
if (!rect.value) return
emit('confirm', { ...rect.value })
emit('confirm', {
rect: { ...rect.value },
annotations: annotations.value,
})
}
function onCancel() {
@@ -153,18 +333,16 @@ function onKeydown(e: KeyboardEvent) {
}
}
function undoAnnotation() {
annotations.value.pop()
}
onMounted(() => {
window.addEventListener('keydown', onKeydown)
})
onUnmounted(() => {
window.removeEventListener('keydown', onKeydown)
})
// Selection size pill (Snipaste shows "WxH" near the top-left of selection).
const sizeLabel = computed(() => {
if (!rect.value) return ''
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
})
</script>
<template>
@@ -176,7 +354,6 @@ const sizeLabel = computed(() => {
@mouseup="onMouseUp"
@contextmenu.prevent="onCancel"
>
<!-- Layer 1: mask with selection cut out over the live desktop -->
<svg
class="mask"
:width="width"
@@ -185,21 +362,78 @@ const sizeLabel = computed(() => {
preserveAspectRatio="none"
>
<path :d="maskPath" fill="rgba(0,0,0,0.45)" fill-rule="evenodd" />
<!-- Selection border, drawn separately so it stays crisp. -->
<rect
v-if="rect"
:x="rect.x"
:y="rect.y"
:width="rect.w"
:height="rect.h"
fill="none"
fill="transparent"
stroke="#3b82f6"
stroke-width="1.5"
vector-effect="non-scaling-stroke"
/>
<g v-for="(annotation, index) in selectionAnnotations" :key="index">
<polyline
v-if="annotation.tool === 'pen'"
:points="annotation.points.map((p) => `${p.x},${p.y}`).join(' ')"
:stroke="annotation.color"
stroke-width="3"
stroke-linecap="round"
stroke-linejoin="round"
fill="none"
/>
<rect
v-else-if="annotation.tool === '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)"
:stroke="annotation.color"
stroke-width="3"
fill="none"
/>
<ellipse
v-else-if="annotation.tool === 'ellipse' && annotation.points.length >= 2"
:cx="(annotation.points[0].x + annotation.points[1].x) / 2"
:cy="(annotation.points[0].y + annotation.points[1].y) / 2"
:rx="Math.abs(annotation.points[1].x - annotation.points[0].x) / 2"
:ry="Math.abs(annotation.points[1].y - annotation.points[0].y) / 2"
:stroke="annotation.color"
stroke-width="3"
fill="none"
/>
</g>
</svg>
<!-- Layer 3a: size readout floating above the selection -->
<div
v-if="rect"
class="selection-hit-area"
:style="{
left: rect.x + 'px',
top: rect.y + 'px',
width: rect.w + 'px',
height: rect.h + 'px',
}"
@mousedown="onSelectionMouseDown"
/>
<div
v-for="handle in handles"
:key="handle.name"
class="resize-handle"
:class="`handle-${handle.name}`"
:style="{ left: handle.x + 'px', top: handle.y + 'px' }"
@mousedown.stop="
(event) => {
dragMode = 'resizing'
resizeHandle = handle.name
dragAnchor = pointFromEvent(event)
startRect = rect ? { ...rect } : null
}
"
/>
<div
v-if="rect && rect.w > 0 && rect.h > 0"
class="size-pill"
@@ -211,11 +445,80 @@ const sizeLabel = computed(() => {
{{ sizeLabel }}
</div>
<!-- Layer 3b: action toolbar -->
<div
v-if="toolbarPos && rect && rect.w >= 4 && rect.h >= 4"
class="toolbar"
:style="{ left: toolbarPos.x + 'px', top: toolbarPos.y + 'px' }"
v-if="leftToolbarPos && rect && rect.w >= 4 && rect.h >= 4"
class="toolbar mark-toolbar"
:style="{ left: leftToolbarPos.x + 'px', top: leftToolbarPos.y + 'px' }"
@mousedown.stop
>
<button
class="icon-btn"
:class="{ active: activeTool === 'pen' }"
title="划线标记"
@click="selectTool('pen')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 20c4-1 6-3 8-7l5-9 3 2-5 9c-2 4-5 6-9 7z" />
<path d="M14 5l5 3" />
</svg>
</button>
<button
class="icon-btn"
:class="{ active: activeTool === 'rect' }"
title="矩形标记"
@click="selectTool('rect')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="5" y="6" width="14" height="12" rx="1.5" />
</svg>
</button>
<button
class="icon-btn"
:class="{ active: activeTool === 'ellipse' }"
title="圆形标记"
@click="selectTool('ellipse')"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="12" r="7" />
</svg>
</button>
<div class="color-wrap">
<button
class="icon-btn color-btn"
title="选择标记颜色"
@click="paletteOpen = !paletteOpen"
>
<span :style="{ background: activeColor }" />
</button>
<div v-if="paletteOpen" class="palette">
<button
v-for="color in colors"
:key="color"
class="swatch"
:class="{ selected: color === activeColor }"
:style="{ background: color }"
:title="color"
@click="chooseColor(color)"
/>
</div>
</div>
<button
class="icon-btn"
:disabled="annotations.length === 0"
title="撤销上一处标记"
@click="undoAnnotation"
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 7H4v5" />
<path d="M4 7c3-3 8-4 12-1 4 3 4 9 0 12-2 1-4 2-7 1" />
</svg>
</button>
</div>
<div
v-if="rightToolbarPos && rect && rect.w >= 4 && rect.h >= 4"
class="toolbar action-toolbar"
:style="{ left: rightToolbarPos.x + 'px', top: rightToolbarPos.y + 'px' }"
@mousedown.stop
>
<button class="btn cancel" @click="onCancel" title="Esc">Cancel</button>
@@ -224,7 +527,6 @@ const sizeLabel = computed(() => {
</button>
</div>
<!-- Hint shown before the user has dragged anything. -->
<div v-if="!rect" class="hint">
Drag to select an area &nbsp;·&nbsp; Esc to cancel
</div>
@@ -248,6 +550,38 @@ const sizeLabel = computed(() => {
pointer-events: none;
}
.selection-hit-area {
position: absolute;
cursor: crosshair;
}
.resize-handle {
position: absolute;
width: 10px;
height: 10px;
transform: translate(-50%, -50%);
border: 1px solid #fff;
background: #3b82f6;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
z-index: 3;
}
.handle-n,
.handle-s {
cursor: ns-resize;
}
.handle-e,
.handle-w {
cursor: ew-resize;
}
.handle-nw,
.handle-se {
cursor: nwse-resize;
}
.handle-ne,
.handle-sw {
cursor: nesw-resize;
}
.size-pill {
position: absolute;
padding: 2px 8px;
@@ -258,7 +592,6 @@ const sizeLabel = computed(() => {
border-radius: 4px;
pointer-events: none;
font-variant-numeric: tabular-nums;
letter-spacing: 0.02em;
}
.toolbar {
@@ -266,11 +599,26 @@ const sizeLabel = computed(() => {
display: flex;
gap: 6px;
align-items: center;
height: 32px;
padding: 4px;
background: rgba(28, 28, 32, 0.94);
border-radius: 8px;
box-shadow: 0 6px 22px rgba(0, 0, 0, 0.4);
cursor: default;
z-index: 4;
}
.mark-toolbar {
width: 190px;
}
.action-toolbar {
width: 220px;
}
.btn,
.icon-btn,
.swatch {
font-family: inherit;
}
.btn {
@@ -280,8 +628,6 @@ const sizeLabel = computed(() => {
font-size: 12px;
font-weight: 500;
cursor: pointer;
font-family: inherit;
transition: background-color 120ms ease;
}
.btn.cancel {
background: transparent;
@@ -298,6 +644,69 @@ const sizeLabel = computed(() => {
background: #2563eb;
}
.icon-btn {
display: grid;
place-items: center;
width: 28px;
height: 28px;
border: 0;
border-radius: 5px;
color: #d1d5db;
background: transparent;
cursor: pointer;
}
.icon-btn:hover:not(:disabled),
.icon-btn.active {
color: #fff;
background: rgba(255, 255, 255, 0.12);
}
.icon-btn:disabled {
opacity: 0.35;
cursor: not-allowed;
}
.icon-btn svg {
width: 18px;
height: 18px;
fill: none;
stroke: currentColor;
stroke-width: 2;
stroke-linecap: round;
stroke-linejoin: round;
}
.color-wrap {
position: relative;
}
.color-btn span {
width: 16px;
height: 16px;
border: 1px solid rgba(255, 255, 255, 0.7);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.18);
}
.palette {
position: absolute;
left: 0;
bottom: 36px;
display: grid;
grid-template-columns: repeat(5, 22px);
gap: 6px;
padding: 8px;
background: rgba(28, 28, 32, 0.96);
border-radius: 8px;
box-shadow: 0 8px 26px rgba(0, 0, 0, 0.45);
}
.swatch {
width: 22px;
height: 22px;
border: 1px solid rgba(255, 255, 255, 0.55);
border-radius: 4px;
cursor: pointer;
}
.swatch.selected {
outline: 2px solid #fff;
outline-offset: 2px;
}
.hint {
position: absolute;
left: 50%;
@@ -309,6 +718,5 @@ const sizeLabel = computed(() => {
background: rgba(0, 0, 0, 0.5);
border-radius: 999px;
pointer-events: none;
letter-spacing: 0.02em;
}
</style>
+2 -2
View File
@@ -9,9 +9,9 @@ export function CancelRegion():Promise<void>;
export function CaptureNow():Promise<void>;
export function ConfirmNativeRegion(arg1:main.RegionRect):Promise<void>;
export function ConfirmNativeRegion(arg1:main.CaptureResult):Promise<void>;
export function ConfirmRegion(arg1:main.RegionRect):Promise<void>;
export function ConfirmRegion(arg1:main.CaptureResult):Promise<void>;
export function GetConfig():Promise<domain.AppConfig>;
+85
View File
@@ -1,3 +1,56 @@
export namespace application {
export class Point {
x: number;
y: number;
static createFrom(source: any = {}) {
return new Point(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.x = source["x"];
this.y = source["y"];
}
}
export class Annotation {
tool: string;
color: string;
points: Point[];
static createFrom(source: any = {}) {
return new Annotation(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.tool = source["tool"];
this.color = source["color"];
this.points = this.convertValues(source["points"], Point);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
}
export namespace domain {
export class S3Config {
@@ -81,6 +134,38 @@ export namespace main {
this.h = source["h"];
}
}
export class CaptureResult {
rect: RegionRect;
annotations: application.Annotation[];
static createFrom(source: any = {}) {
return new CaptureResult(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.rect = this.convertValues(source["rect"], RegionRect);
this.annotations = this.convertValues(source["annotations"], application.Annotation);
}
convertValues(a: any, classs: any, asMap: boolean = false): any {
if (!a) {
return a;
}
if (a.slice && a.map) {
return (a as any[]).map(elem => this.convertValues(elem, classs));
} else if ("object" === typeof a) {
if (asMap) {
for (const key of Object.keys(a)) {
a[key] = new classs(a[key]);
}
return a;
}
return new classs(a);
}
return a;
}
}
}
+182
View File
@@ -0,0 +1,182 @@
package application
import (
"bytes"
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"math"
"strconv"
"strings"
)
// Annotation describes a user-drawn mark relative to the selected screenshot.
// Coordinates are logical pixels in the same coordinate system as the overlay.
type Annotation struct {
Tool string `json:"tool"`
Color string `json:"color"`
Points []Point `json:"points"`
}
type Point struct {
X float64 `json:"x"`
Y float64 `json:"y"`
}
// ApplyAnnotations decodes a PNG, draws all annotations, and re-encodes it.
func ApplyAnnotations(pngBytes []byte, annotations []Annotation, scale float64) ([]byte, error) {
if len(annotations) == 0 {
return pngBytes, nil
}
if scale <= 0 {
scale = 1
}
src, err := png.Decode(bytes.NewReader(pngBytes))
if err != nil {
return nil, fmt.Errorf("decode annotated png: %w", err)
}
bounds := src.Bounds()
dst := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
draw.Draw(dst, dst.Bounds(), src, bounds.Min, draw.Src)
for _, ann := range annotations {
c, err := parseHexColor(ann.Color)
if err != nil {
c = color.RGBA{R: 59, G: 130, B: 246, A: 255}
}
width := int(math.Max(2, math.Round(3*scale)))
switch ann.Tool {
case "pen":
drawPolyline(dst, ann.Points, scale, width, c)
case "rect":
drawRectOutline(dst, ann.Points, scale, width, c)
case "ellipse":
drawEllipseOutline(dst, ann.Points, scale, width, c)
}
}
var buf bytes.Buffer
if err := png.Encode(&buf, dst); err != nil {
return nil, fmt.Errorf("encode annotated png: %w", err)
}
return buf.Bytes(), nil
}
func parseHexColor(hex string) (color.RGBA, error) {
value := strings.TrimPrefix(strings.TrimSpace(hex), "#")
if len(value) != 6 {
return color.RGBA{}, fmt.Errorf("invalid color %q", hex)
}
n, err := strconv.ParseUint(value, 16, 32)
if err != nil {
return color.RGBA{}, err
}
return color.RGBA{
R: uint8(n >> 16),
G: uint8(n >> 8),
B: uint8(n),
A: 255,
}, nil
}
func drawPolyline(img *image.RGBA, points []Point, scale float64, width int, c color.RGBA) {
if len(points) == 1 {
drawDot(img, scalePoint(points[0], scale), width, c)
return
}
for i := 1; i < len(points); i++ {
drawLine(img, scalePoint(points[i-1], scale), scalePoint(points[i], scale), width, c)
}
}
func drawRectOutline(img *image.RGBA, points []Point, scale float64, width int, c color.RGBA) {
if len(points) < 2 {
return
}
a := scalePoint(points[0], scale)
b := scalePoint(points[len(points)-1], scale)
x1, x2 := ordered(a.X, b.X)
y1, y2 := ordered(a.Y, b.Y)
drawLine(img, Point{X: x1, Y: y1}, Point{X: x2, Y: y1}, width, c)
drawLine(img, Point{X: x2, Y: y1}, Point{X: x2, Y: y2}, width, c)
drawLine(img, Point{X: x2, Y: y2}, Point{X: x1, Y: y2}, width, c)
drawLine(img, Point{X: x1, Y: y2}, Point{X: x1, Y: y1}, width, c)
}
func drawEllipseOutline(img *image.RGBA, points []Point, scale float64, width int, c color.RGBA) {
if len(points) < 2 {
return
}
a := scalePoint(points[0], scale)
b := scalePoint(points[len(points)-1], scale)
x1, x2 := ordered(a.X, b.X)
y1, y2 := ordered(a.Y, b.Y)
rx := (x2 - x1) / 2
ry := (y2 - y1) / 2
if rx <= 0 || ry <= 0 {
return
}
cx := x1 + rx
cy := y1 + ry
steps := int(math.Max(48, math.Ceil(2*math.Pi*math.Max(rx, ry)/4)))
prev := Point{
X: cx + rx,
Y: cy,
}
for i := 1; i <= steps; i++ {
theta := 2 * math.Pi * float64(i) / float64(steps)
next := Point{
X: cx + rx*math.Cos(theta),
Y: cy + ry*math.Sin(theta),
}
drawLine(img, prev, next, width, c)
prev = next
}
}
func drawLine(img *image.RGBA, a, b Point, width int, c color.RGBA) {
dx := b.X - a.X
dy := b.Y - a.Y
steps := int(math.Max(math.Abs(dx), math.Abs(dy)))
if steps == 0 {
drawDot(img, a, width, c)
return
}
for i := 0; i <= steps; i++ {
t := float64(i) / float64(steps)
drawDot(img, Point{X: a.X + dx*t, Y: a.Y + dy*t}, width, c)
}
}
func drawDot(img *image.RGBA, p Point, width int, c color.RGBA) {
radius := float64(width) / 2
minX := int(math.Floor(p.X - radius))
maxX := int(math.Ceil(p.X + radius))
minY := int(math.Floor(p.Y - radius))
maxY := int(math.Ceil(p.Y + radius))
bounds := img.Bounds()
for y := minY; y <= maxY; y++ {
for x := minX; x <= maxX; x++ {
if !image.Pt(x, y).In(bounds) {
continue
}
if math.Hypot(float64(x)-p.X, float64(y)-p.Y) <= radius {
img.SetRGBA(x, y, c)
}
}
}
}
func scalePoint(p Point, scale float64) Point {
return Point{X: p.X * scale, Y: p.Y * scale}
}
func ordered(a, b float64) (float64, float64) {
if a < b {
return a, b
}
return b, a
}
+53
View File
@@ -0,0 +1,53 @@
package application
import (
"bytes"
"image"
"image/color"
"image/draw"
"image/png"
"testing"
)
func TestApplyAnnotationsDrawsIntoPNG(t *testing.T) {
src := image.NewRGBA(image.Rect(0, 0, 40, 40))
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: "rect",
Color: "#ef4444",
Points: []Point{
{X: 5, Y: 5},
{X: 30, Y: 30},
},
},
}, 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 got := color.RGBAModel.Convert(img.At(5, 5)).(color.RGBA); got.R != 0xef || got.G != 0x44 || got.B != 0x44 {
t.Fatalf("expected annotated pixel at rectangle edge, got %#v", got)
}
}
func TestApplyAnnotationsNoAnnotationsReturnsOriginalBytes(t *testing.T) {
original := []byte("not decoded when no annotations")
out, err := ApplyAnnotations(original, nil, 1)
if err != nil {
t.Fatalf("apply annotations: %v", err)
}
if !bytes.Equal(out, original) {
t.Fatalf("expected original bytes")
}
}
+10 -6
View File
@@ -5,7 +5,7 @@ package main
import "C"
//export nativeOverlayConfirm
func nativeOverlayConfirm(x, y, w, h C.int) {
func nativeOverlayConfirm(x, y, w, h C.int, annotationsJSON *C.char) {
nativeOverlayState.Lock()
app := nativeOverlayState.app
nativeOverlayState.app = nil
@@ -13,12 +13,16 @@ func nativeOverlayConfirm(x, y, w, h C.int) {
if app == nil {
return
}
rawAnnotations := C.GoString(annotationsJSON)
go func() {
_ = app.ConfirmNativeRegion(RegionRect{
X: int(x),
Y: int(y),
W: int(w),
H: int(h),
_ = app.ConfirmNativeRegion(CaptureResult{
Rect: RegionRect{
X: int(x),
Y: int(y),
W: int(w),
H: int(h),
},
Annotations: parseNativeAnnotations(rawAnnotations),
})
}()
}
+332 -6
View File
@@ -7,9 +7,10 @@ package main
#cgo LDFLAGS: -framework AppKit -framework CoreGraphics
#include <math.h>
#include <dispatch/dispatch.h>
#import <objc/runtime.h>
#import <AppKit/AppKit.h>
extern void nativeOverlayConfirm(int x, int y, int w, int h);
extern void nativeOverlayConfirm(int x, int y, int w, int h, const char *annotationsJSON);
extern void nativeOverlayCancel(void);
static NSWindow *nativeOverlayWindow = nil;
@@ -27,11 +28,25 @@ static id nativeOverlayKeyMonitor = nil;
@property BOOL hasSelection;
@property BOOL creating;
@property BOOL moving;
@property BOOL resizing;
@property BOOL annotating;
@property NSRect selection;
@property NSPoint anchor;
@property NSPoint moveOffset;
@property NSRect resizeStart;
@property NSString *resizeHandle;
@property NSString *activeTool;
@property(strong) NSColor *activeColor;
@property(strong) NSMutableArray<NSDictionary *> *annotations;
@property(strong) NSMutableDictionary *draftAnnotation;
@property(strong) NSButton *cancelButton;
@property(strong) NSButton *uploadButton;
@property(strong) NSButton *penButton;
@property(strong) NSButton *rectButton;
@property(strong) NSButton *ellipseButton;
@property(strong) NSButton *colorButton;
@property(strong) NSButton *undoButton;
@property(strong) NSView *paletteView;
@property(strong) NSTextField *sizeLabel;
@property(strong) NSTextField *hintLabel;
- (void)syncControls;
@@ -50,17 +65,28 @@ static id nativeOverlayKeyMonitor = nil;
[self setWantsLayer:YES];
[[self layer] setBackgroundColor:[[NSColor clearColor] CGColor]];
_activeTool = nil;
_activeColor = [NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0];
_annotations = [NSMutableArray array];
_cancelButton = [NSButton buttonWithTitle:@"Cancel" target:self action:@selector(cancelSelection)];
_uploadButton = [NSButton buttonWithTitle:@"Upload & copy" target:self action:@selector(confirmSelection)];
_penButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectPen)];
_rectButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectRect)];
_ellipseButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectEllipse)];
_colorButton = [NSButton buttonWithTitle:@"" target:self action:@selector(togglePalette)];
_undoButton = [NSButton buttonWithTitle:@"" target:self action:@selector(undoAnnotation)];
_paletteView = [[NSView alloc] initWithFrame:NSZeroRect];
_sizeLabel = [NSTextField labelWithString:@""];
_hintLabel = [NSTextField labelWithString:@"Drag to select an area · Esc to cancel"];
[self styleControls];
for (NSView *view in @[_cancelButton, _uploadButton, _sizeLabel, _hintLabel]) {
for (NSView *view in @[_cancelButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _colorButton, _undoButton, _paletteView, _sizeLabel, _hintLabel]) {
[self addSubview:view];
}
[_cancelButton setHidden:YES];
[_uploadButton setHidden:YES];
for (NSView *view in @[_cancelButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _colorButton, _undoButton, _paletteView]) {
[view setHidden:YES];
}
[_sizeLabel setHidden:YES];
[_sizeLabel setTextColor:[NSColor whiteColor]];
@@ -79,6 +105,21 @@ static id nativeOverlayKeyMonitor = nil;
return self;
}
- (NSString *)hexForColor:(NSColor *)color {
NSColor *rgb = [color colorUsingColorSpace:[NSColorSpace sRGBColorSpace]];
NSInteger r = (NSInteger)llround([rgb redComponent] * 255.0);
NSInteger g = (NSInteger)llround([rgb greenComponent] * 255.0);
NSInteger b = (NSInteger)llround([rgb blueComponent] * 255.0);
return [NSString stringWithFormat:@"#%02lx%02lx%02lx", (long)r, (long)g, (long)b];
}
- (NSImage *)iconFromSVG:(NSString *)svg {
NSData *data = [svg dataUsingEncoding:NSUTF8StringEncoding];
NSImage *image = [[NSImage alloc] initWithData:data];
[image setTemplate:YES];
return image;
}
- (void)styleButton:(NSButton *)button background:(NSColor *)background foreground:(NSColor *)foreground {
[button setBordered:NO];
[button setBezelStyle:NSBezelStyleRegularSquare];
@@ -91,6 +132,20 @@ static id nativeOverlayKeyMonitor = nil;
[button setAttributedTitle:title];
}
- (void)styleIconButton:(NSButton *)button image:(NSImage *)image {
[button setBordered:NO];
[button setBezelStyle:NSBezelStyleRegularSquare];
[button setImagePosition:NSImageOnly];
[button setImageScaling:NSImageScaleProportionallyDown];
if (@available(macOS 10.14, *)) {
[button setContentTintColor:[NSColor whiteColor]];
}
[button setImage:image];
[button setWantsLayer:YES];
[[button layer] setCornerRadius:5];
[[button layer] setBackgroundColor:[[NSColor clearColor] CGColor]];
}
- (void)styleControls {
[self styleButton:_cancelButton
background:[NSColor colorWithCalibratedWhite:0.12 alpha:0.96]
@@ -98,6 +153,14 @@ static id nativeOverlayKeyMonitor = nil;
[self styleButton:_uploadButton
background:[NSColor colorWithCalibratedRed:59.0/255.0 green:130.0/255.0 blue:246.0/255.0 alpha:1.0]
foreground:[NSColor whiteColor]];
[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:_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];
[[_paletteView layer] setCornerRadius:8];
[[_paletteView layer] setBackgroundColor:[[NSColor colorWithCalibratedWhite:0.11 alpha:0.96] CGColor]];
}
- (void)drawRect:(NSRect)dirtyRect {
@@ -133,23 +196,156 @@ static id nativeOverlayKeyMonitor = nil;
[corners lineToPoint:NSMakePoint(NSMinX(_selection), NSMaxY(_selection) - corner)];
[corners setLineWidth:3];
[corners stroke];
[self drawAnnotations];
[self drawResizeHandles];
} else {
NSRectFill(self.bounds);
}
}
- (void)drawResizeHandles {
NSArray *points = @[
[NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMinY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMidX(_selection), NSMinY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMinY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMidY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMaxY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMidX(_selection), NSMaxY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMaxY(_selection))],
[NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMidY(_selection))]
];
[[NSColor whiteColor] setStroke];
[[NSColor colorWithCalibratedRed:59.0/255.0 green:130.0/255.0 blue:246.0/255.0 alpha:1.0] setFill];
for (NSValue *value in points) {
NSPoint p = [value pointValue];
NSRect handleRect = NSMakeRect(p.x - 5, p.y - 5, 10, 10);
NSBezierPath *path = [NSBezierPath bezierPathWithRect:handleRect];
[path fill];
[path stroke];
}
}
- (void)drawAnnotations {
NSMutableArray *items = [NSMutableArray arrayWithArray:_annotations];
if (_draftAnnotation != nil) {
[items addObject:_draftAnnotation];
}
for (NSDictionary *item in items) {
NSString *tool = item[@"tool"];
NSColor *color = item[@"nsColor"];
NSArray *points = item[@"points"];
if (points.count == 0) {
continue;
}
[color setStroke];
NSBezierPath *path = [NSBezierPath bezierPath];
[path setLineWidth:3];
[path setLineCapStyle:NSLineCapStyleRound];
[path setLineJoinStyle:NSLineJoinStyleRound];
if ([tool isEqualToString:@"pen"]) {
NSPoint first = [points[0] pointValue];
[path moveToPoint:NSMakePoint(_selection.origin.x + first.x, _selection.origin.y + first.y)];
for (NSUInteger i = 1; i < points.count; i++) {
NSPoint point = [points[i] pointValue];
[path lineToPoint:NSMakePoint(_selection.origin.x + point.x, _selection.origin.y + point.y)];
}
[path stroke];
} else if (points.count >= 2) {
NSPoint a = [points[0] pointValue];
NSPoint 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));
if ([tool isEqualToString:@"rect"]) {
NSBezierPath *rectPath = [NSBezierPath bezierPathWithRect:r];
[rectPath setLineWidth:3];
[rectPath stroke];
} else if ([tool isEqualToString:@"ellipse"]) {
NSBezierPath *ellipsePath = [NSBezierPath bezierPathWithOvalInRect:r];
[ellipsePath setLineWidth:3];
[ellipsePath stroke];
}
}
}
}
- (NSString *)resizeHandleAtPoint:(NSPoint)p {
if (!_hasSelection) {
return nil;
}
CGFloat t = 9;
NSDictionary *handles = @{
@"nw": [NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMinY(_selection))],
@"n": [NSValue valueWithPoint:NSMakePoint(NSMidX(_selection), NSMinY(_selection))],
@"ne": [NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMinY(_selection))],
@"e": [NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMidY(_selection))],
@"se": [NSValue valueWithPoint:NSMakePoint(NSMaxX(_selection), NSMaxY(_selection))],
@"s": [NSValue valueWithPoint:NSMakePoint(NSMidX(_selection), NSMaxY(_selection))],
@"sw": [NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMaxY(_selection))],
@"w": [NSValue valueWithPoint:NSMakePoint(NSMinX(_selection), NSMidY(_selection))]
};
for (NSString *key in handles) {
NSPoint hp = [handles[key] pointValue];
if (fabs(p.x - hp.x) <= t && fabs(p.y - hp.y) <= t) {
return key;
}
}
BOOL nearX = p.x >= NSMinX(_selection) - t && p.x <= NSMaxX(_selection) + t;
BOOL nearY = p.y >= NSMinY(_selection) - t && p.y <= NSMaxY(_selection) + t;
if (nearX && fabs(p.y - NSMinY(_selection)) <= t) return @"n";
if (nearX && fabs(p.y - NSMaxY(_selection)) <= t) return @"s";
if (nearY && fabs(p.x - NSMinX(_selection)) <= t) return @"w";
if (nearY && fabs(p.x - NSMaxX(_selection)) <= t) return @"e";
return nil;
}
- (NSPoint)localPoint:(NSPoint)p {
return NSMakePoint(
MAX(0, MIN(p.x - _selection.origin.x, _selection.size.width)),
MAX(0, MIN(p.y - _selection.origin.y, _selection.size.height)));
}
- (void)mouseDown:(NSEvent *)event {
NSPoint p = [self convertPoint:[event locationInWindow] fromView:nil];
if (_hasSelection && NSPointInRect(p, _selection)) {
NSString *handle = [self resizeHandleAtPoint:p];
if (handle != nil) {
_resizing = YES;
_creating = NO;
_moving = NO;
_annotating = NO;
_resizeHandle = handle;
_resizeStart = _selection;
} else if (_hasSelection && NSPointInRect(p, _selection) && _activeTool != nil) {
_annotating = YES;
_creating = NO;
_moving = NO;
_resizing = NO;
NSPoint local = [self localPoint:p];
_draftAnnotation = [@{
@"tool": _activeTool,
@"color": [self hexForColor:_activeColor],
@"nsColor": _activeColor,
@"points": [NSMutableArray arrayWithObject:[NSValue valueWithPoint:local]]
} mutableCopy];
} else if (_hasSelection && NSPointInRect(p, _selection)) {
_moving = YES;
_creating = NO;
_resizing = NO;
_annotating = NO;
_moveOffset = NSMakePoint(p.x - _selection.origin.x, p.y - _selection.origin.y);
} else {
_creating = YES;
_moving = NO;
_resizing = NO;
_annotating = NO;
_hasSelection = YES;
_anchor = p;
_selection = NSMakeRect(p.x, p.y, 0, 0);
[_annotations removeAllObjects];
_draftAnnotation = nil;
}
[self syncControls];
}
@@ -166,6 +362,32 @@ static id nativeOverlayKeyMonitor = nil;
x = MAX(0, MIN(x, self.bounds.size.width - _selection.size.width));
y = MAX(0, MIN(y, self.bounds.size.height - _selection.size.height));
_selection.origin = NSMakePoint(x, y);
} else if (_resizing) {
CGFloat left = NSMinX(_resizeStart);
CGFloat top = NSMinY(_resizeStart);
CGFloat right = NSMaxX(_resizeStart);
CGFloat bottom = NSMaxY(_resizeStart);
if ([_resizeHandle containsString:@"w"]) left = p.x;
if ([_resizeHandle containsString:@"e"]) right = p.x;
if ([_resizeHandle containsString:@"n"]) top = p.y;
if ([_resizeHandle containsString:@"s"]) bottom = p.y;
left = MAX(0, MIN(left, self.bounds.size.width));
right = MAX(0, MIN(right, self.bounds.size.width));
top = MAX(0, MIN(top, self.bounds.size.height));
bottom = MAX(0, MIN(bottom, self.bounds.size.height));
_selection = NSMakeRect(MIN(left, right), MIN(top, bottom), fabs(right - left), fabs(bottom - top));
} else if (_annotating && _draftAnnotation != nil) {
NSMutableArray *points = _draftAnnotation[@"points"];
NSPoint local = [self localPoint:p];
if ([_activeTool isEqualToString:@"pen"]) {
[points addObject:[NSValue valueWithPoint:local]];
} else {
if (points.count == 1) {
[points addObject:[NSValue valueWithPoint:local]];
} else {
points[1] = [NSValue valueWithPoint:local];
}
}
}
[self syncControls];
[self setNeedsDisplay:YES];
@@ -174,6 +396,12 @@ static id nativeOverlayKeyMonitor = nil;
- (void)mouseUp:(NSEvent *)event {
_creating = NO;
_moving = NO;
_resizing = NO;
if (_annotating && _draftAnnotation != nil) {
[_annotations addObject:_draftAnnotation];
_draftAnnotation = nil;
}
_annotating = NO;
if (_hasSelection && (_selection.size.width < 4 || _selection.size.height < 4)) {
_hasSelection = NO;
}
@@ -199,6 +427,11 @@ static id nativeOverlayKeyMonitor = nil;
BOOL visible = _hasSelection && _selection.size.width >= 4 && _selection.size.height >= 4;
[_cancelButton setHidden:!visible];
[_uploadButton setHidden:!visible];
[_penButton setHidden:!visible];
[_rectButton setHidden:!visible];
[_ellipseButton setHidden:!visible];
[_colorButton setHidden:!visible];
[_undoButton setHidden:!visible];
[_sizeLabel setHidden:!visible];
[_hintLabel setHidden:_hasSelection];
@@ -220,6 +453,98 @@ static id nativeOverlayKeyMonitor = nil;
[_cancelButton setFrame:NSMakeRect(x, y, 86, 32)];
[_uploadButton setFrame:NSMakeRect(x + 92, y, 128, 32)];
CGFloat markW = 170;
CGFloat markX = MAX(0, MIN(_selection.origin.x, self.bounds.size.width - 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)];
[[_colorButton layer] setBackgroundColor:[_activeColor CGColor]];
[_undoButton setEnabled:_annotations.count > 0];
[_paletteView setFrame:NSMakeRect(markX, MAX(0, y - 78), 150, 70)];
[self updateToolButtonStates];
}
- (void)updateToolButtonStates {
NSDictionary *buttons = @{@"pen": _penButton, @"rect": _rectButton, @"ellipse": _ellipseButton};
for (NSString *tool in buttons) {
NSButton *button = buttons[tool];
NSColor *bg = [tool isEqualToString:_activeTool]
? [NSColor colorWithCalibratedWhite:1.0 alpha:0.14]
: [NSColor clearColor];
[[button layer] setBackgroundColor:[bg CGColor]];
}
}
- (void)toggleTool:(NSString *)tool {
_activeTool = [_activeTool isEqualToString:tool] ? nil : tool;
[self syncControls];
}
- (void)selectPen { [self toggleTool:@"pen"]; }
- (void)selectRect { [self toggleTool:@"rect"]; }
- (void)selectEllipse { [self toggleTool:@"ellipse"]; }
- (void)undoAnnotation {
if (_annotations.count > 0) {
[_annotations removeLastObject];
[self syncControls];
[self setNeedsDisplay:YES];
}
}
- (void)togglePalette {
[_paletteView setHidden:![_paletteView isHidden]];
if (![_paletteView isHidden] && _paletteView.subviews.count == 0) {
NSArray *colors = @[
[NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0],
[NSColor colorWithCalibratedRed:249.0/255.0 green:115.0/255.0 blue:22.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],
[NSColor colorWithCalibratedRed:34.0/255.0 green:197.0/255.0 blue:94.0/255.0 alpha:1.0],
[NSColor colorWithCalibratedRed:59.0/255.0 green:130.0/255.0 blue:246.0/255.0 alpha:1.0],
[NSColor colorWithCalibratedRed:139.0/255.0 green:92.0/255.0 blue:246.0/255.0 alpha:1.0],
[NSColor colorWithCalibratedRed:236.0/255.0 green:72.0/255.0 blue:153.0/255.0 alpha:1.0],
[NSColor whiteColor],
[NSColor colorWithCalibratedWhite:0.07 alpha:1.0]
];
for (NSUInteger i = 0; i < colors.count; i++) {
NSButton *button = [NSButton buttonWithTitle:@"" target:self action:@selector(selectPaletteColor:)];
[button setBordered:NO];
[button setWantsLayer:YES];
[[button layer] setCornerRadius:4];
[[button layer] setBackgroundColor:[colors[i] CGColor]];
[button setTag:(NSInteger)i];
[button setFrame:NSMakeRect(8 + (i % 5) * 28, 38 - (i / 5) * 28, 22, 22)];
[_paletteView addSubview:button];
}
objc_setAssociatedObject(_paletteView, "snapgoColors", colors, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
- (void)selectPaletteColor:(NSButton *)sender {
NSArray *colors = objc_getAssociatedObject(_paletteView, "snapgoColors");
if (sender.tag >= 0 && sender.tag < (NSInteger)colors.count) {
_activeColor = colors[(NSUInteger)sender.tag];
[_paletteView setHidden:YES];
[self syncControls];
}
}
- (NSString *)annotationsJSON {
NSMutableArray *payload = [NSMutableArray array];
for (NSDictionary *item in _annotations) {
NSMutableArray *points = [NSMutableArray array];
for (NSValue *value in item[@"points"]) {
NSPoint p = [value pointValue];
[points addObject:@{@"x": @(p.x), @"y": @(p.y)}];
}
[payload addObject:@{@"tool": item[@"tool"], @"color": item[@"color"], @"points": points}];
}
NSData *data = [NSJSONSerialization dataWithJSONObject:payload options:0 error:nil];
if (data == nil) {
return @"[]";
}
return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
- (void)confirmSelection {
@@ -233,7 +558,8 @@ static id nativeOverlayKeyMonitor = nil;
nativeOverlayKeyMonitor = nil;
}
nativeOverlayWindow = nil;
nativeOverlayConfirm((int)llround(r.origin.x), (int)llround(r.origin.y), (int)llround(r.size.width), (int)llround(r.size.height));
NSString *json = [self annotationsJSON];
nativeOverlayConfirm((int)llround(r.origin.x), (int)llround(r.origin.y), (int)llround(r.size.width), (int)llround(r.size.height), [json UTF8String]);
}
- (void)cancelSelection {