Compare commits
10 Commits
1229efaa84
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 5aa60555b9 | |||
| 75c9b96fbf | |||
| b69ef00013 | |||
| 50551de105 | |||
| b82108db38 | |||
| dd12521be2 | |||
| f1998fb23c | |||
| 8e611a11e6 | |||
| ba252c8576 | |||
| 1115f4532c |
@@ -21,6 +21,7 @@ SnapGo 是一个为“截完图马上发链接”而做的轻量截图工具。
|
|||||||
- 全局快捷键触发:无论当前在什么应用里,都能快速发起截图
|
- 全局快捷键触发:无论当前在什么应用里,都能快速发起截图
|
||||||
- 菜单栏常驻:随用随取,不打断主流程
|
- 菜单栏常驻:随用随取,不打断主流程
|
||||||
- 支持 S3 兼容存储:可接入 AWS S3、MinIO、Cloudflare R2、Backblaze B2 等
|
- 支持 S3 兼容存储:可接入 AWS S3、MinIO、Cloudflare R2、Backblaze B2 等
|
||||||
|
- 支持 FTP / SFTP:可通过独立截图操作上传到文件服务器,并复制远端路径
|
||||||
- 支持自定义公开地址:可配合 CDN 或自定义域名使用
|
- 支持自定义公开地址:可配合 CDN 或自定义域名使用
|
||||||
- 上传失败自动兜底:至少保住截图文件,不会白截
|
- 上传失败自动兜底:至少保住截图文件,不会白截
|
||||||
|
|
||||||
@@ -57,11 +58,11 @@ SnapGo 是一个为“截完图马上发链接”而做的轻量截图工具。
|
|||||||
|
|
||||||
## 使用方式
|
## 使用方式
|
||||||
|
|
||||||
1. 打开应用,填写你的 S3 兼容对象存储配置
|
1. 打开应用,填写 S3、FTP / SFTP 或 SSH 远端配置
|
||||||
2. 保存并测试连接
|
2. 保存并测试连接
|
||||||
3. 按下默认快捷键 `cmd+shift+a`
|
3. 按下默认快捷键 `cmd+shift+a`
|
||||||
4. 框选截图区域
|
4. 框选截图区域
|
||||||
5. 直接粘贴刚刚自动复制好的图片链接
|
5. 点击目标上传按钮,直接粘贴自动复制的图片链接或远端路径
|
||||||
|
|
||||||
## 当前体验
|
## 当前体验
|
||||||
|
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
@@ -23,6 +24,7 @@ import (
|
|||||||
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||||
"github.com/mmmy/snapgo/internal/infrastructure/config"
|
"github.com/mmmy/snapgo/internal/infrastructure/config"
|
||||||
"github.com/mmmy/snapgo/internal/infrastructure/display"
|
"github.com/mmmy/snapgo/internal/infrastructure/display"
|
||||||
|
ftppkg "github.com/mmmy/snapgo/internal/infrastructure/ftp"
|
||||||
"github.com/mmmy/snapgo/internal/infrastructure/hotkey"
|
"github.com/mmmy/snapgo/internal/infrastructure/hotkey"
|
||||||
llmpkg "github.com/mmmy/snapgo/internal/infrastructure/llm"
|
llmpkg "github.com/mmmy/snapgo/internal/infrastructure/llm"
|
||||||
ocrpkg "github.com/mmmy/snapgo/internal/infrastructure/ocr"
|
ocrpkg "github.com/mmmy/snapgo/internal/infrastructure/ocr"
|
||||||
@@ -35,8 +37,8 @@ import (
|
|||||||
//
|
//
|
||||||
// We deliberately keep this struct small: it owns long-lived collaborators
|
// We deliberately keep this struct small: it owns long-lived collaborators
|
||||||
// (config store, hotkey manager, capturer, clipboard) but delegates the
|
// (config store, hotkey manager, capturer, clipboard) but delegates the
|
||||||
// real work to the application service constructed on demand once an OSS
|
// real work to application services constructed on demand for the selected
|
||||||
// provider is configured.
|
// storage destination.
|
||||||
type App struct {
|
type App struct {
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
|
|
||||||
@@ -400,6 +402,56 @@ func (a *App) runSaveRemotePipeline(pngBytes []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// runFTPUploadPipeline uploads through the protocol selected in FTPConfig and
|
||||||
|
// copies the resulting remote path. FTP/SFTP remains separate from both S3
|
||||||
|
// (public URL semantics) and SSH/SCP (a distinct toolbar destination).
|
||||||
|
func (a *App) runFTPUploadPipeline(pngBytes []byte) error {
|
||||||
|
a.mu.RLock()
|
||||||
|
cfg := a.cfg
|
||||||
|
a.mu.RUnlock()
|
||||||
|
|
||||||
|
if !cfg.IsFTPConfigured() {
|
||||||
|
err := fmt.Errorf("FTP/SFTP host/user is not configured")
|
||||||
|
a.emitOperationStatus("ftp-upload", "需要配置 FTP/SFTP", err.Error(), "error")
|
||||||
|
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
uploader, err := ftppkg.NewUploader(cfg.FTP)
|
||||||
|
if err != nil {
|
||||||
|
a.emitOperationStatus("ftp-upload", "FTP/SFTP 配置错误", err.Error(), "error")
|
||||||
|
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
slog.Info("FTP/SFTP upload dispatch",
|
||||||
|
"protocol", cfg.FTP.Protocol,
|
||||||
|
"host", cfg.FTP.Host,
|
||||||
|
"user", cfg.FTP.User,
|
||||||
|
"port", cfg.FTP.Port,
|
||||||
|
"auth_method", cfg.FTP.AuthMethod,
|
||||||
|
"strict_host_key", cfg.FTP.StrictHostKey,
|
||||||
|
"has_password", cfg.FTP.Password != "",
|
||||||
|
"png_size", len(pngBytes))
|
||||||
|
|
||||||
|
svc := &application.CaptureAndFTPService{
|
||||||
|
Uploader: uploader,
|
||||||
|
Clipboard: a.clip,
|
||||||
|
Notifier: &runtimeNotifier{ctx: a.ctx},
|
||||||
|
Cfg: cfg.FTP,
|
||||||
|
}
|
||||||
|
protocolLabel := strings.ToUpper(cfg.FTP.Protocol)
|
||||||
|
if protocolLabel == "" {
|
||||||
|
protocolLabel = "FTP"
|
||||||
|
}
|
||||||
|
a.emitOperationStatus("ftp-upload", "上传中", "正在上传截图到 "+protocolLabel, "running")
|
||||||
|
if err := svc.ExecuteWithBytes(a.ctx, pngBytes); err != nil {
|
||||||
|
a.emitOperationStatus("ftp-upload", "上传失败", err.Error(), "error")
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
a.emitOperationStatus("ftp-upload", "上传完成", "远端路径已复制到剪贴板", "success")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func (a *App) runSummaryPipeline(pngBytes []byte) error {
|
func (a *App) runSummaryPipeline(pngBytes []byte) error {
|
||||||
a.mu.RLock()
|
a.mu.RLock()
|
||||||
cfg := a.cfg
|
cfg := a.cfg
|
||||||
@@ -689,6 +741,33 @@ func (a *App) TestSSHConnection(cfg domain.SSHConfig) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TestFTPConnection performs a write/delete probe with the supplied FTP or
|
||||||
|
// SFTP configuration so Settings can verify both authentication and remote
|
||||||
|
// directory permissions before saving.
|
||||||
|
func (a *App) TestFTPConnection(cfg domain.FTPConfig) error {
|
||||||
|
slog.Info("RPC TestFTPConnection",
|
||||||
|
"protocol", cfg.Protocol,
|
||||||
|
"host", cfg.Host,
|
||||||
|
"user", cfg.User,
|
||||||
|
"port", cfg.Port,
|
||||||
|
"auth_method", cfg.AuthMethod,
|
||||||
|
"strict_host_key", cfg.StrictHostKey,
|
||||||
|
"has_password", cfg.Password != "")
|
||||||
|
uploader, err := ftppkg.NewUploader(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := uploader.TestConnection(a.ctx); err != nil {
|
||||||
|
slog.Error("RPC TestFTPConnection failed",
|
||||||
|
"protocol", cfg.Protocol,
|
||||||
|
"host", cfg.Host,
|
||||||
|
"user", cfg.User,
|
||||||
|
"err", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
// CaptureNow is the in-app trigger.
|
// CaptureNow is the in-app trigger.
|
||||||
func (a *App) CaptureNow() {
|
func (a *App) CaptureNow() {
|
||||||
go a.runInteractiveCapture()
|
go a.runInteractiveCapture()
|
||||||
@@ -920,6 +999,30 @@ func (a *App) SaveRegionToRemote(result CaptureResult) error {
|
|||||||
return a.runSaveRemotePipeline(cropped)
|
return a.runSaveRemotePipeline(cropped)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UploadRegionToFTP uploads the selected region through the configured FTP or
|
||||||
|
// SFTP destination. This is the non-macOS Wails overlay action.
|
||||||
|
func (a *App) UploadRegionToFTP(result CaptureResult) error {
|
||||||
|
pc, err := a.consumePendingCapture()
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("UploadRegionToFTP: no pending capture", "err", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
a.capturing.Store(false)
|
||||||
|
a.dismissOverlay()
|
||||||
|
}()
|
||||||
|
|
||||||
|
a.dismissOverlay()
|
||||||
|
flushFrame()
|
||||||
|
cropped, err := a.captureSelectedPNG(result, pc)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("UploadRegionToFTP: capture failed", "err", err)
|
||||||
|
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return a.runFTPUploadPipeline(cropped)
|
||||||
|
}
|
||||||
|
|
||||||
// SummarizeRegion uploads the selected screenshot to S3, sends the public URL
|
// SummarizeRegion uploads the selected screenshot to S3, sends the public URL
|
||||||
// to the configured multimodal LLM, and copies the resulting summary.
|
// to the configured multimodal LLM, and copies the resulting summary.
|
||||||
func (a *App) SummarizeRegion(result CaptureResult) error {
|
func (a *App) SummarizeRegion(result CaptureResult) error {
|
||||||
@@ -1008,6 +1111,29 @@ func (a *App) SaveNativeRegionToRemote(result CaptureResult) error {
|
|||||||
return a.runSaveRemotePipeline(cropped)
|
return a.runSaveRemotePipeline(cropped)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// UploadNativeRegionToFTP is the macOS AppKit overlay equivalent of
|
||||||
|
// UploadRegionToFTP. The native panel has already closed when this runs.
|
||||||
|
func (a *App) UploadNativeRegionToFTP(result CaptureResult) error {
|
||||||
|
pc, err := a.consumePendingCapture()
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("UploadNativeRegionToFTP: no pending capture", "err", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
a.capturing.Store(false)
|
||||||
|
hideDockIcon()
|
||||||
|
}()
|
||||||
|
|
||||||
|
flushFrame()
|
||||||
|
cropped, err := a.captureSelectedPNG(result, pc)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("UploadNativeRegionToFTP: capture failed", "err", err)
|
||||||
|
wruntime.EventsEmit(a.ctx, "upload:failure", err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return a.runFTPUploadPipeline(cropped)
|
||||||
|
}
|
||||||
|
|
||||||
// SummarizeNativeRegion is the macOS-native overlay equivalent of
|
// SummarizeNativeRegion is the macOS-native overlay equivalent of
|
||||||
// SummarizeRegion. The AppKit panel is already closed before this runs.
|
// SummarizeRegion. The AppKit panel is already closed before this runs.
|
||||||
func (a *App) SummarizeNativeRegion(result CaptureResult) error {
|
func (a *App) SummarizeNativeRegion(result CaptureResult) error {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
"build": "vue-tsc --noEmit && vite build",
|
"build": "vue-tsc --noEmit && vite build",
|
||||||
|
"test": "node --test tests/*.test.ts",
|
||||||
"preview": "vite preview"
|
"preview": "vite preview"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
|||||||
@@ -1 +1 @@
|
|||||||
bb7ffb87329c9ad4990374471d4ce9a4
|
e2d56b98c3c8ae5968db0bbb461b5615
|
||||||
+14
-1
@@ -22,6 +22,7 @@ import {
|
|||||||
CopyRegionImage,
|
CopyRegionImage,
|
||||||
SaveRegionImage,
|
SaveRegionImage,
|
||||||
SaveRegionToRemote,
|
SaveRegionToRemote,
|
||||||
|
UploadRegionToFTP,
|
||||||
SummarizeRegion,
|
SummarizeRegion,
|
||||||
ExtractTextRegion,
|
ExtractTextRegion,
|
||||||
CancelRegion,
|
CancelRegion,
|
||||||
@@ -59,7 +60,7 @@ async function loadThemePreference() {
|
|||||||
// `SettingsTab` is hoisted to the App shell so the sidebar (which lives
|
// `SettingsTab` is hoisted to the App shell so the sidebar (which lives
|
||||||
// here) and the inner SettingsView (which renders the matching card) can
|
// here) and the inner SettingsView (which renders the matching card) can
|
||||||
// share a single source of truth without an event bus.
|
// share a single source of truth without an event bus.
|
||||||
type SettingsTab = 'general' | 's3' | 'ssh' | 'llm' | 'ocr'
|
type SettingsTab = 'general' | 's3' | 'ftp' | 'ssh' | 'llm' | 'ocr'
|
||||||
const activeTab = ref<SettingsTab>('general')
|
const activeTab = ref<SettingsTab>('general')
|
||||||
|
|
||||||
// Sidebar entries are declarative so adding a destination type later is
|
// Sidebar entries are declarative so adding a destination type later is
|
||||||
@@ -67,6 +68,7 @@ const activeTab = ref<SettingsTab>('general')
|
|||||||
const sidebarItems: Array<{ id: SettingsTab; label: string }> = [
|
const sidebarItems: Array<{ id: SettingsTab; label: string }> = [
|
||||||
{ id: 'general', label: '通用设置' },
|
{ id: 'general', label: '通用设置' },
|
||||||
{ id: 's3', label: '对象存储' },
|
{ id: 's3', label: '对象存储' },
|
||||||
|
{ id: 'ftp', label: '文件服务' },
|
||||||
{ id: 'ssh', label: '远程主机' },
|
{ id: 'ssh', label: '远程主机' },
|
||||||
{ id: 'llm', label: '智能识图' },
|
{ id: 'llm', label: '智能识图' },
|
||||||
{ id: 'ocr', label: '文字提取' },
|
{ id: 'ocr', label: '文字提取' },
|
||||||
@@ -184,6 +186,16 @@ async function onOverlaySaveRemote(rect: OverlayResult) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function onOverlayUploadFTP(rect: OverlayResult) {
|
||||||
|
mode.value = 'settings'
|
||||||
|
overlayPayload.value = null
|
||||||
|
try {
|
||||||
|
await UploadRegionToFTP(rect as any)
|
||||||
|
} catch {
|
||||||
|
/* Surfaced via upload:failure */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function onOverlaySummarize(rect: OverlayResult) {
|
async function onOverlaySummarize(rect: OverlayResult) {
|
||||||
mode.value = 'settings'
|
mode.value = 'settings'
|
||||||
overlayPayload.value = null
|
overlayPayload.value = null
|
||||||
@@ -275,6 +287,7 @@ onUnmounted(() => {
|
|||||||
@copy="onOverlayCopy"
|
@copy="onOverlayCopy"
|
||||||
@save="onOverlaySave"
|
@save="onOverlaySave"
|
||||||
@save-remote="onOverlaySaveRemote"
|
@save-remote="onOverlaySaveRemote"
|
||||||
|
@upload-ftp="onOverlayUploadFTP"
|
||||||
@summarize="onOverlaySummarize"
|
@summarize="onOverlaySummarize"
|
||||||
@ocr="onOverlayOCR"
|
@ocr="onOverlayOCR"
|
||||||
@cancel="onOverlayCancel"
|
@cancel="onOverlayCancel"
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg"><path d="M128 128h768v256H128V128zm64 64v128h640V192H192zm64 48h64v32h-64v-32zM128 448h416v64H192v192h352v64H128V448zm560-32 160 160-45.248 45.248L720 538.496V832h-64V538.496l-82.752 82.752L528 576l160-160z" fill="currentColor"></path></svg>
|
||||||
|
After Width: | Height: | Size: 306 B |
@@ -0,0 +1,28 @@
|
|||||||
|
export interface AnnotationPoint {
|
||||||
|
x: number
|
||||||
|
y: number
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PointCollection {
|
||||||
|
points: AnnotationPoint[]
|
||||||
|
}
|
||||||
|
|
||||||
|
// Annotations are stored relative to the selection origin. Resizing from the
|
||||||
|
// top or left moves that origin, so offset the local points in the opposite
|
||||||
|
// direction to keep them attached to the same screen pixels.
|
||||||
|
export function preserveAnnotationScreenPositions(
|
||||||
|
annotations: PointCollection[],
|
||||||
|
previousOrigin: AnnotationPoint,
|
||||||
|
nextOrigin: AnnotationPoint
|
||||||
|
) {
|
||||||
|
const dx = previousOrigin.x - nextOrigin.x
|
||||||
|
const dy = previousOrigin.y - nextOrigin.y
|
||||||
|
if (dx === 0 && dy === 0) return
|
||||||
|
|
||||||
|
for (const annotation of annotations) {
|
||||||
|
for (const point of annotation.points) {
|
||||||
|
point.x += dx
|
||||||
|
point.y += dy
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,9 @@ import cancelIcon from '../assets/icons/cancel.svg?raw'
|
|||||||
import copyIcon from '../assets/icons/copy.svg?raw'
|
import copyIcon from '../assets/icons/copy.svg?raw'
|
||||||
import saveIcon from '../assets/icons/save-local.svg?raw'
|
import saveIcon from '../assets/icons/save-local.svg?raw'
|
||||||
import saveRemoteIcon from '../assets/icons/save-remote.svg?raw'
|
import saveRemoteIcon from '../assets/icons/save-remote.svg?raw'
|
||||||
|
import ftpIcon from '../assets/icons/ftp.svg?raw'
|
||||||
import uploadIcon from '../assets/icons/upload.svg?raw'
|
import uploadIcon from '../assets/icons/upload.svg?raw'
|
||||||
|
import { preserveAnnotationScreenPositions } from '../utils/annotationGeometry'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
width: number
|
width: number
|
||||||
@@ -23,7 +25,8 @@ interface Rect {
|
|||||||
h: number
|
h: number
|
||||||
}
|
}
|
||||||
|
|
||||||
type Tool = 'pen' | 'rect' | 'ellipse' | 'text'
|
type Tool = 'pen' | 'line' | 'arrow' | 'rect' | 'ellipse' | 'text' | 'mosaic-brush' | 'mosaic-rect'
|
||||||
|
type MosaicMode = 'brush' | 'rect'
|
||||||
interface Point {
|
interface Point {
|
||||||
x: number
|
x: number
|
||||||
y: number
|
y: number
|
||||||
@@ -54,6 +57,10 @@ const emit = defineEmits<{
|
|||||||
e: 'save-remote',
|
e: 'save-remote',
|
||||||
payload: { rect: Rect; annotations: Annotation[] }
|
payload: { rect: Rect; annotations: Annotation[] }
|
||||||
): void
|
): void
|
||||||
|
(
|
||||||
|
e: 'upload-ftp',
|
||||||
|
payload: { rect: Rect; annotations: Annotation[] }
|
||||||
|
): void
|
||||||
(
|
(
|
||||||
e: 'summarize',
|
e: 'summarize',
|
||||||
payload: { rect: Rect; annotations: Annotation[] }
|
payload: { rect: Rect; annotations: Annotation[] }
|
||||||
@@ -72,6 +79,8 @@ const activeTool = ref<Tool>('pen')
|
|||||||
const activeColor = ref('#ef4444')
|
const activeColor = ref('#ef4444')
|
||||||
const activeStrokeWidth = ref(3)
|
const activeStrokeWidth = ref(3)
|
||||||
const activeFontSize = ref(20)
|
const activeFontSize = ref(20)
|
||||||
|
const mosaicMode = ref<MosaicMode>('brush')
|
||||||
|
const mosaicBrushWidth = ref(24)
|
||||||
const textDraft = ref<{
|
const textDraft = ref<{
|
||||||
point: Point
|
point: Point
|
||||||
value: string
|
value: string
|
||||||
@@ -99,6 +108,7 @@ const textDragOriginalPoint = ref<Point | null>(null)
|
|||||||
|
|
||||||
const DEFAULT_TEXT_FONT_SIZE = 20
|
const DEFAULT_TEXT_FONT_SIZE = 20
|
||||||
const STROKE_WIDTHS = [2, 4, 6]
|
const STROKE_WIDTHS = [2, 4, 6]
|
||||||
|
const MOSAIC_WIDTHS = [16, 24, 36, 52]
|
||||||
const FONT_SIZES = [16, 20, 28, 36]
|
const FONT_SIZES = [16, 20, 28, 36]
|
||||||
|
|
||||||
const colors = [
|
const colors = [
|
||||||
@@ -141,17 +151,18 @@ const sizeLabel = computed(() => {
|
|||||||
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
|
return `${Math.round(rect.value.w)} × ${Math.round(rect.value.h)}`
|
||||||
})
|
})
|
||||||
|
|
||||||
const MARK_TOOLBAR_W = 178
|
const MARK_TOOLBAR_W = 280
|
||||||
const ACTION_TOOLBAR_W = 252
|
const ACTION_TOOLBAR_W = 288
|
||||||
const TOOLBAR_GROUP_GAP = 8
|
const TOOLBAR_GROUP_GAP = 8
|
||||||
|
|
||||||
const toolOrder: Tool[] = ['pen', 'rect', 'ellipse', 'text']
|
const toolOrder: Tool[] = ['pen', 'line', 'arrow', 'rect', 'ellipse', 'text', 'mosaic-brush', 'mosaic-rect']
|
||||||
|
|
||||||
const toolSettingsPos = computed(() => {
|
const toolSettingsPos = computed(() => {
|
||||||
if (!leftToolbarPos.value || !rect.value || !activeTool.value) return null
|
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 menuH = 58
|
||||||
const buttonIndex = toolOrder.indexOf(activeTool.value)
|
const buttonIndex = isMosaic ? 6 : toolOrder.indexOf(activeTool.value)
|
||||||
const buttonCenter = 4 + buttonIndex * 34 + 14
|
const buttonCenter = 4 + buttonIndex * 34 + 14
|
||||||
let x = leftToolbarPos.value.x
|
let x = leftToolbarPos.value.x
|
||||||
let y = leftToolbarPos.value.y + 44
|
let y = leftToolbarPos.value.y + 44
|
||||||
@@ -305,6 +316,28 @@ function textRenderBox(annotation: Annotation) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function arrowHeadPoints(annotation: Annotation) {
|
||||||
|
if (annotation.points.length < 2) return ''
|
||||||
|
const start = annotation.points[0]
|
||||||
|
const end = annotation.points[annotation.points.length - 1]
|
||||||
|
const dx = end.x - start.x
|
||||||
|
const dy = end.y - start.y
|
||||||
|
const length = Math.hypot(dx, dy)
|
||||||
|
if (length < 1) return ''
|
||||||
|
const headLength = Math.min(length * 0.45, Math.max(10, (annotation.strokeWidth || 3) * 4))
|
||||||
|
const angle = Math.atan2(dy, dx)
|
||||||
|
const spread = Math.PI / 6
|
||||||
|
const left = {
|
||||||
|
x: end.x - headLength * Math.cos(angle - spread),
|
||||||
|
y: end.y - headLength * Math.sin(angle - spread),
|
||||||
|
}
|
||||||
|
const right = {
|
||||||
|
x: end.x - headLength * Math.cos(angle + spread),
|
||||||
|
y: end.y - headLength * Math.sin(angle + spread),
|
||||||
|
}
|
||||||
|
return `${left.x},${left.y} ${end.x},${end.y} ${right.x},${right.y}`
|
||||||
|
}
|
||||||
|
|
||||||
function textAnnotationIndexAtPoint(p: Point) {
|
function textAnnotationIndexAtPoint(p: Point) {
|
||||||
if (!rect.value) return null
|
if (!rect.value) return null
|
||||||
for (let i = annotations.value.length - 1; i >= 0; i--) {
|
for (let i = annotations.value.length - 1; i >= 0; i--) {
|
||||||
@@ -427,7 +460,7 @@ function onSelectionMouseDown(e: MouseEvent) {
|
|||||||
draftAnnotation.value = {
|
draftAnnotation.value = {
|
||||||
tool: activeTool.value,
|
tool: activeTool.value,
|
||||||
color: activeColor.value,
|
color: activeColor.value,
|
||||||
strokeWidth: activeStrokeWidth.value,
|
strokeWidth: activeTool.value === 'mosaic-brush' ? mosaicBrushWidth.value : activeStrokeWidth.value,
|
||||||
points: [local],
|
points: [local],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -461,7 +494,7 @@ function onMouseMove(e: MouseEvent) {
|
|||||||
annotation.points[0] = clampTextLocalPoint(next, annotation)
|
annotation.points[0] = clampTextLocalPoint(next, annotation)
|
||||||
}
|
}
|
||||||
} else if (dragMode.value === 'annotating' && draftAnnotation.value) {
|
} 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))
|
draftAnnotation.value.points.push(localPoint(p))
|
||||||
} else {
|
} else {
|
||||||
draftAnnotation.value.points = [
|
draftAnnotation.value.points = [
|
||||||
@@ -507,18 +540,35 @@ function resizeSelection(p: Point) {
|
|||||||
right = clamp(right, 0, props.width)
|
right = clamp(right, 0, props.width)
|
||||||
top = clamp(top, 0, props.height)
|
top = clamp(top, 0, props.height)
|
||||||
bottom = clamp(bottom, 0, props.height)
|
bottom = clamp(bottom, 0, props.height)
|
||||||
rect.value = {
|
const nextRect = {
|
||||||
x: Math.min(left, right),
|
x: Math.min(left, right),
|
||||||
y: Math.min(top, bottom),
|
y: Math.min(top, bottom),
|
||||||
w: Math.abs(right - left),
|
w: Math.abs(right - left),
|
||||||
h: Math.abs(bottom - top),
|
h: Math.abs(bottom - top),
|
||||||
}
|
}
|
||||||
|
if (rect.value) {
|
||||||
|
preserveAnnotationScreenPositions(annotations.value, rect.value, nextRect)
|
||||||
|
}
|
||||||
|
rect.value = nextRect
|
||||||
}
|
}
|
||||||
|
|
||||||
function selectTool(tool: Tool) {
|
function selectTool(tool: Tool) {
|
||||||
activeTool.value = 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) {
|
function chooseColor(color: string) {
|
||||||
activeColor.value = color
|
activeColor.value = color
|
||||||
if (textDraft.value) {
|
if (textDraft.value) {
|
||||||
@@ -571,6 +621,10 @@ function onSaveRemote() {
|
|||||||
emitAction('save-remote')
|
emitAction('save-remote')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function onUploadFTP() {
|
||||||
|
emitAction('upload-ftp')
|
||||||
|
}
|
||||||
|
|
||||||
function onSummarize() {
|
function onSummarize() {
|
||||||
emitAction('summarize')
|
emitAction('summarize')
|
||||||
}
|
}
|
||||||
@@ -579,7 +633,16 @@ function onOCR() {
|
|||||||
emitAction('ocr')
|
emitAction('ocr')
|
||||||
}
|
}
|
||||||
|
|
||||||
function emitAction(action: 'confirm' | 'copy' | 'save' | 'save-remote' | 'summarize' | 'ocr') {
|
function emitAction(
|
||||||
|
action:
|
||||||
|
| 'confirm'
|
||||||
|
| 'copy'
|
||||||
|
| 'save'
|
||||||
|
| 'save-remote'
|
||||||
|
| 'upload-ftp'
|
||||||
|
| 'summarize'
|
||||||
|
| 'ocr'
|
||||||
|
) {
|
||||||
if (!rect.value) return
|
if (!rect.value) return
|
||||||
commitTextDraft()
|
commitTextDraft()
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -590,6 +653,7 @@ function emitAction(action: 'confirm' | 'copy' | 'save' | 'save-remote' | 'summa
|
|||||||
if (action === 'copy') emit('copy', payload)
|
if (action === 'copy') emit('copy', payload)
|
||||||
if (action === 'save') emit('save', payload)
|
if (action === 'save') emit('save', payload)
|
||||||
if (action === 'save-remote') emit('save-remote', payload)
|
if (action === 'save-remote') emit('save-remote', payload)
|
||||||
|
if (action === 'upload-ftp') emit('upload-ftp', payload)
|
||||||
if (action === 'summarize') emit('summarize', payload)
|
if (action === 'summarize') emit('summarize', payload)
|
||||||
if (action === 'ocr') emit('ocr', payload)
|
if (action === 'ocr') emit('ocr', payload)
|
||||||
}
|
}
|
||||||
@@ -729,6 +793,13 @@ onUnmounted(() => {
|
|||||||
:viewBox="`0 0 ${width} ${height}`"
|
:viewBox="`0 0 ${width} ${height}`"
|
||||||
preserveAspectRatio="none"
|
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" />
|
<path :d="maskPath" fill="rgba(0,0,0,0.45)" fill-rule="evenodd" />
|
||||||
<rect
|
<rect
|
||||||
v-if="rect"
|
v-if="rect"
|
||||||
@@ -751,6 +822,35 @@ onUnmounted(() => {
|
|||||||
stroke-linejoin="round"
|
stroke-linejoin="round"
|
||||||
fill="none"
|
fill="none"
|
||||||
/>
|
/>
|
||||||
|
<line
|
||||||
|
v-else-if="annotation.tool === 'line' && annotation.points.length >= 2"
|
||||||
|
:x1="annotation.points[0].x"
|
||||||
|
:y1="annotation.points[0].y"
|
||||||
|
:x2="annotation.points[annotation.points.length - 1].x"
|
||||||
|
:y2="annotation.points[annotation.points.length - 1].y"
|
||||||
|
:stroke="annotation.color"
|
||||||
|
:stroke-width="annotation.strokeWidth || 3"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
<g v-else-if="annotation.tool === 'arrow' && annotation.points.length >= 2">
|
||||||
|
<line
|
||||||
|
:x1="annotation.points[0].x"
|
||||||
|
:y1="annotation.points[0].y"
|
||||||
|
:x2="annotation.points[annotation.points.length - 1].x"
|
||||||
|
:y2="annotation.points[annotation.points.length - 1].y"
|
||||||
|
:stroke="annotation.color"
|
||||||
|
:stroke-width="annotation.strokeWidth || 3"
|
||||||
|
stroke-linecap="round"
|
||||||
|
/>
|
||||||
|
<polyline
|
||||||
|
:points="arrowHeadPoints(annotation)"
|
||||||
|
:stroke="annotation.color"
|
||||||
|
:stroke-width="annotation.strokeWidth || 3"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
fill="none"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
<rect
|
<rect
|
||||||
v-else-if="annotation.tool === 'rect' && annotation.points.length >= 2"
|
v-else-if="annotation.tool === 'rect' && annotation.points.length >= 2"
|
||||||
:x="Math.min(annotation.points[0].x, annotation.points[1].x)"
|
:x="Math.min(annotation.points[0].x, annotation.points[1].x)"
|
||||||
@@ -792,6 +892,25 @@ onUnmounted(() => {
|
|||||||
{{ annotation.text }}
|
{{ annotation.text }}
|
||||||
</text>
|
</text>
|
||||||
</template>
|
</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>
|
</g>
|
||||||
</svg>
|
</svg>
|
||||||
|
|
||||||
@@ -863,12 +982,37 @@ onUnmounted(() => {
|
|||||||
<button
|
<button
|
||||||
class="icon-btn"
|
class="icon-btn"
|
||||||
:class="{ active: activeTool === 'pen' }"
|
:class="{ active: activeTool === 'pen' }"
|
||||||
title="划线标记"
|
title="画笔标记"
|
||||||
|
aria-label="画笔标记"
|
||||||
@click="selectTool('pen')"
|
@click="selectTool('pen')"
|
||||||
>
|
>
|
||||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
<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.5 5.5 4-4 4 4-4 4" />
|
||||||
<path d="M14 5l5 3" />
|
<path d="m17.5 8.5-7.8 7.8" />
|
||||||
|
<path d="M11 14.8c.8 2.8-.7 5.5-3.7 6.3-1.8.5-3.7.1-5.3-.9 2.1-.4 2.8-1.5 3.1-3.3.4-2.5 3.3-3.8 5.9-2.1Z" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="icon-btn"
|
||||||
|
:class="{ active: activeTool === 'line' }"
|
||||||
|
title="直线标记"
|
||||||
|
aria-label="直线标记"
|
||||||
|
@click="selectTool('line')"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M5 19 19 5" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
class="icon-btn"
|
||||||
|
:class="{ active: activeTool === 'arrow' }"
|
||||||
|
title="箭头标记"
|
||||||
|
aria-label="箭头标记"
|
||||||
|
@click="selectTool('arrow')"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||||
|
<path d="M5 19 19 5" />
|
||||||
|
<path d="M11 5h8v8" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
@@ -903,6 +1047,21 @@ onUnmounted(() => {
|
|||||||
<path d="M9 19h6" />
|
<path d="M9 19h6" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</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
|
<button
|
||||||
class="icon-btn"
|
class="icon-btn"
|
||||||
:class="{ muted: annotations.length === 0 }"
|
:class="{ muted: annotations.length === 0 }"
|
||||||
@@ -928,7 +1087,55 @@ onUnmounted(() => {
|
|||||||
}"
|
}"
|
||||||
@mousedown.stop
|
@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
|
<button
|
||||||
v-for="widthValue in STROKE_WIDTHS"
|
v-for="widthValue in STROKE_WIDTHS"
|
||||||
:key="widthValue"
|
:key="widthValue"
|
||||||
@@ -952,8 +1159,8 @@ onUnmounted(() => {
|
|||||||
{{ size }}
|
{{ size }}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="settings-divider" />
|
<div v-if="!activeTool.startsWith('mosaic-')" class="settings-divider" />
|
||||||
<div class="setting-group color-group">
|
<div v-if="!activeTool.startsWith('mosaic-')" class="setting-group color-group">
|
||||||
<button
|
<button
|
||||||
v-for="color in colors"
|
v-for="color in colors"
|
||||||
:key="color"
|
:key="color"
|
||||||
@@ -995,11 +1202,18 @@ onUnmounted(() => {
|
|||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
class="action-btn"
|
class="action-btn"
|
||||||
data-tip="保存远端"
|
data-tip="上传 SSH/SCP"
|
||||||
aria-label="保存远端"
|
aria-label="上传 SSH/SCP"
|
||||||
@click="onSaveRemote"
|
@click="onSaveRemote"
|
||||||
v-html="saveRemoteIcon"
|
v-html="saveRemoteIcon"
|
||||||
/>
|
/>
|
||||||
|
<button
|
||||||
|
class="action-btn"
|
||||||
|
data-tip="上传 FTP/SFTP"
|
||||||
|
aria-label="上传 FTP/SFTP"
|
||||||
|
@click="onUploadFTP"
|
||||||
|
v-html="ftpIcon"
|
||||||
|
/>
|
||||||
<button
|
<button
|
||||||
class="action-btn"
|
class="action-btn"
|
||||||
data-tip="提取文字"
|
data-tip="提取文字"
|
||||||
@@ -1030,8 +1244,8 @@ onUnmounted(() => {
|
|||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
class="action-btn primary"
|
class="action-btn primary"
|
||||||
data-tip="上传云端"
|
data-tip="上传 S3"
|
||||||
aria-label="上传云端"
|
aria-label="上传 S3"
|
||||||
@click="onConfirm"
|
@click="onConfirm"
|
||||||
v-html="uploadIcon"
|
v-html="uploadIcon"
|
||||||
/>
|
/>
|
||||||
@@ -1145,17 +1359,20 @@ onUnmounted(() => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.mark-toolbar {
|
.mark-toolbar {
|
||||||
width: 178px;
|
width: 280px;
|
||||||
}
|
}
|
||||||
.action-toolbar {
|
.action-toolbar {
|
||||||
width: 252px;
|
box-sizing: border-box;
|
||||||
|
width: 288px;
|
||||||
|
gap: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.icon-btn,
|
.icon-btn,
|
||||||
.action-btn,
|
.action-btn,
|
||||||
.swatch,
|
.swatch,
|
||||||
.stroke-choice,
|
.stroke-choice,
|
||||||
.font-choice {
|
.font-choice,
|
||||||
|
.mode-choice {
|
||||||
font-family: inherit;
|
font-family: inherit;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1313,6 +1530,53 @@ onUnmounted(() => {
|
|||||||
background: transparent;
|
background: transparent;
|
||||||
cursor: pointer;
|
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:hover,
|
||||||
.stroke-choice.active,
|
.stroke-choice.active,
|
||||||
.font-choice:hover,
|
.font-choice:hover,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
*
|
*
|
||||||
* • "general" — the global hotkey / capture parameters.
|
* • "general" — the global hotkey / capture parameters.
|
||||||
* • "s3" — S3-compatible object-storage credentials.
|
* • "s3" — S3-compatible object-storage credentials.
|
||||||
|
* • "ftp" — FTP/SFTP file-transfer destination.
|
||||||
* • "ssh" — SSH/SCP destination for the "save remote" button.
|
* • "ssh" — SSH/SCP destination for the "save remote" button.
|
||||||
* • "llm" — multimodal screenshot summary provider settings.
|
* • "llm" — multimodal screenshot summary provider settings.
|
||||||
* • "ocr" — cloud OCR provider settings for text extraction.
|
* • "ocr" — cloud OCR provider settings for text extraction.
|
||||||
@@ -18,14 +19,16 @@ import {
|
|||||||
GetConfig,
|
GetConfig,
|
||||||
SaveConfig,
|
SaveConfig,
|
||||||
TestConnection,
|
TestConnection,
|
||||||
|
TestFTPConnection,
|
||||||
TestSSHConnection,
|
TestSSHConnection,
|
||||||
CaptureNow,
|
CaptureNow,
|
||||||
} from '../../wailsjs/go/main/App'
|
} from '../../wailsjs/go/main/App'
|
||||||
|
|
||||||
// Tab discriminator shared with the App shell. Kept as a string union so
|
// Tab discriminator shared with the App shell. Kept as a string union so
|
||||||
// the parent can pass the value without importing a type from this view.
|
// the parent can pass the value without importing a type from this view.
|
||||||
type TabId = 'general' | 's3' | 'ssh' | 'llm' | 'ocr'
|
type TabId = 'general' | 's3' | 'ftp' | 'ssh' | 'llm' | 'ocr'
|
||||||
type ThemeMode = 'auto' | 'light' | 'dark'
|
type ThemeMode = 'auto' | 'light' | 'dark'
|
||||||
|
type FTPProtocol = 'ftp' | 'sftp'
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
tab: TabId
|
tab: TabId
|
||||||
@@ -59,6 +62,20 @@ interface SSHConfig {
|
|||||||
connectTimeoutSecs: number
|
connectTimeoutSecs: number
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface FTPConfig {
|
||||||
|
protocol: FTPProtocol
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
user: string
|
||||||
|
authMethod: 'password' | 'key'
|
||||||
|
password: string
|
||||||
|
rootDirectory: string
|
||||||
|
pathPrefix: string
|
||||||
|
strictHostKey: boolean
|
||||||
|
knownHostsPath: string
|
||||||
|
connectTimeoutSecs: number
|
||||||
|
}
|
||||||
|
|
||||||
interface LLMProviderConfig {
|
interface LLMProviderConfig {
|
||||||
label: string
|
label: string
|
||||||
baseUrl: string
|
baseUrl: string
|
||||||
@@ -97,6 +114,7 @@ interface AppConfig {
|
|||||||
theme: ThemeMode
|
theme: ThemeMode
|
||||||
s3: S3Config
|
s3: S3Config
|
||||||
ssh: SSHConfig
|
ssh: SSHConfig
|
||||||
|
ftp: FTPConfig
|
||||||
llm: LLMConfig
|
llm: LLMConfig
|
||||||
ocr: OCRConfig
|
ocr: OCRConfig
|
||||||
}
|
}
|
||||||
@@ -145,6 +163,19 @@ function defaultConfig(): AppConfig {
|
|||||||
publicUrlBase: '',
|
publicUrlBase: '',
|
||||||
usePathStyle: true,
|
usePathStyle: true,
|
||||||
},
|
},
|
||||||
|
ftp: {
|
||||||
|
protocol: 'ftp',
|
||||||
|
host: '',
|
||||||
|
port: 21,
|
||||||
|
user: '',
|
||||||
|
authMethod: 'password',
|
||||||
|
password: '',
|
||||||
|
rootDirectory: '/',
|
||||||
|
pathPrefix: 'snapgo/',
|
||||||
|
strictHostKey: false,
|
||||||
|
knownHostsPath: '',
|
||||||
|
connectTimeoutSecs: 10,
|
||||||
|
},
|
||||||
ssh: {
|
ssh: {
|
||||||
host: '',
|
host: '',
|
||||||
port: 22,
|
port: 22,
|
||||||
@@ -223,6 +254,7 @@ const config = ref<AppConfig>(defaultConfig())
|
|||||||
|
|
||||||
const saving = ref(false)
|
const saving = ref(false)
|
||||||
const testing = ref(false)
|
const testing = ref(false)
|
||||||
|
const testingFTP = ref(false)
|
||||||
const testingSSH = ref(false)
|
const testingSSH = ref(false)
|
||||||
const message = ref<{ kind: 'ok' | 'err'; text: string } | null>(null)
|
const message = ref<{ kind: 'ok' | 'err'; text: string } | null>(null)
|
||||||
|
|
||||||
@@ -240,6 +272,48 @@ const sshPathDisplay = computed({
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// FTP and SFTP both upload relative to the authenticated login directory.
|
||||||
|
// RootDirectory is display-only: it is prepended to the uploaded relative path
|
||||||
|
// when that path is copied, without changing where the file is uploaded.
|
||||||
|
const ftpPathDisplay = computed({
|
||||||
|
get: () => config.value.ftp.pathPrefix,
|
||||||
|
set: (raw: string) => {
|
||||||
|
let cleaned = raw.trim()
|
||||||
|
cleaned = cleaned.replace(/^~/, '')
|
||||||
|
cleaned = cleaned.replace(/^\/+/, '')
|
||||||
|
config.value.ftp.pathPrefix = cleaned
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const ftpCopiedPathPreview = computed(() => {
|
||||||
|
const root = config.value.ftp.rootDirectory.trim().replace(/\/+$/, '')
|
||||||
|
const remote = config.value.ftp.pathPrefix
|
||||||
|
.trim()
|
||||||
|
.replace(/^\/+|\/+$/g, '')
|
||||||
|
const remotePrefix = remote ? `${remote}/` : ''
|
||||||
|
return `${root || (config.value.ftp.protocol === 'sftp' ? '~' : '')}/${remotePrefix}2026/07/20260713-110413-18lnbx.png`
|
||||||
|
})
|
||||||
|
|
||||||
|
function changeFTPProtocol(event: Event) {
|
||||||
|
const next = (event.target as HTMLSelectElement).value as FTPProtocol
|
||||||
|
const previous = config.value.ftp.protocol
|
||||||
|
const previousDefault = previous === 'sftp' ? 22 : 21
|
||||||
|
const previousRootDefault = previous === 'sftp' ? '~/' : '/'
|
||||||
|
if (config.value.ftp.port === previousDefault) {
|
||||||
|
config.value.ftp.port = next === 'sftp' ? 22 : 21
|
||||||
|
}
|
||||||
|
if (config.value.ftp.rootDirectory === previousRootDefault) {
|
||||||
|
config.value.ftp.rootDirectory = next === 'sftp' ? '~/' : '/'
|
||||||
|
}
|
||||||
|
config.value.ftp.protocol = next
|
||||||
|
}
|
||||||
|
|
||||||
|
function changeFTPAuthMethod(event: Event) {
|
||||||
|
config.value.ftp.authMethod = (event.target as HTMLSelectElement).value as
|
||||||
|
| 'password'
|
||||||
|
| 'key'
|
||||||
|
}
|
||||||
|
|
||||||
const activeLLMProvider = computed(() => {
|
const activeLLMProvider = computed(() => {
|
||||||
const id = config.value.llm.activeProvider || 'openai'
|
const id = config.value.llm.activeProvider || 'openai'
|
||||||
if (!config.value.llm.providers[id]) {
|
if (!config.value.llm.providers[id]) {
|
||||||
@@ -280,6 +354,7 @@ async function load() {
|
|||||||
Object.assign(merged, cfg)
|
Object.assign(merged, cfg)
|
||||||
merged.s3 = { ...merged.s3, ...(cfg as any).s3 }
|
merged.s3 = { ...merged.s3, ...(cfg as any).s3 }
|
||||||
merged.ssh = { ...merged.ssh, ...(cfg as any).ssh }
|
merged.ssh = { ...merged.ssh, ...(cfg as any).ssh }
|
||||||
|
merged.ftp = { ...merged.ftp, ...(cfg as any).ftp }
|
||||||
merged.llm = { ...merged.llm, ...(cfg as any).llm }
|
merged.llm = { ...merged.llm, ...(cfg as any).llm }
|
||||||
merged.llm.providers = {
|
merged.llm.providers = {
|
||||||
...defaultConfig().llm.providers,
|
...defaultConfig().llm.providers,
|
||||||
@@ -320,6 +395,21 @@ async function test() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function testFTP() {
|
||||||
|
testingFTP.value = true
|
||||||
|
try {
|
||||||
|
await TestFTPConnection(config.value.ftp as any)
|
||||||
|
flash(
|
||||||
|
'ok',
|
||||||
|
`${config.value.ftp.protocol.toUpperCase()} connection OK — remote directory is writable`
|
||||||
|
)
|
||||||
|
} catch (err: any) {
|
||||||
|
flash('err', `FTP/SFTP test failed: ${err?.message ?? err}`)
|
||||||
|
} finally {
|
||||||
|
testingFTP.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function testSSH() {
|
async function testSSH() {
|
||||||
testingSSH.value = true
|
testingSSH.value = true
|
||||||
try {
|
try {
|
||||||
@@ -450,6 +540,130 @@ onMounted(load)
|
|||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<!-- FTP/SFTP tab — file-transfer destination for its toolbar action. -->
|
||||||
|
<section v-if="props.tab === 'ftp'" class="card">
|
||||||
|
<h2>文件服务</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<label class="field">
|
||||||
|
<span>Protocol</span>
|
||||||
|
<select :value="config.ftp.protocol" @change="changeFTPProtocol">
|
||||||
|
<option value="ftp">FTP</option>
|
||||||
|
<option value="sftp">SFTP (SSH File Transfer Protocol)</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Port</span>
|
||||||
|
<input
|
||||||
|
v-model.number="config.ftp.port"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="65535"
|
||||||
|
:placeholder="config.ftp.protocol === 'sftp' ? '22' : '21'"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Host (IP or domain) *</span>
|
||||||
|
<input v-model.trim="config.ftp.host" placeholder="files.example.com" />
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>User *</span>
|
||||||
|
<input v-model.trim="config.ftp.user" placeholder="snapgo" />
|
||||||
|
</label>
|
||||||
|
<label
|
||||||
|
v-if="config.ftp.protocol === 'sftp'"
|
||||||
|
key="sftp-auth-method"
|
||||||
|
class="field"
|
||||||
|
>
|
||||||
|
<span>Auth method</span>
|
||||||
|
<select
|
||||||
|
:value="config.ftp.authMethod"
|
||||||
|
@change="changeFTPAuthMethod"
|
||||||
|
>
|
||||||
|
<option value="password">Password</option>
|
||||||
|
<option value="key">SSH-Key</option>
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
<label
|
||||||
|
v-if="config.ftp.protocol === 'ftp' || config.ftp.authMethod === 'password'"
|
||||||
|
:key="`${config.ftp.protocol}-password`"
|
||||||
|
class="field"
|
||||||
|
>
|
||||||
|
<span>Password</span>
|
||||||
|
<input v-model="config.ftp.password" type="password" />
|
||||||
|
</label>
|
||||||
|
<label class="field full">
|
||||||
|
<span>根目录(仅用于拼接复制路径)</span>
|
||||||
|
<input
|
||||||
|
v-model.trim="config.ftp.rootDirectory"
|
||||||
|
:placeholder="config.ftp.protocol === 'sftp' ? '~/' : '/'"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label class="field full">
|
||||||
|
<span>Remote directory(登录目录下的上传目录)</span>
|
||||||
|
<input
|
||||||
|
v-model="ftpPathDisplay"
|
||||||
|
placeholder="snapgo/"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label class="field">
|
||||||
|
<span>Connect timeout (sec)</span>
|
||||||
|
<input
|
||||||
|
v-model.number="config.ftp.connectTimeoutSecs"
|
||||||
|
type="number"
|
||||||
|
min="1"
|
||||||
|
max="120"
|
||||||
|
placeholder="10"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label v-if="config.ftp.protocol === 'sftp'" class="field">
|
||||||
|
<span>Known hosts path</span>
|
||||||
|
<input
|
||||||
|
v-model="config.ftp.knownHostsPath"
|
||||||
|
placeholder="~/.ssh/known_hosts"
|
||||||
|
:disabled="!config.ftp.strictHostKey"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label v-if="config.ftp.protocol === 'sftp'" class="field checkbox">
|
||||||
|
<input type="checkbox" v-model="config.ftp.strictHostKey" />
|
||||||
|
<span>Strict host key checking (recommended)</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p class="hint">
|
||||||
|
复制路径示例:<code>{{ ftpCopiedPathPreview }}</code>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<p v-if="config.ftp.protocol === 'ftp'" class="hint warn">
|
||||||
|
FTP sends the username, password, and screenshot without encryption.
|
||||||
|
Prefer SFTP on networks you do not fully trust. SFTP is not FTPS.
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
v-else-if="config.ftp.authMethod === 'key'"
|
||||||
|
class="hint"
|
||||||
|
>
|
||||||
|
SSH-Key mode uses your <code>ssh-agent</code> and
|
||||||
|
<code>~/.ssh/id_*</code> keys.
|
||||||
|
</p>
|
||||||
|
<p
|
||||||
|
v-else-if="!config.ftp.strictHostKey"
|
||||||
|
class="hint warn"
|
||||||
|
>
|
||||||
|
Host key checking is disabled. Enable it for production servers to
|
||||||
|
detect server impersonation.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div class="actions">
|
||||||
|
<button class="btn" :disabled="testingFTP" @click="testFTP">
|
||||||
|
{{ testingFTP ? 'Testing…' : 'Test connection' }}
|
||||||
|
</button>
|
||||||
|
<button class="btn primary" :disabled="saving" @click="save">
|
||||||
|
{{ saving ? 'Saving…' : 'Save' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<!-- SSH-Conf tab — destination for the save-remote action. -->
|
<!-- SSH-Conf tab — destination for the save-remote action. -->
|
||||||
<section v-if="props.tab === 'ssh'" class="card">
|
<section v-if="props.tab === 'ssh'" class="card">
|
||||||
<h2>SSH / SCP destination</h2>
|
<h2>SSH / SCP destination</h2>
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import test from 'node:test'
|
||||||
|
|
||||||
|
import { preserveAnnotationScreenPositions } from '../src/utils/annotationGeometry.ts'
|
||||||
|
|
||||||
|
test('keeps annotation points at the same screen position when the origin moves', () => {
|
||||||
|
const annotations = [
|
||||||
|
{ points: [{ x: 30, y: 40 }, { x: 80, y: 90 }] },
|
||||||
|
{ points: [{ x: 12, y: 18 }] },
|
||||||
|
]
|
||||||
|
|
||||||
|
preserveAnnotationScreenPositions(
|
||||||
|
annotations,
|
||||||
|
{ x: 100, y: 200 },
|
||||||
|
{ x: 125, y: 230 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.deepEqual(annotations, [
|
||||||
|
{ points: [{ x: 5, y: 10 }, { x: 55, y: 60 }] },
|
||||||
|
{ points: [{ x: -13, y: -12 }] },
|
||||||
|
])
|
||||||
|
assert.deepEqual(
|
||||||
|
annotations[0].points.map((point) => ({
|
||||||
|
x: 125 + point.x,
|
||||||
|
y: 230 + point.y,
|
||||||
|
})),
|
||||||
|
[{ x: 130, y: 240 }, { x: 180, y: 290 }]
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
test('does not move annotations when only the right or bottom edge changes', () => {
|
||||||
|
const annotations = [{ points: [{ x: 30, y: 40 }] }]
|
||||||
|
|
||||||
|
preserveAnnotationScreenPositions(
|
||||||
|
annotations,
|
||||||
|
{ x: 100, y: 200 },
|
||||||
|
{ x: 100, y: 200 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.deepEqual(annotations, [{ points: [{ x: 30, y: 40 }] }])
|
||||||
|
})
|
||||||
|
|
||||||
|
test('preserves screen positions across repeated drags and an edge crossover', () => {
|
||||||
|
const annotations = [{ points: [{ x: 50, y: 60 }] }]
|
||||||
|
|
||||||
|
preserveAnnotationScreenPositions(
|
||||||
|
annotations,
|
||||||
|
{ x: 100, y: 100 },
|
||||||
|
{ x: 140, y: 130 }
|
||||||
|
)
|
||||||
|
preserveAnnotationScreenPositions(
|
||||||
|
annotations,
|
||||||
|
{ x: 140, y: 130 },
|
||||||
|
{ x: 300, y: 150 }
|
||||||
|
)
|
||||||
|
|
||||||
|
assert.deepEqual(annotations, [{ points: [{ x: -150, y: 10 }] }])
|
||||||
|
assert.deepEqual(
|
||||||
|
{
|
||||||
|
x: 300 + annotations[0].points[0].x,
|
||||||
|
y: 150 + annotations[0].points[0].y,
|
||||||
|
},
|
||||||
|
{ x: 150, y: 160 }
|
||||||
|
)
|
||||||
|
})
|
||||||
Vendored
+6
@@ -47,4 +47,10 @@ export function SummarizeRegion(arg1:main.CaptureResult):Promise<void>;
|
|||||||
|
|
||||||
export function TestConnection(arg1:domain.S3Config):Promise<void>;
|
export function TestConnection(arg1:domain.S3Config):Promise<void>;
|
||||||
|
|
||||||
|
export function TestFTPConnection(arg1:domain.FTPConfig):Promise<void>;
|
||||||
|
|
||||||
export function TestSSHConnection(arg1:domain.SSHConfig):Promise<void>;
|
export function TestSSHConnection(arg1:domain.SSHConfig):Promise<void>;
|
||||||
|
|
||||||
|
export function UploadNativeRegionToFTP(arg1:main.CaptureResult):Promise<void>;
|
||||||
|
|
||||||
|
export function UploadRegionToFTP(arg1:main.CaptureResult):Promise<void>;
|
||||||
|
|||||||
@@ -90,6 +90,18 @@ export function TestConnection(arg1) {
|
|||||||
return window['go']['main']['App']['TestConnection'](arg1);
|
return window['go']['main']['App']['TestConnection'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function TestFTPConnection(arg1) {
|
||||||
|
return window['go']['main']['App']['TestFTPConnection'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
export function TestSSHConnection(arg1) {
|
export function TestSSHConnection(arg1) {
|
||||||
return window['go']['main']['App']['TestSSHConnection'](arg1);
|
return window['go']['main']['App']['TestSSHConnection'](arg1);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function UploadNativeRegionToFTP(arg1) {
|
||||||
|
return window['go']['main']['App']['UploadNativeRegionToFTP'](arg1);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UploadRegionToFTP(arg1) {
|
||||||
|
return window['go']['main']['App']['UploadRegionToFTP'](arg1);
|
||||||
|
}
|
||||||
|
|||||||
@@ -179,6 +179,38 @@ export namespace domain {
|
|||||||
return a;
|
return a;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
export class FTPConfig {
|
||||||
|
protocol: string;
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
user: string;
|
||||||
|
authMethod: string;
|
||||||
|
password: string;
|
||||||
|
rootDirectory: string;
|
||||||
|
pathPrefix: string;
|
||||||
|
strictHostKey: boolean;
|
||||||
|
knownHostsPath: string;
|
||||||
|
connectTimeoutSecs: number;
|
||||||
|
|
||||||
|
static createFrom(source: any = {}) {
|
||||||
|
return new FTPConfig(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(source: any = {}) {
|
||||||
|
if ('string' === typeof source) source = JSON.parse(source);
|
||||||
|
this.protocol = source["protocol"];
|
||||||
|
this.host = source["host"];
|
||||||
|
this.port = source["port"];
|
||||||
|
this.user = source["user"];
|
||||||
|
this.authMethod = source["authMethod"];
|
||||||
|
this.password = source["password"];
|
||||||
|
this.rootDirectory = source["rootDirectory"];
|
||||||
|
this.pathPrefix = source["pathPrefix"];
|
||||||
|
this.strictHostKey = source["strictHostKey"];
|
||||||
|
this.knownHostsPath = source["knownHostsPath"];
|
||||||
|
this.connectTimeoutSecs = source["connectTimeoutSecs"];
|
||||||
|
}
|
||||||
|
}
|
||||||
export class SSHConfig {
|
export class SSHConfig {
|
||||||
host: string;
|
host: string;
|
||||||
port: number;
|
port: number;
|
||||||
@@ -238,6 +270,7 @@ export namespace domain {
|
|||||||
theme: string;
|
theme: string;
|
||||||
s3: S3Config;
|
s3: S3Config;
|
||||||
ssh: SSHConfig;
|
ssh: SSHConfig;
|
||||||
|
ftp: FTPConfig;
|
||||||
llm: LLMConfig;
|
llm: LLMConfig;
|
||||||
ocr: OCRConfig;
|
ocr: OCRConfig;
|
||||||
|
|
||||||
@@ -251,6 +284,7 @@ export namespace domain {
|
|||||||
this.theme = source["theme"];
|
this.theme = source["theme"];
|
||||||
this.s3 = this.convertValues(source["s3"], S3Config);
|
this.s3 = this.convertValues(source["s3"], S3Config);
|
||||||
this.ssh = this.convertValues(source["ssh"], SSHConfig);
|
this.ssh = this.convertValues(source["ssh"], SSHConfig);
|
||||||
|
this.ftp = this.convertValues(source["ftp"], FTPConfig);
|
||||||
this.llm = this.convertValues(source["llm"], LLMConfig);
|
this.llm = this.convertValues(source["llm"], LLMConfig);
|
||||||
this.ocr = this.convertValues(source["ocr"], OCRConfig);
|
this.ocr = this.convertValues(source["ocr"], OCRConfig);
|
||||||
}
|
}
|
||||||
@@ -278,6 +312,7 @@ export namespace domain {
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,11 +7,13 @@ require (
|
|||||||
github.com/aws/aws-sdk-go-v2 v1.30.3
|
github.com/aws/aws-sdk-go-v2 v1.30.3
|
||||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27
|
github.com/aws/aws-sdk-go-v2/credentials v1.17.27
|
||||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2
|
||||||
|
github.com/jlaffaye/ftp v0.2.0
|
||||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237
|
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237
|
||||||
|
github.com/pkg/sftp v1.13.10
|
||||||
github.com/wailsapp/wails/v2 v2.12.0
|
github.com/wailsapp/wails/v2 v2.12.0
|
||||||
golang.design/x/clipboard v0.7.0
|
golang.design/x/clipboard v0.7.0
|
||||||
golang.design/x/hotkey v0.4.1
|
golang.design/x/hotkey v0.4.1
|
||||||
golang.org/x/crypto v0.33.0
|
golang.org/x/crypto v0.41.0
|
||||||
golang.org/x/image v0.12.0
|
golang.org/x/image v0.12.0
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -32,8 +34,11 @@ require (
|
|||||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
github.com/google/uuid v1.6.0 // indirect
|
||||||
github.com/gorilla/websocket v1.5.3 // indirect
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
|
github.com/hashicorp/errwrap v1.0.0 // indirect
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e // indirect
|
||||||
github.com/jezek/xgb v1.1.0 // indirect
|
github.com/jezek/xgb v1.1.0 // indirect
|
||||||
|
github.com/kr/fs v0.1.0 // indirect
|
||||||
github.com/labstack/echo/v4 v4.13.3 // indirect
|
github.com/labstack/echo/v4 v4.13.3 // indirect
|
||||||
github.com/labstack/gommon v0.4.2 // indirect
|
github.com/labstack/gommon v0.4.2 // indirect
|
||||||
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
|
github.com/leaanthony/go-ansi-parser v1.6.1 // indirect
|
||||||
@@ -54,7 +59,7 @@ require (
|
|||||||
github.com/wailsapp/mimetype v1.4.1 // indirect
|
github.com/wailsapp/mimetype v1.4.1 // indirect
|
||||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect
|
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 // indirect
|
||||||
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect
|
golang.org/x/mobile v0.0.0-20230301163155-e0f57694e12c // indirect
|
||||||
golang.org/x/net v0.35.0 // indirect
|
golang.org/x/net v0.42.0 // indirect
|
||||||
golang.org/x/sys v0.30.0 // indirect
|
golang.org/x/sys v0.35.0 // indirect
|
||||||
golang.org/x/text v0.22.0 // indirect
|
golang.org/x/text v0.28.0 // indirect
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -41,12 +41,20 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
|||||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||||
|
github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=
|
||||||
|
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||||
|
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e h1:Q3+PugElBCf4PFpxhErSzU3/PY5sFL5Z6rfv4AbGAck=
|
||||||
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
github.com/jchv/go-winloader v0.0.0-20210711035445-715c2860da7e/go.mod h1:alcuEEnZsY1WQsagKhZDsoPCRoOijYqhZvPwLG0kzVs=
|
||||||
github.com/jezek/xgb v1.1.0 h1:wnpxJzP1+rkbGclEkmwpVFQWpuE2PUGNUzP8SbfFobk=
|
github.com/jezek/xgb v1.1.0 h1:wnpxJzP1+rkbGclEkmwpVFQWpuE2PUGNUzP8SbfFobk=
|
||||||
github.com/jezek/xgb v1.1.0/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
|
github.com/jezek/xgb v1.1.0/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
|
||||||
|
github.com/jlaffaye/ftp v0.2.0 h1:lXNvW7cBu7R/68bknOX3MrRIIqZ61zELs1P2RAiA3lg=
|
||||||
|
github.com/jlaffaye/ftp v0.2.0/go.mod h1:is2Ds5qkhceAPy2xD6RLI6hmp/qysSoymZ+Z2uTnspI=
|
||||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237 h1:YOp8St+CM/AQ9Vp4XYm4272E77MptJDHkwypQHIRl9Q=
|
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237 h1:YOp8St+CM/AQ9Vp4XYm4272E77MptJDHkwypQHIRl9Q=
|
||||||
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237/go.mod h1:e7qQlOY68wOz4b82D7n+DdaptZAi+SHW0+yKiWZzEYE=
|
github.com/kbinani/screenshot v0.0.0-20230812210009-b87d31814237/go.mod h1:e7qQlOY68wOz4b82D7n+DdaptZAi+SHW0+yKiWZzEYE=
|
||||||
|
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||||
|
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||||
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
github.com/labstack/echo/v4 v4.13.3 h1:pwhpCPrTl5qry5HRdM5FwdXnhXSLSY+WE+YQSeCaafY=
|
||||||
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
github.com/labstack/echo/v4 v4.13.3/go.mod h1:o90YNEeQWjDozo584l7AwhJMHN0bOC4tAfg+Xox9q5g=
|
||||||
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
github.com/labstack/gommon v0.4.2 h1:F8qTUNXgG1+6WQmqoUWnz8WiEU60mXVVw0P4ht1WRA0=
|
||||||
@@ -75,6 +83,8 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmd
|
|||||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||||
|
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
@@ -106,8 +116,8 @@ golang.design/x/mainthread v0.3.0/go.mod h1:vYX7cF2b3pTJMGM/hc13NmN6kblKnf4/IyvH
|
|||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=
|
golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4=
|
||||||
golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=
|
golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc=
|
||||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU=
|
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56 h1:estk1glOnSVeJ9tdEZZc5mAMDZk5lNJNyJ6DvrBkTEU=
|
||||||
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
|
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
|
||||||
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
|
||||||
@@ -126,8 +136,8 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v
|
|||||||
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
golang.org/x/net v0.0.0-20210505024714-0287a6fb4125/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
golang.org/x/net v0.35.0 h1:T5GQRQb2y08kTAByq9L4/bz8cipCdA8FbRTXewonqY8=
|
golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs=
|
||||||
golang.org/x/net v0.35.0/go.mod h1:EglIi67kWsHKlRzzVMUD93VMSWGFOMSZgxFjparz1Qk=
|
golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8=
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
@@ -144,21 +154,21 @@ golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBc
|
|||||||
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
|
golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI=
|
||||||
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
golang.org/x/term v0.29.0 h1:L6pJp37ocefwRRtYPKSWOWzOtWSxVajvz2ldH/xi3iU=
|
golang.org/x/term v0.34.0 h1:O/2T7POpk0ZZ7MAzMeWFSg6S5IpWd/RXDlM9hgM3DR4=
|
||||||
golang.org/x/term v0.29.0/go.mod h1:6bl4lRlvVuDgSf3179VpIxBF0o10JUpXWOnI7nErv7s=
|
golang.org/x/term v0.34.0/go.mod h1:5jC53AEywhIVebHgPVeg0mj8OD3VO9OzclacVrqpaAw=
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
|
||||||
golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
|
golang.org/x/text v0.28.0 h1:rhazDwis8INMIwQ4tpjLDzUhx6RlXqZNPEM0huQojng=
|
||||||
golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
|
golang.org/x/text v0.28.0/go.mod h1:U8nCwOR8jO/marOQ0QbDiOngZVEBB7MAiitBuMjXiNU=
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
|||||||
@@ -75,12 +75,20 @@ func ApplyAnnotationsWithScale(pngBytes []byte, annotations []Annotation, scaleX
|
|||||||
switch ann.Tool {
|
switch ann.Tool {
|
||||||
case "pen":
|
case "pen":
|
||||||
drawPolyline(dst, ann.Points, scaleX, scaleY, width, c)
|
drawPolyline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||||
|
case "line":
|
||||||
|
drawStraightLine(dst, ann.Points, scaleX, scaleY, width, c)
|
||||||
|
case "arrow":
|
||||||
|
drawArrow(dst, ann.Points, scaleX, scaleY, width, c)
|
||||||
case "rect":
|
case "rect":
|
||||||
drawRectOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
drawRectOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||||
case "ellipse":
|
case "ellipse":
|
||||||
drawEllipseOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
drawEllipseOutline(dst, ann.Points, scaleX, scaleY, width, c)
|
||||||
case "text":
|
case "text":
|
||||||
drawTextAnnotation(dst, ann, scaleX, scaleY, c)
|
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 +99,121 @@ func ApplyAnnotationsWithScale(pngBytes []byte, annotations []Annotation, scaleX
|
|||||||
return buf.Bytes(), nil
|
return buf.Bytes(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func drawStraightLine(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||||
|
if len(points) < 2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
drawLine(img, scalePoint(points[0], scaleX, scaleY), scalePoint(points[len(points)-1], scaleX, scaleY), width, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
func drawArrow(img *image.RGBA, points []Point, scaleX, scaleY float64, width int, c color.RGBA) {
|
||||||
|
if len(points) < 2 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
start := scalePoint(points[0], scaleX, scaleY)
|
||||||
|
end := scalePoint(points[len(points)-1], scaleX, scaleY)
|
||||||
|
dx, dy := end.X-start.X, end.Y-start.Y
|
||||||
|
length := math.Hypot(dx, dy)
|
||||||
|
if length < 1 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
drawLine(img, start, end, width, c)
|
||||||
|
headLength := math.Min(length*0.45, math.Max(10*math.Max(scaleX, scaleY), float64(width)*4))
|
||||||
|
angle := math.Atan2(dy, dx)
|
||||||
|
spread := math.Pi / 6
|
||||||
|
left := Point{X: end.X - headLength*math.Cos(angle-spread), Y: end.Y - headLength*math.Sin(angle-spread)}
|
||||||
|
right := Point{X: end.X - headLength*math.Cos(angle+spread), Y: end.Y - headLength*math.Sin(angle+spread)}
|
||||||
|
drawLine(img, end, left, width, c)
|
||||||
|
drawLine(img, end, right, width, c)
|
||||||
|
}
|
||||||
|
|
||||||
|
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) {
|
func parseHexColor(hex string) (color.RGBA, error) {
|
||||||
value := strings.TrimPrefix(strings.TrimSpace(hex), "#")
|
value := strings.TrimPrefix(strings.TrimSpace(hex), "#")
|
||||||
if len(value) != 6 {
|
if len(value) != 6 {
|
||||||
|
|||||||
@@ -171,3 +171,110 @@ func TestApplyAnnotationsUsesStrokeWidth(t *testing.T) {
|
|||||||
t.Fatalf("expected thick rectangle stroke to cover y=24, got %#v", got)
|
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")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyAnnotationsDrawsStraightLine(t *testing.T) {
|
||||||
|
src := image.NewRGBA(image.Rect(0, 0, 60, 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: "line", Color: "#ef4444", StrokeWidth: 4,
|
||||||
|
Points: []Point{{X: 5, Y: 20}, {X: 50, Y: 20}},
|
||||||
|
}}, 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)
|
||||||
|
}
|
||||||
|
got := color.RGBAModel.Convert(img.At(30, 20)).(color.RGBA)
|
||||||
|
if got.R < 180 || got.G > 180 || got.B > 180 {
|
||||||
|
t.Fatalf("expected red line at center, got %#v", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestApplyAnnotationsDrawsArrowHead(t *testing.T) {
|
||||||
|
src := image.NewRGBA(image.Rect(0, 0, 80, 60))
|
||||||
|
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: "arrow", Color: "#3b82f6", StrokeWidth: 3,
|
||||||
|
Points: []Point{{X: 10, Y: 30}, {X: 60, 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)
|
||||||
|
}
|
||||||
|
shaft := color.RGBAModel.Convert(img.At(35, 30)).(color.RGBA)
|
||||||
|
head := color.RGBAModel.Convert(img.At(52, 25)).(color.RGBA)
|
||||||
|
if shaft.B < 180 || shaft.R > 140 || head.B < 180 || head.R > 140 {
|
||||||
|
t.Fatalf("expected blue arrow shaft and head, got shaft=%#v head=%#v", shaft, head)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
// capture_ftp.go — application-level FTP/SFTP upload orchestration.
|
||||||
|
//
|
||||||
|
// Design rationale:
|
||||||
|
// - FTP/SFTP returns a remote filesystem path, not necessarily a public URL,
|
||||||
|
// so this flow stays separate from the OSSProvider-based S3 pipeline.
|
||||||
|
// - A tiny uploader interface keeps protocol libraries out of the
|
||||||
|
// application layer and makes the upload/copy/notify sequence unit-testable.
|
||||||
|
// - The dated filename layout is shared with SSH/SCP while FTP-specific path
|
||||||
|
// validation prevents an invalid prefix from escaping the login root.
|
||||||
|
package application
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/mmmy/snapgo/internal/domain"
|
||||||
|
"github.com/mmmy/snapgo/internal/infrastructure/clipboard"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ftpSvcLog returns an application-layer FTP logger bound to the current
|
||||||
|
// default slog handler.
|
||||||
|
func ftpSvcLog() *slog.Logger { return slog.Default().With("component", "application.ftp") }
|
||||||
|
|
||||||
|
// FTPUploader abstracts both FTP and SFTP adapters.
|
||||||
|
type FTPUploader interface {
|
||||||
|
// Upload stores data at remoteRelPath, relative to the authenticated
|
||||||
|
// account's login root.
|
||||||
|
Upload(ctx context.Context, remoteRelPath string, data []byte) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// CaptureAndFTPService wires captured PNG bytes → FTP/SFTP → clipboard →
|
||||||
|
// notification.
|
||||||
|
type CaptureAndFTPService struct {
|
||||||
|
Uploader FTPUploader
|
||||||
|
Clipboard clipboard.Writer
|
||||||
|
Notifier Notifier
|
||||||
|
Cfg domain.FTPConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// ExecuteWithBytes uploads previously captured PNG bytes and copies a display
|
||||||
|
// path built from the configured root directory plus the uploaded relative
|
||||||
|
// path. RootDirectory deliberately does not affect the upload destination.
|
||||||
|
func (s *CaptureAndFTPService) ExecuteWithBytes(ctx context.Context, pngBytes []byte) error {
|
||||||
|
if s.Uploader == nil {
|
||||||
|
s.notifyFailure("FTP/SFTP not configured")
|
||||||
|
return fmt.Errorf("ftp uploader is nil")
|
||||||
|
}
|
||||||
|
if len(pngBytes) == 0 {
|
||||||
|
s.notifyFailure("empty screenshot")
|
||||||
|
return fmt.Errorf("empty screenshot")
|
||||||
|
}
|
||||||
|
|
||||||
|
relPath, err := buildFTPRemotePath(s.Cfg.PathPrefix)
|
||||||
|
if err != nil {
|
||||||
|
s.notifyFailure(err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol := normalizedFTPProtocol(s.Cfg.Protocol)
|
||||||
|
start := time.Now()
|
||||||
|
ftpSvcLog().Info("file-transfer pipeline start",
|
||||||
|
"protocol", protocol,
|
||||||
|
"host", s.Cfg.Host,
|
||||||
|
"user", s.Cfg.User,
|
||||||
|
"port", s.Cfg.Port,
|
||||||
|
"size", len(pngBytes),
|
||||||
|
"remote_path", relPath,
|
||||||
|
"strict_host_key", s.Cfg.StrictHostKey)
|
||||||
|
|
||||||
|
if err := s.Uploader.Upload(ctx, relPath, pngBytes); err != nil {
|
||||||
|
ftpSvcLog().Error("file-transfer upload failed",
|
||||||
|
"protocol", protocol,
|
||||||
|
"remote_path", relPath,
|
||||||
|
"elapsed", time.Since(start),
|
||||||
|
"err", err)
|
||||||
|
s.notifyFailure(strings.ToUpper(protocol) + " upload failed: " + err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
clipText := ftpShareText(protocol, s.Cfg.RootDirectory, relPath)
|
||||||
|
if s.Clipboard != nil {
|
||||||
|
if err := s.Clipboard.WriteText(clipText); err != nil {
|
||||||
|
s.notifyFailure("clipboard write failed: " + err.Error())
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if s.Notifier != nil {
|
||||||
|
s.Notifier.NotifySuccess(clipText)
|
||||||
|
}
|
||||||
|
ftpSvcLog().Info("file-transfer pipeline done",
|
||||||
|
"protocol", protocol,
|
||||||
|
"remote_path", relPath,
|
||||||
|
"total_elapsed", time.Since(start))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// buildFTPRemotePath validates the user-controlled prefix before reusing the
|
||||||
|
// existing dated remote-path generator shared with SSH/SCP.
|
||||||
|
func buildFTPRemotePath(prefix string) (string, error) {
|
||||||
|
if err := validateFTPPathPrefix(prefix); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
prefix = strings.TrimSpace(prefix)
|
||||||
|
prefix = strings.TrimPrefix(prefix, "~")
|
||||||
|
prefix = strings.TrimLeft(prefix, "/")
|
||||||
|
return buildRemoteRelPath(prefix), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateFTPPathPrefix(prefix string) error {
|
||||||
|
if strings.ContainsAny(prefix, "\x00\r\n\\") {
|
||||||
|
return fmt.Errorf("FTP/SFTP path contains an invalid character")
|
||||||
|
}
|
||||||
|
prefix = strings.TrimSpace(prefix)
|
||||||
|
prefix = strings.TrimPrefix(prefix, "~")
|
||||||
|
prefix = strings.TrimLeft(prefix, "/")
|
||||||
|
for _, segment := range strings.Split(prefix, "/") {
|
||||||
|
if segment == ".." {
|
||||||
|
return fmt.Errorf("FTP/SFTP path must stay inside the login directory")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizedFTPProtocol(protocol string) string {
|
||||||
|
if protocol == domain.FTPProtocolSFTP {
|
||||||
|
return domain.FTPProtocolSFTP
|
||||||
|
}
|
||||||
|
return domain.FTPProtocolFTP
|
||||||
|
}
|
||||||
|
|
||||||
|
func ftpShareText(protocol, rootDirectory, relPath string) string {
|
||||||
|
rootDirectory = strings.TrimSpace(rootDirectory)
|
||||||
|
if rootDirectory == "" {
|
||||||
|
if protocol == domain.FTPProtocolSFTP {
|
||||||
|
rootDirectory = "~/"
|
||||||
|
} else {
|
||||||
|
rootDirectory = "/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return strings.TrimRight(rootDirectory, "/") + "/" + strings.TrimLeft(relPath, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CaptureAndFTPService) notifyFailure(reason string) {
|
||||||
|
if s.Notifier != nil {
|
||||||
|
s.Notifier.NotifyFailure(reason)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
package application
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/mmmy/snapgo/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
type fakeFTPUploader struct {
|
||||||
|
path string
|
||||||
|
data []byte
|
||||||
|
err error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (f *fakeFTPUploader) Upload(_ context.Context, remoteRelPath string, data []byte) error {
|
||||||
|
f.path = remoteRelPath
|
||||||
|
f.data = append([]byte(nil), data...)
|
||||||
|
return f.err
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureAndFTPServiceUploadsAndCopiesFTPPath(t *testing.T) {
|
||||||
|
uploader := &fakeFTPUploader{}
|
||||||
|
clip := &fakeClipboard{}
|
||||||
|
notifier := &fakeNotifier{}
|
||||||
|
svc := &CaptureAndFTPService{
|
||||||
|
Uploader: uploader,
|
||||||
|
Clipboard: clip,
|
||||||
|
Notifier: notifier,
|
||||||
|
Cfg: domain.FTPConfig{
|
||||||
|
Protocol: domain.FTPProtocolFTP,
|
||||||
|
PathPrefix: "snapgo/",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.ExecuteWithBytes(context.Background(), []byte("png")); err != nil {
|
||||||
|
t.Fatalf("upload FTP screenshot: %v", err)
|
||||||
|
}
|
||||||
|
if string(uploader.data) != "png" {
|
||||||
|
t.Fatalf("expected PNG bytes, got %q", string(uploader.data))
|
||||||
|
}
|
||||||
|
if !strings.HasPrefix(uploader.path, "snapgo/") || !strings.HasSuffix(uploader.path, ".png") {
|
||||||
|
t.Fatalf("unexpected remote path %q", uploader.path)
|
||||||
|
}
|
||||||
|
if clip.text != "/"+uploader.path {
|
||||||
|
t.Fatalf("expected FTP root path copied, got %q", clip.text)
|
||||||
|
}
|
||||||
|
if notifier.success != clip.text {
|
||||||
|
t.Fatalf("expected success notification %q, got %q", clip.text, notifier.success)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureAndFTPServiceCopiesConfiguredRootPath(t *testing.T) {
|
||||||
|
uploader := &fakeFTPUploader{}
|
||||||
|
clip := &fakeClipboard{}
|
||||||
|
svc := &CaptureAndFTPService{
|
||||||
|
Uploader: uploader,
|
||||||
|
Clipboard: clip,
|
||||||
|
Cfg: domain.FTPConfig{
|
||||||
|
Protocol: domain.FTPProtocolSFTP,
|
||||||
|
RootDirectory: "~/ftp/",
|
||||||
|
PathPrefix: "images",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := svc.ExecuteWithBytes(context.Background(), []byte("png")); err != nil {
|
||||||
|
t.Fatalf("upload SFTP screenshot: %v", err)
|
||||||
|
}
|
||||||
|
if clip.text != "~/ftp/"+uploader.path {
|
||||||
|
t.Fatalf("expected configured SFTP root path copied, got %q", clip.text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFTPShareTextJoinsConfiguredRootAndRemoteDirectory(t *testing.T) {
|
||||||
|
const relPath = "snapgo/2026/07/20260713-110413-18lnbx.png"
|
||||||
|
const want = "~/ftp/snapgo/2026/07/20260713-110413-18lnbx.png"
|
||||||
|
if got := ftpShareText(domain.FTPProtocolSFTP, "~/ftp/", relPath); got != want {
|
||||||
|
t.Fatalf("ftpShareText() = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFTPShareTextUsesProtocolDefaultWhenRootDirectoryIsEmpty(t *testing.T) {
|
||||||
|
const relPath = "snapgo/2026/07/image.png"
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
protocol string
|
||||||
|
want string
|
||||||
|
}{
|
||||||
|
{name: "FTP", protocol: domain.FTPProtocolFTP, want: "/" + relPath},
|
||||||
|
{name: "SFTP", protocol: domain.FTPProtocolSFTP, want: "~/" + relPath},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
if got := ftpShareText(tt.protocol, "", relPath); got != tt.want {
|
||||||
|
t.Fatalf("ftpShareText() = %q, want %q", got, tt.want)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureAndFTPServiceRejectsTraversalBeforeUpload(t *testing.T) {
|
||||||
|
uploader := &fakeFTPUploader{}
|
||||||
|
notifier := &fakeNotifier{}
|
||||||
|
svc := &CaptureAndFTPService{
|
||||||
|
Uploader: uploader,
|
||||||
|
Notifier: notifier,
|
||||||
|
Cfg: domain.FTPConfig{
|
||||||
|
Protocol: domain.FTPProtocolSFTP,
|
||||||
|
PathPrefix: "../../outside",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := svc.ExecuteWithBytes(context.Background(), []byte("png"))
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected traversal prefix to fail")
|
||||||
|
}
|
||||||
|
if uploader.path != "" {
|
||||||
|
t.Fatalf("uploader should not run, got path %q", uploader.path)
|
||||||
|
}
|
||||||
|
if notifier.failure == "" {
|
||||||
|
t.Fatal("expected failure notification")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCaptureAndFTPServiceSurfacesUploadFailure(t *testing.T) {
|
||||||
|
want := errors.New("server unavailable")
|
||||||
|
uploader := &fakeFTPUploader{err: want}
|
||||||
|
clip := &fakeClipboard{}
|
||||||
|
notifier := &fakeNotifier{}
|
||||||
|
svc := &CaptureAndFTPService{
|
||||||
|
Uploader: uploader,
|
||||||
|
Clipboard: clip,
|
||||||
|
Notifier: notifier,
|
||||||
|
Cfg: domain.FTPConfig{Protocol: domain.FTPProtocolFTP},
|
||||||
|
}
|
||||||
|
|
||||||
|
err := svc.ExecuteWithBytes(context.Background(), []byte("png"))
|
||||||
|
if !errors.Is(err, want) {
|
||||||
|
t.Fatalf("expected %v, got %v", want, err)
|
||||||
|
}
|
||||||
|
if clip.text != "" {
|
||||||
|
t.Fatalf("clipboard should remain empty, got %q", clip.text)
|
||||||
|
}
|
||||||
|
if !strings.Contains(notifier.failure, "server unavailable") {
|
||||||
|
t.Fatalf("unexpected failure notification %q", notifier.failure)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildFTPRemotePathNormalizesLoginRootMarkers(t *testing.T) {
|
||||||
|
remotePath, err := buildFTPRemotePath(" ~////snapgo/ ")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("build remote path: %v", err)
|
||||||
|
}
|
||||||
|
if strings.HasPrefix(remotePath, "/") || !strings.HasPrefix(remotePath, "snapgo/") {
|
||||||
|
t.Fatalf("expected relative snapgo path, got %q", remotePath)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,8 @@
|
|||||||
// Package domain — configuration types.
|
// Package domain — configuration types.
|
||||||
//
|
//
|
||||||
// S3Config and SSHConfig are intentionally split into their own structs so
|
// S3Config, SSHConfig, and FTPConfig are intentionally split into their own
|
||||||
// that future providers can introduce their own configuration types side-
|
// structs so future providers can introduce configuration types side-by-side
|
||||||
// by-side without polluting the core domain types file.
|
// without polluting the core domain types file.
|
||||||
package domain
|
package domain
|
||||||
|
|
||||||
// S3Config describes the connection parameters for any S3-compatible
|
// S3Config describes the connection parameters for any S3-compatible
|
||||||
@@ -72,6 +72,37 @@ type SSHConfig struct {
|
|||||||
ConnectTimeoutSecs int `json:"connectTimeoutSecs"`
|
ConnectTimeoutSecs int `json:"connectTimeoutSecs"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FTPConfig describes a file-transfer destination reached through FTP or
|
||||||
|
// SFTP. It is intentionally separate from SSHConfig: SFTP uses the SSH
|
||||||
|
// transport, but it is a different file-transfer protocol from the existing
|
||||||
|
// SCP action and has its own remote-root semantics.
|
||||||
|
//
|
||||||
|
// Field design notes:
|
||||||
|
// - Protocol is either "ftp" or "sftp". Their default ports are 21 and 22.
|
||||||
|
// - AuthMethod is used only by SFTP. "password" uses Password, while "key"
|
||||||
|
// reuses the local ssh-agent and ~/.ssh/id_* discovery used by SSH/SCP.
|
||||||
|
// - PathPrefix is relative to the account's login root. The application
|
||||||
|
// rejects absolute paths and traversal segments before uploading.
|
||||||
|
// - RootDirectory is only used to build the path copied to the clipboard.
|
||||||
|
// Keeping it separate from PathPrefix lets the server expose a login root
|
||||||
|
// such as "~/ftp/" while uploads still target a relative directory such
|
||||||
|
// as "snapgo/".
|
||||||
|
// - StrictHostKey and KnownHostsPath apply only to SFTP. Plain FTP has no
|
||||||
|
// host-key mechanism and sends credentials and data without encryption.
|
||||||
|
type FTPConfig struct {
|
||||||
|
Protocol string `json:"protocol"`
|
||||||
|
Host string `json:"host"`
|
||||||
|
Port int `json:"port"`
|
||||||
|
User string `json:"user"`
|
||||||
|
AuthMethod string `json:"authMethod"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
RootDirectory string `json:"rootDirectory"`
|
||||||
|
PathPrefix string `json:"pathPrefix"`
|
||||||
|
StrictHostKey bool `json:"strictHostKey"`
|
||||||
|
KnownHostsPath string `json:"knownHostsPath"`
|
||||||
|
ConnectTimeoutSecs int `json:"connectTimeoutSecs"`
|
||||||
|
}
|
||||||
|
|
||||||
// LLMProviderConfig stores one OpenAI-compatible multimodal chat endpoint.
|
// LLMProviderConfig stores one OpenAI-compatible multimodal chat endpoint.
|
||||||
//
|
//
|
||||||
// The three built-in providers (Qwen, Doubao/Ark, OpenAI-compatible) all use
|
// The three built-in providers (Qwen, Doubao/Ark, OpenAI-compatible) all use
|
||||||
@@ -145,6 +176,12 @@ const (
|
|||||||
SSHAuthKerberos = "kerberos"
|
SSHAuthKerberos = "kerberos"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// File-transfer protocol identifiers stored in FTPConfig.Protocol.
|
||||||
|
const (
|
||||||
|
FTPProtocolFTP = "ftp"
|
||||||
|
FTPProtocolSFTP = "sftp"
|
||||||
|
)
|
||||||
|
|
||||||
// Built-in LLM provider identifiers.
|
// Built-in LLM provider identifiers.
|
||||||
const (
|
const (
|
||||||
LLMProviderQwen = "qwen"
|
LLMProviderQwen = "qwen"
|
||||||
@@ -181,8 +218,8 @@ func (c SSHConfig) IsKerberos() bool {
|
|||||||
|
|
||||||
// AppConfig is the top-level on-disk configuration document.
|
// AppConfig is the top-level on-disk configuration document.
|
||||||
//
|
//
|
||||||
// We keep S3 / SSH nested so that adding more providers later (e.g. AliyunOSS,
|
// We keep S3 / SSH / FTP nested so adding another provider later only requires
|
||||||
// COS, FTP) only requires a new sibling field rather than a schema rewrite.
|
// a new sibling field rather than a schema rewrite.
|
||||||
type AppConfig struct {
|
type AppConfig struct {
|
||||||
// Hotkey describes the global shortcut that triggers a capture.
|
// Hotkey describes the global shortcut that triggers a capture.
|
||||||
// Stored as a human-readable string like "cmd+shift+a"; parsing happens
|
// Stored as a human-readable string like "cmd+shift+a"; parsing happens
|
||||||
@@ -199,6 +236,9 @@ type AppConfig struct {
|
|||||||
// destination triggered by the save-remote toolbar button.
|
// destination triggered by the save-remote toolbar button.
|
||||||
SSH SSHConfig `json:"ssh"`
|
SSH SSHConfig `json:"ssh"`
|
||||||
|
|
||||||
|
// FTP holds the destination used by the dedicated FTP/SFTP toolbar action.
|
||||||
|
FTP FTPConfig `json:"ftp"`
|
||||||
|
|
||||||
// LLM holds provider settings for the "copy summary" screenshot action.
|
// LLM holds provider settings for the "copy summary" screenshot action.
|
||||||
LLM LLMConfig `json:"llm"`
|
LLM LLMConfig `json:"llm"`
|
||||||
|
|
||||||
@@ -221,6 +261,15 @@ func DefaultAppConfig() AppConfig {
|
|||||||
ConnectTimeoutSecs: 10,
|
ConnectTimeoutSecs: 10,
|
||||||
StrictHostKey: false,
|
StrictHostKey: false,
|
||||||
},
|
},
|
||||||
|
FTP: FTPConfig{
|
||||||
|
Protocol: FTPProtocolFTP,
|
||||||
|
Port: 21,
|
||||||
|
AuthMethod: SSHAuthPassword,
|
||||||
|
RootDirectory: "/",
|
||||||
|
PathPrefix: "snapgo/",
|
||||||
|
ConnectTimeoutSecs: 10,
|
||||||
|
StrictHostKey: false,
|
||||||
|
},
|
||||||
LLM: DefaultLLMConfig(),
|
LLM: DefaultLLMConfig(),
|
||||||
OCR: DefaultOCRConfig(),
|
OCR: DefaultOCRConfig(),
|
||||||
}
|
}
|
||||||
@@ -315,6 +364,32 @@ func (c *AppConfig) Normalize() {
|
|||||||
if c.SSH.ConnectTimeoutSecs == 0 {
|
if c.SSH.ConnectTimeoutSecs == 0 {
|
||||||
c.SSH.ConnectTimeoutSecs = 10
|
c.SSH.ConnectTimeoutSecs = 10
|
||||||
}
|
}
|
||||||
|
if c.FTP.Protocol != FTPProtocolFTP && c.FTP.Protocol != FTPProtocolSFTP {
|
||||||
|
c.FTP.Protocol = FTPProtocolFTP
|
||||||
|
}
|
||||||
|
if c.FTP.Port == 0 {
|
||||||
|
if c.FTP.Protocol == FTPProtocolSFTP {
|
||||||
|
c.FTP.Port = 22
|
||||||
|
} else {
|
||||||
|
c.FTP.Port = 21
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.FTP.AuthMethod != SSHAuthPassword && c.FTP.AuthMethod != SSHAuthKey {
|
||||||
|
c.FTP.AuthMethod = SSHAuthPassword
|
||||||
|
}
|
||||||
|
if c.FTP.RootDirectory == "" {
|
||||||
|
if c.FTP.Protocol == FTPProtocolSFTP {
|
||||||
|
c.FTP.RootDirectory = "~/"
|
||||||
|
} else {
|
||||||
|
c.FTP.RootDirectory = "/"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if c.FTP.PathPrefix == "" {
|
||||||
|
c.FTP.PathPrefix = "snapgo/"
|
||||||
|
}
|
||||||
|
if c.FTP.ConnectTimeoutSecs == 0 {
|
||||||
|
c.FTP.ConnectTimeoutSecs = 10
|
||||||
|
}
|
||||||
|
|
||||||
defaultLLM := DefaultLLMConfig()
|
defaultLLM := DefaultLLMConfig()
|
||||||
if c.LLM.ActiveProvider == "" {
|
if c.LLM.ActiveProvider == "" {
|
||||||
@@ -409,6 +484,14 @@ func (c AppConfig) IsSSHConfigured() bool {
|
|||||||
return c.SSH.Host != "" && c.SSH.User != ""
|
return c.SSH.Host != "" && c.SSH.User != ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IsFTPConfigured reports whether the FTP/SFTP destination has the minimum
|
||||||
|
// fields required to attempt a connection. Password is not required because
|
||||||
|
// SFTP key authentication and password-less FTP accounts are both valid.
|
||||||
|
func (c AppConfig) IsFTPConfigured() bool {
|
||||||
|
return (c.FTP.Protocol == FTPProtocolFTP || c.FTP.Protocol == FTPProtocolSFTP) &&
|
||||||
|
c.FTP.Host != "" && c.FTP.User != ""
|
||||||
|
}
|
||||||
|
|
||||||
// ActiveLLMProvider returns the selected provider config plus a boolean
|
// ActiveLLMProvider returns the selected provider config plus a boolean
|
||||||
// indicating whether the selection exists.
|
// indicating whether the selection exists.
|
||||||
func (c AppConfig) ActiveLLMProvider() (string, LLMProviderConfig, bool) {
|
func (c AppConfig) ActiveLLMProvider() (string, LLMProviderConfig, bool) {
|
||||||
|
|||||||
@@ -0,0 +1,56 @@
|
|||||||
|
package domain
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestDefaultAppConfigIncludesFTPDefaults(t *testing.T) {
|
||||||
|
cfg := DefaultAppConfig()
|
||||||
|
if cfg.FTP.Protocol != FTPProtocolFTP {
|
||||||
|
t.Fatalf("expected default FTP protocol, got %q", cfg.FTP.Protocol)
|
||||||
|
}
|
||||||
|
if cfg.FTP.Port != 21 {
|
||||||
|
t.Fatalf("expected default FTP port 21, got %d", cfg.FTP.Port)
|
||||||
|
}
|
||||||
|
if cfg.FTP.PathPrefix != "snapgo/" {
|
||||||
|
t.Fatalf("expected default path prefix, got %q", cfg.FTP.PathPrefix)
|
||||||
|
}
|
||||||
|
if cfg.FTP.RootDirectory != "/" {
|
||||||
|
t.Fatalf("expected default root directory, got %q", cfg.FTP.RootDirectory)
|
||||||
|
}
|
||||||
|
if cfg.FTP.ConnectTimeoutSecs != 10 {
|
||||||
|
t.Fatalf("expected 10 second timeout, got %d", cfg.FTP.ConnectTimeoutSecs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNormalizeUsesSFTPDefaultPort(t *testing.T) {
|
||||||
|
cfg := AppConfig{
|
||||||
|
FTP: FTPConfig{
|
||||||
|
Protocol: FTPProtocolSFTP,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cfg.Normalize()
|
||||||
|
if cfg.FTP.Port != 22 {
|
||||||
|
t.Fatalf("expected SFTP port 22, got %d", cfg.FTP.Port)
|
||||||
|
}
|
||||||
|
if cfg.FTP.AuthMethod != SSHAuthPassword {
|
||||||
|
t.Fatalf("expected password auth default, got %q", cfg.FTP.AuthMethod)
|
||||||
|
}
|
||||||
|
if cfg.FTP.RootDirectory != "~/" {
|
||||||
|
t.Fatalf("expected SFTP home root directory, got %q", cfg.FTP.RootDirectory)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestIsFTPConfiguredRequiresProtocolHostAndUser(t *testing.T) {
|
||||||
|
cfg := DefaultAppConfig()
|
||||||
|
if cfg.IsFTPConfigured() {
|
||||||
|
t.Fatal("empty FTP destination should not be configured")
|
||||||
|
}
|
||||||
|
cfg.FTP.Host = "files.example.com"
|
||||||
|
cfg.FTP.User = "snapgo"
|
||||||
|
if !cfg.IsFTPConfigured() {
|
||||||
|
t.Fatal("host and user should be enough for a normalized FTP config")
|
||||||
|
}
|
||||||
|
cfg.FTP.Protocol = "invalid"
|
||||||
|
if cfg.IsFTPConfigured() {
|
||||||
|
t.Fatal("invalid protocol should not be configured")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,288 @@
|
|||||||
|
// Package ftp provides the FTP side of SnapGo's FTP/SFTP destination.
|
||||||
|
//
|
||||||
|
// Design rationale:
|
||||||
|
// - Plain FTP needs a real protocol client for PASV/EPSV handling; hand-
|
||||||
|
// rolling those details would be fragile across common servers.
|
||||||
|
// - SFTP is delegated to the sibling SSH adapter so authentication, agent,
|
||||||
|
// key discovery, and known_hosts behaviour stay consistent with SCP.
|
||||||
|
// - Both implementations upload to a temporary name and rename only after
|
||||||
|
// the payload is complete, preventing a failed transfer from exposing a
|
||||||
|
// partially written screenshot at the final path.
|
||||||
|
package ftp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
ftpclient "github.com/jlaffaye/ftp"
|
||||||
|
|
||||||
|
"github.com/mmmy/snapgo/internal/domain"
|
||||||
|
sshpkg "github.com/mmmy/snapgo/internal/infrastructure/ssh"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RemoteUploader is the common capability exposed to app.go for FTP and
|
||||||
|
// SFTP. The application service only needs Upload; TestConnection remains an
|
||||||
|
// infrastructure concern used by the Settings probe RPC.
|
||||||
|
type RemoteUploader interface {
|
||||||
|
Upload(ctx context.Context, remoteRelPath string, data []byte) error
|
||||||
|
TestConnection(ctx context.Context) error
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewUploader validates cfg and returns the adapter for its selected protocol.
|
||||||
|
func NewUploader(cfg domain.FTPConfig) (RemoteUploader, error) {
|
||||||
|
normalized, err := normalizeConfig(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if normalized.Protocol == domain.FTPProtocolSFTP {
|
||||||
|
return sshpkg.NewSFTPUploader(normalized), nil
|
||||||
|
}
|
||||||
|
return &plainUploader{cfg: normalized}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type plainUploader struct {
|
||||||
|
cfg domain.FTPConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func ftpLog() *slog.Logger { return slog.Default().With("component", "ftp") }
|
||||||
|
|
||||||
|
func normalizeConfig(cfg domain.FTPConfig) (domain.FTPConfig, error) {
|
||||||
|
cfg.Protocol = strings.ToLower(strings.TrimSpace(cfg.Protocol))
|
||||||
|
if cfg.Protocol == "" {
|
||||||
|
cfg.Protocol = domain.FTPProtocolFTP
|
||||||
|
}
|
||||||
|
if cfg.Protocol != domain.FTPProtocolFTP && cfg.Protocol != domain.FTPProtocolSFTP {
|
||||||
|
return domain.FTPConfig{}, fmt.Errorf("file transfer: protocol must be ftp or sftp")
|
||||||
|
}
|
||||||
|
cfg.Host = strings.TrimSpace(cfg.Host)
|
||||||
|
cfg.User = strings.TrimSpace(cfg.User)
|
||||||
|
if cfg.Host == "" || cfg.User == "" {
|
||||||
|
return domain.FTPConfig{}, fmt.Errorf("file transfer: host and user are required")
|
||||||
|
}
|
||||||
|
if cfg.Port <= 0 {
|
||||||
|
if cfg.Protocol == domain.FTPProtocolSFTP {
|
||||||
|
cfg.Port = 22
|
||||||
|
} else {
|
||||||
|
cfg.Port = 21
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if cfg.Port > 65535 {
|
||||||
|
return domain.FTPConfig{}, fmt.Errorf("file transfer: port must be between 1 and 65535")
|
||||||
|
}
|
||||||
|
if cfg.ConnectTimeoutSecs <= 0 {
|
||||||
|
cfg.ConnectTimeoutSecs = 10
|
||||||
|
}
|
||||||
|
if cfg.AuthMethod == "" {
|
||||||
|
cfg.AuthMethod = domain.SSHAuthPassword
|
||||||
|
}
|
||||||
|
if cfg.Protocol == domain.FTPProtocolSFTP &&
|
||||||
|
cfg.AuthMethod != domain.SSHAuthPassword && cfg.AuthMethod != domain.SSHAuthKey {
|
||||||
|
return domain.FTPConfig{}, fmt.Errorf("sftp: auth method must be password or key")
|
||||||
|
}
|
||||||
|
return cfg, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *plainUploader) dial(ctx context.Context) (*ftpclient.ServerConn, error) {
|
||||||
|
timeout := time.Duration(u.cfg.ConnectTimeoutSecs) * time.Second
|
||||||
|
addr := net.JoinHostPort(u.cfg.Host, fmt.Sprintf("%d", u.cfg.Port))
|
||||||
|
ftpLog().Info("FTP dial start",
|
||||||
|
"addr", addr,
|
||||||
|
"user", u.cfg.User,
|
||||||
|
"timeout", timeout,
|
||||||
|
"has_password", u.cfg.Password != "")
|
||||||
|
conn, err := ftpclient.Dial(
|
||||||
|
addr,
|
||||||
|
ftpclient.DialWithDialFunc(contextDialFunc(ctx, timeout)),
|
||||||
|
ftpclient.DialWithShutTimeout(timeout),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("ftp: dial %s: %w", addr, err)
|
||||||
|
}
|
||||||
|
if err := conn.Login(u.cfg.User, u.cfg.Password); err != nil {
|
||||||
|
_ = conn.Quit()
|
||||||
|
return nil, fmt.Errorf("ftp: login: %w", err)
|
||||||
|
}
|
||||||
|
return conn, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload stores one screenshot through plain FTP.
|
||||||
|
func (u *plainUploader) Upload(ctx context.Context, remoteRelPath string, data []byte) error {
|
||||||
|
cleaned, err := validateRemoteRelativePath(remoteRelPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
conn, err := u.dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = conn.Quit() }()
|
||||||
|
|
||||||
|
if err := enterFTPDirectory(conn, path.Dir(cleaned)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
base := path.Base(cleaned)
|
||||||
|
|
||||||
|
tempName := temporaryRemoteName(base)
|
||||||
|
removeTemp := true
|
||||||
|
defer func() {
|
||||||
|
if removeTemp {
|
||||||
|
_ = conn.Delete(tempName)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
if err := conn.Stor(tempName, &contextReader{ctx: ctx, reader: bytes.NewReader(data)}); err != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return fmt.Errorf("ftp: store %s: %w", cleaned, err)
|
||||||
|
}
|
||||||
|
if err := conn.Rename(tempName, base); err != nil {
|
||||||
|
return fmt.Errorf("ftp: commit %s: %w", cleaned, err)
|
||||||
|
}
|
||||||
|
removeTemp = false
|
||||||
|
ftpLog().Info("FTP upload ok", "remote_path", cleaned, "size", len(data))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConnection writes and removes a small probe under the configured path,
|
||||||
|
// proving that credentials and directory permissions are both usable.
|
||||||
|
func (u *plainUploader) TestConnection(ctx context.Context) error {
|
||||||
|
probe, err := probeRemotePath(u.cfg.PathPrefix)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
conn, err := u.dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = conn.Quit() }()
|
||||||
|
|
||||||
|
if err := enterFTPDirectory(conn, path.Dir(probe)); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
base := path.Base(probe)
|
||||||
|
if err := conn.Stor(base, strings.NewReader("snapgo")); err != nil {
|
||||||
|
return fmt.Errorf("ftp probe: write: %w", err)
|
||||||
|
}
|
||||||
|
if err := conn.Delete(base); err != nil {
|
||||||
|
return fmt.Errorf("ftp probe: delete: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// enterFTPDirectory walks to dir relative to the login root, creating missing
|
||||||
|
// segments.
|
||||||
|
func enterFTPDirectory(conn *ftpclient.ServerConn, dir string) error {
|
||||||
|
dir = strings.Trim(dir, "/")
|
||||||
|
if dir == "" || dir == "." {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
for _, segment := range strings.Split(dir, "/") {
|
||||||
|
if err := conn.ChangeDir(segment); err == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := conn.MakeDir(segment); err != nil {
|
||||||
|
// A concurrent uploader may have created the directory after our
|
||||||
|
// failed CWD. Retrying CWD distinguishes that race from a real error.
|
||||||
|
if retryErr := conn.ChangeDir(segment); retryErr == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
return fmt.Errorf("ftp: create directory %q: %w", segment, err)
|
||||||
|
}
|
||||||
|
if err := conn.ChangeDir(segment); err != nil {
|
||||||
|
return fmt.Errorf("ftp: enter directory %q: %w", segment, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateRemoteRelativePath(value string) (string, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" || strings.HasPrefix(value, "/") || strings.HasPrefix(value, "~") {
|
||||||
|
return "", fmt.Errorf("file transfer: remote path must be relative to the login directory")
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(value, "\x00\r\n\\") {
|
||||||
|
return "", fmt.Errorf("file transfer: remote path contains an invalid character")
|
||||||
|
}
|
||||||
|
for _, segment := range strings.Split(value, "/") {
|
||||||
|
if segment == ".." {
|
||||||
|
return "", fmt.Errorf("file transfer: remote path must not contain '..'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleaned := path.Clean(value)
|
||||||
|
if cleaned == "." || path.Base(cleaned) == "." || path.Base(cleaned) == ".." {
|
||||||
|
return "", fmt.Errorf("file transfer: remote filename is empty")
|
||||||
|
}
|
||||||
|
return cleaned, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func probeRemotePath(prefix string) (string, error) {
|
||||||
|
prefix = strings.TrimSpace(prefix)
|
||||||
|
prefix = strings.TrimPrefix(prefix, "~")
|
||||||
|
prefix = strings.TrimLeft(prefix, "/")
|
||||||
|
probe := fmt.Sprintf(".snapgo-probe-%d", time.Now().UnixNano())
|
||||||
|
return validateRemoteRelativePath(path.Join(prefix, probe))
|
||||||
|
}
|
||||||
|
|
||||||
|
func temporaryRemoteName(base string) string {
|
||||||
|
return fmt.Sprintf(".%s.snapgo-upload-%d", base, time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
|
type contextReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
reader io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func contextDialFunc(ctx context.Context, timeout time.Duration) func(string, string) (net.Conn, error) {
|
||||||
|
dialer := &net.Dialer{Timeout: timeout}
|
||||||
|
return func(network, address string) (net.Conn, error) {
|
||||||
|
conn, err := dialer.DialContext(ctx, network, address)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
wrapped := &cancelableConn{
|
||||||
|
Conn: conn,
|
||||||
|
done: make(chan struct{}),
|
||||||
|
}
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
_ = wrapped.Close()
|
||||||
|
case <-wrapped.done:
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return wrapped, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type cancelableConn struct {
|
||||||
|
net.Conn
|
||||||
|
done chan struct{}
|
||||||
|
once sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cancelableConn) Close() error {
|
||||||
|
var err error
|
||||||
|
c.once.Do(func() {
|
||||||
|
close(c.done)
|
||||||
|
err = c.Conn.Close()
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *contextReader) Read(p []byte) (int, error) {
|
||||||
|
select {
|
||||||
|
case <-r.ctx.Done():
|
||||||
|
return 0, r.ctx.Err()
|
||||||
|
default:
|
||||||
|
return r.reader.Read(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
package ftp
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateRemoteRelativePath(t *testing.T) {
|
||||||
|
valid, err := validateRemoteRelativePath("snapgo/2026/07/image.png")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("valid path rejected: %v", err)
|
||||||
|
}
|
||||||
|
if valid != "snapgo/2026/07/image.png" {
|
||||||
|
t.Fatalf("unexpected normalized path %q", valid)
|
||||||
|
}
|
||||||
|
|
||||||
|
invalid := []string{
|
||||||
|
"",
|
||||||
|
"/absolute/image.png",
|
||||||
|
"~/image.png",
|
||||||
|
"../image.png",
|
||||||
|
"snapgo/../../image.png",
|
||||||
|
"snapgo\\image.png",
|
||||||
|
"snapgo/image.png\nnext",
|
||||||
|
}
|
||||||
|
for _, value := range invalid {
|
||||||
|
if _, err := validateRemoteRelativePath(value); err == nil {
|
||||||
|
t.Errorf("expected %q to be rejected", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestProbeRemotePathRejectsTraversalPrefix(t *testing.T) {
|
||||||
|
if _, err := probeRemotePath("../../outside"); err == nil {
|
||||||
|
t.Fatal("expected traversal prefix to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package ssh
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/pkg/sftp"
|
||||||
|
|
||||||
|
"github.com/mmmy/snapgo/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
// SFTPUploader transfers screenshots through the SSH File Transfer Protocol.
|
||||||
|
// It lives beside the SCP client so both protocols share the same SSH
|
||||||
|
// authentication and host-key implementation without duplicating credential
|
||||||
|
// discovery code.
|
||||||
|
type SFTPUploader struct {
|
||||||
|
cfg domain.FTPConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewSFTPUploader returns a short-lived SFTP adapter. A fresh SSH/SFTP
|
||||||
|
// connection is opened for every upload or connection probe.
|
||||||
|
func NewSFTPUploader(cfg domain.FTPConfig) *SFTPUploader {
|
||||||
|
return &SFTPUploader{cfg: cfg}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *SFTPUploader) sshConfig() domain.SSHConfig {
|
||||||
|
return domain.SSHConfig{
|
||||||
|
Host: u.cfg.Host,
|
||||||
|
Port: u.cfg.Port,
|
||||||
|
User: u.cfg.User,
|
||||||
|
AuthMethod: u.cfg.AuthMethod,
|
||||||
|
Password: u.cfg.Password,
|
||||||
|
StrictHostKey: u.cfg.StrictHostKey,
|
||||||
|
KnownHostsPath: u.cfg.KnownHostsPath,
|
||||||
|
ConnectTimeoutSecs: u.cfg.ConnectTimeoutSecs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *SFTPUploader) dial(ctx context.Context) (*Client, *sftp.Client, error) {
|
||||||
|
sshClient, err := Dial(ctx, u.sshConfig())
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("sftp: %w", err)
|
||||||
|
}
|
||||||
|
sftpClient, err := sftp.NewClient(sshClient.client)
|
||||||
|
if err != nil {
|
||||||
|
_ = sshClient.Close()
|
||||||
|
return nil, nil, fmt.Errorf("sftp: start subsystem: %w", err)
|
||||||
|
}
|
||||||
|
return sshClient, sftpClient, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload writes data to a temporary file and atomically exposes it at the
|
||||||
|
// final relative path after the transfer completes.
|
||||||
|
func (u *SFTPUploader) Upload(ctx context.Context, remoteRelPath string, data []byte) error {
|
||||||
|
cleaned, err := validateSFTPRemotePath(remoteRelPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sshClient, sftpClient, err := u.dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
done := closeSFTPOnCancel(ctx, sshClient, sftpClient)
|
||||||
|
defer sshClient.Close()
|
||||||
|
defer sftpClient.Close()
|
||||||
|
defer close(done)
|
||||||
|
|
||||||
|
dir := path.Dir(cleaned)
|
||||||
|
if dir != "." {
|
||||||
|
if err := sftpClient.MkdirAll(dir); err != nil {
|
||||||
|
return fmt.Errorf("sftp: create directory %s: %w", dir, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tempPath := path.Join(dir, temporarySFTPName(path.Base(cleaned)))
|
||||||
|
removeTemp := true
|
||||||
|
defer func() {
|
||||||
|
if removeTemp {
|
||||||
|
_ = sftpClient.Remove(tempPath)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
file, err := sftpClient.OpenFile(tempPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("sftp: create temporary file: %w", err)
|
||||||
|
}
|
||||||
|
reader := &sftpContextReader{ctx: ctx, reader: bytes.NewReader(data)}
|
||||||
|
_, copyErr := io.Copy(file, reader)
|
||||||
|
if copyErr == nil {
|
||||||
|
copyErr = file.Chmod(0o644)
|
||||||
|
}
|
||||||
|
closeErr := file.Close()
|
||||||
|
if copyErr != nil {
|
||||||
|
if ctx.Err() != nil {
|
||||||
|
return ctx.Err()
|
||||||
|
}
|
||||||
|
return fmt.Errorf("sftp: write %s: %w", cleaned, copyErr)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
return fmt.Errorf("sftp: close %s: %w", cleaned, closeErr)
|
||||||
|
}
|
||||||
|
if err := sftpClient.Rename(tempPath, cleaned); err != nil {
|
||||||
|
return fmt.Errorf("sftp: commit %s: %w", cleaned, err)
|
||||||
|
}
|
||||||
|
removeTemp = false
|
||||||
|
sshLog().Info("SFTP upload ok", "remote_path", cleaned, "size", len(data))
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestConnection verifies SFTP write/delete permissions with a small probe.
|
||||||
|
func (u *SFTPUploader) TestConnection(ctx context.Context) error {
|
||||||
|
probe, err := sftpProbePath(u.cfg.PathPrefix)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
sshClient, sftpClient, err := u.dial(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
done := closeSFTPOnCancel(ctx, sshClient, sftpClient)
|
||||||
|
defer sshClient.Close()
|
||||||
|
defer sftpClient.Close()
|
||||||
|
defer close(done)
|
||||||
|
|
||||||
|
dir := path.Dir(probe)
|
||||||
|
if dir != "." {
|
||||||
|
if err := sftpClient.MkdirAll(dir); err != nil {
|
||||||
|
return fmt.Errorf("sftp probe: create directory: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file, err := sftpClient.OpenFile(probe, os.O_WRONLY|os.O_CREATE|os.O_TRUNC)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("sftp probe: create: %w", err)
|
||||||
|
}
|
||||||
|
_, writeErr := file.Write([]byte("snapgo"))
|
||||||
|
closeErr := file.Close()
|
||||||
|
if writeErr != nil {
|
||||||
|
_ = sftpClient.Remove(probe)
|
||||||
|
return fmt.Errorf("sftp probe: write: %w", writeErr)
|
||||||
|
}
|
||||||
|
if closeErr != nil {
|
||||||
|
_ = sftpClient.Remove(probe)
|
||||||
|
return fmt.Errorf("sftp probe: close: %w", closeErr)
|
||||||
|
}
|
||||||
|
if err := sftpClient.Remove(probe); err != nil {
|
||||||
|
return fmt.Errorf("sftp probe: delete: %w", err)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func closeSFTPOnCancel(ctx context.Context, sshClient *Client, sftpClient *sftp.Client) chan struct{} {
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
_ = sftpClient.Close()
|
||||||
|
_ = sshClient.Close()
|
||||||
|
case <-done:
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
return done
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateSFTPRemotePath(value string) (string, error) {
|
||||||
|
value = strings.TrimSpace(value)
|
||||||
|
if value == "" || strings.HasPrefix(value, "/") || strings.HasPrefix(value, "~") {
|
||||||
|
return "", fmt.Errorf("sftp: remote path must be relative to the login directory")
|
||||||
|
}
|
||||||
|
if strings.ContainsAny(value, "\x00\r\n\\") {
|
||||||
|
return "", fmt.Errorf("sftp: remote path contains an invalid character")
|
||||||
|
}
|
||||||
|
for _, segment := range strings.Split(value, "/") {
|
||||||
|
if segment == ".." {
|
||||||
|
return "", fmt.Errorf("sftp: remote path must not contain '..'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cleaned := path.Clean(value)
|
||||||
|
if cleaned == "." || path.Base(cleaned) == "." || path.Base(cleaned) == ".." {
|
||||||
|
return "", fmt.Errorf("sftp: remote filename is empty")
|
||||||
|
}
|
||||||
|
return cleaned, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func sftpProbePath(prefix string) (string, error) {
|
||||||
|
prefix = strings.TrimSpace(prefix)
|
||||||
|
prefix = strings.TrimPrefix(prefix, "~")
|
||||||
|
prefix = strings.TrimLeft(prefix, "/")
|
||||||
|
return validateSFTPRemotePath(path.Join(prefix, fmt.Sprintf(".snapgo-probe-%d", time.Now().UnixNano())))
|
||||||
|
}
|
||||||
|
|
||||||
|
func temporarySFTPName(base string) string {
|
||||||
|
return fmt.Sprintf(".%s.snapgo-upload-%d", base, time.Now().UnixNano())
|
||||||
|
}
|
||||||
|
|
||||||
|
type sftpContextReader struct {
|
||||||
|
ctx context.Context
|
||||||
|
reader io.Reader
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *sftpContextReader) Read(p []byte) (int, error) {
|
||||||
|
select {
|
||||||
|
case <-r.ctx.Done():
|
||||||
|
return 0, r.ctx.Err()
|
||||||
|
default:
|
||||||
|
return r.reader.Read(p)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package ssh
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestValidateSFTPRemotePathRejectsTraversal(t *testing.T) {
|
||||||
|
if got, err := validateSFTPRemotePath("snapgo/2026/image.png"); err != nil || got != "snapgo/2026/image.png" {
|
||||||
|
t.Fatalf("valid path: got %q err=%v", got, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, value := range []string{
|
||||||
|
"",
|
||||||
|
"/absolute/image.png",
|
||||||
|
"~/image.png",
|
||||||
|
"../image.png",
|
||||||
|
"snapgo/../../image.png",
|
||||||
|
"snapgo\\image.png",
|
||||||
|
} {
|
||||||
|
if _, err := validateSFTPRemotePath(value); err == nil {
|
||||||
|
t.Errorf("expected %q to be rejected", value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestSFTPProbePathRejectsTraversalPrefix(t *testing.T) {
|
||||||
|
if _, err := sftpProbePath("../../outside"); err == nil {
|
||||||
|
t.Fatal("expected traversal prefix to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -74,7 +74,7 @@ func main() {
|
|||||||
WindowIsTranslucent: true,
|
WindowIsTranslucent: true,
|
||||||
About: &mac.AboutInfo{
|
About: &mac.AboutInfo{
|
||||||
Title: "SnapGo",
|
Title: "SnapGo",
|
||||||
Message: "Cross-platform screenshot tool with one-click upload to S3.",
|
Message: "Cross-platform screenshot tool with one-click upload to S3, FTP, SFTP, or SSH.",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -74,6 +74,18 @@ func nativeOverlaySaveRemote(x, y, w, h C.int, annotationsJSON *C.char) {
|
|||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//export nativeOverlayUploadFTP
|
||||||
|
func nativeOverlayUploadFTP(x, y, w, h C.int, annotationsJSON *C.char) {
|
||||||
|
app := consumeNativeOverlayApp()
|
||||||
|
if app == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
result := nativeCaptureResult(x, y, w, h, annotationsJSON)
|
||||||
|
go func() {
|
||||||
|
_ = app.UploadNativeRegionToFTP(result)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
//export nativeOverlaySummarize
|
//export nativeOverlaySummarize
|
||||||
func nativeOverlaySummarize(x, y, w, h C.int, annotationsJSON *C.char) {
|
func nativeOverlaySummarize(x, y, w, h C.int, annotationsJSON *C.char) {
|
||||||
app := consumeNativeOverlayApp()
|
app := consumeNativeOverlayApp()
|
||||||
|
|||||||
+320
-28
@@ -15,6 +15,7 @@ extern void nativeOverlayConfirm(int x, int y, int w, int h, const char *annotat
|
|||||||
extern void nativeOverlayCopy(int x, int y, int w, int h, const char *annotationsJSON);
|
extern void nativeOverlayCopy(int x, int y, int w, int h, const char *annotationsJSON);
|
||||||
extern void nativeOverlaySave(int x, int y, int w, int h, const char *annotationsJSON, const char *dir);
|
extern void nativeOverlaySave(int x, int y, int w, int h, const char *annotationsJSON, const char *dir);
|
||||||
extern void nativeOverlaySaveRemote(int x, int y, int w, int h, const char *annotationsJSON);
|
extern void nativeOverlaySaveRemote(int x, int y, int w, int h, const char *annotationsJSON);
|
||||||
|
extern void nativeOverlayUploadFTP(int x, int y, int w, int h, const char *annotationsJSON);
|
||||||
extern void nativeOverlaySummarize(int x, int y, int w, int h, const char *annotationsJSON);
|
extern void nativeOverlaySummarize(int x, int y, int w, int h, const char *annotationsJSON);
|
||||||
extern void nativeOverlayOCR(int x, int y, int w, int h, const char *annotationsJSON);
|
extern void nativeOverlayOCR(int x, int y, int w, int h, const char *annotationsJSON);
|
||||||
extern void nativeOverlayCancel(void);
|
extern void nativeOverlayCancel(void);
|
||||||
@@ -141,8 +142,14 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
@property(strong) NSColor *activeColor;
|
@property(strong) NSColor *activeColor;
|
||||||
@property CGFloat activeStrokeWidth;
|
@property CGFloat activeStrokeWidth;
|
||||||
@property CGFloat activeFontSize;
|
@property CGFloat activeFontSize;
|
||||||
|
@property CGFloat mosaicBrushWidth;
|
||||||
|
@property NSString *mosaicMode;
|
||||||
@property(strong) NSMutableArray<NSDictionary *> *annotations;
|
@property(strong) NSMutableArray<NSDictionary *> *annotations;
|
||||||
@property(strong) NSMutableDictionary *draftAnnotation;
|
@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;
|
@property(strong) NSButton *cancelButton;
|
||||||
// Use `clipboardButton` (not `copyButton`) to avoid ARC's "copy" method
|
// Use `clipboardButton` (not `copyButton`) to avoid ARC's "copy" method
|
||||||
// family ownership rule which would otherwise treat the synthesized getter
|
// family ownership rule which would otherwise treat the synthesized getter
|
||||||
@@ -150,19 +157,25 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
@property(strong) NSButton *clipboardButton;
|
@property(strong) NSButton *clipboardButton;
|
||||||
@property(strong) NSButton *saveButton;
|
@property(strong) NSButton *saveButton;
|
||||||
@property(strong) NSButton *saveRemoteButton;
|
@property(strong) NSButton *saveRemoteButton;
|
||||||
|
@property(strong) NSButton *ftpButton;
|
||||||
@property(strong) NSButton *ocrButton;
|
@property(strong) NSButton *ocrButton;
|
||||||
@property(strong) NSButton *summaryButton;
|
@property(strong) NSButton *summaryButton;
|
||||||
@property(strong) NSButton *uploadButton;
|
@property(strong) NSButton *uploadButton;
|
||||||
@property(strong) NSButton *penButton;
|
@property(strong) NSButton *penButton;
|
||||||
|
@property(strong) NSButton *lineButton;
|
||||||
|
@property(strong) NSButton *arrowButton;
|
||||||
@property(strong) NSButton *rectButton;
|
@property(strong) NSButton *rectButton;
|
||||||
@property(strong) NSButton *ellipseButton;
|
@property(strong) NSButton *ellipseButton;
|
||||||
@property(strong) NSButton *textButton;
|
@property(strong) NSButton *textButton;
|
||||||
|
@property(strong) NSButton *mosaicButton;
|
||||||
@property(strong) NSButton *undoButton;
|
@property(strong) NSButton *undoButton;
|
||||||
@property(strong) SnipToolSettingsView *toolSettingsView;
|
@property(strong) SnipToolSettingsView *toolSettingsView;
|
||||||
@property(strong) NSView *settingsDivider;
|
@property(strong) NSView *settingsDivider;
|
||||||
@property(strong) NSMutableArray<NSButton *> *strokeSettingButtons;
|
@property(strong) NSMutableArray<NSButton *> *strokeSettingButtons;
|
||||||
@property(strong) NSMutableArray<NSButton *> *fontSettingButtons;
|
@property(strong) NSMutableArray<NSButton *> *fontSettingButtons;
|
||||||
@property(strong) NSMutableArray<NSButton *> *colorSettingButtons;
|
@property(strong) NSMutableArray<NSButton *> *colorSettingButtons;
|
||||||
|
@property(strong) NSMutableArray<NSButton *> *mosaicModeButtons;
|
||||||
|
@property(strong) NSMutableArray<NSButton *> *mosaicWidthButtons;
|
||||||
@property(strong) NSView *actionToolbarBg;
|
@property(strong) NSView *actionToolbarBg;
|
||||||
@property(strong) NSTextField *textEditor;
|
@property(strong) NSTextField *textEditor;
|
||||||
@property NSPoint textEditorLocalPoint;
|
@property NSPoint textEditorLocalPoint;
|
||||||
@@ -181,6 +194,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
- (void)copySelection;
|
- (void)copySelection;
|
||||||
- (void)saveSelection;
|
- (void)saveSelection;
|
||||||
- (void)saveRemoteSelection;
|
- (void)saveRemoteSelection;
|
||||||
|
- (void)uploadFTPSelection;
|
||||||
- (void)ocrSelection;
|
- (void)ocrSelection;
|
||||||
- (void)summarizeSelection;
|
- (void)summarizeSelection;
|
||||||
- (void)cancelSelection;
|
- (void)cancelSelection;
|
||||||
@@ -192,6 +206,8 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
- (void)selectStrokeWidth:(NSButton *)sender;
|
- (void)selectStrokeWidth:(NSButton *)sender;
|
||||||
- (void)selectFontSize:(NSButton *)sender;
|
- (void)selectFontSize:(NSButton *)sender;
|
||||||
- (void)selectToolColor:(NSButton *)sender;
|
- (void)selectToolColor:(NSButton *)sender;
|
||||||
|
- (void)selectMosaicMode:(NSButton *)sender;
|
||||||
|
- (void)selectMosaicWidth:(NSButton *)sender;
|
||||||
- (BOOL)isEditingText;
|
- (BOOL)isEditingText;
|
||||||
- (void)commitTextEditor;
|
- (void)commitTextEditor;
|
||||||
- (void)cancelTextEditor;
|
- (void)cancelTextEditor;
|
||||||
@@ -211,6 +227,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];
|
_activeColor = [NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0];
|
||||||
_activeStrokeWidth = 3.0;
|
_activeStrokeWidth = 3.0;
|
||||||
_activeFontSize = 20.0;
|
_activeFontSize = 20.0;
|
||||||
|
_mosaicBrushWidth = 24.0;
|
||||||
|
_mosaicMode = @"brush";
|
||||||
_annotations = [NSMutableArray array];
|
_annotations = [NSMutableArray array];
|
||||||
_textEditorAnnotationIndex = -1;
|
_textEditorAnnotationIndex = -1;
|
||||||
_selectedTextAnnotationIndex = -1;
|
_selectedTextAnnotationIndex = -1;
|
||||||
@@ -222,6 +240,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
_clipboardButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(copySelection)];
|
_clipboardButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(copySelection)];
|
||||||
_saveButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(saveSelection)];
|
_saveButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(saveSelection)];
|
||||||
_saveRemoteButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(saveRemoteSelection)];
|
_saveRemoteButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(saveRemoteSelection)];
|
||||||
|
_ftpButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(uploadFTPSelection)];
|
||||||
_ocrButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(ocrSelection)];
|
_ocrButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(ocrSelection)];
|
||||||
_summaryButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(summarizeSelection)];
|
_summaryButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(summarizeSelection)];
|
||||||
_uploadButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(confirmSelection)];
|
_uploadButton = [SnipHoverButton buttonWithTitle:@"" target:self action:@selector(confirmSelection)];
|
||||||
@@ -230,20 +249,26 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[_cancelButton setToolTip:@"取消截图"];
|
[_cancelButton setToolTip:@"取消截图"];
|
||||||
[_clipboardButton setToolTip:@"复制图片"];
|
[_clipboardButton setToolTip:@"复制图片"];
|
||||||
[_saveButton setToolTip:@"保存本地"];
|
[_saveButton setToolTip:@"保存本地"];
|
||||||
[_saveRemoteButton setToolTip:@"保存远端"];
|
[_saveRemoteButton setToolTip:@"上传 SSH/SCP"];
|
||||||
|
[_ftpButton setToolTip:@"上传 FTP/SFTP"];
|
||||||
[_ocrButton setToolTip:@"提取文字"];
|
[_ocrButton setToolTip:@"提取文字"];
|
||||||
[_summaryButton setToolTip:@"复制总结"];
|
[_summaryButton setToolTip:@"复制总结"];
|
||||||
[_uploadButton setToolTip:@"上传云端"];
|
[_uploadButton setToolTip:@"上传 S3"];
|
||||||
_penButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectPen)];
|
_penButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectPen)];
|
||||||
|
_lineButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectLine)];
|
||||||
|
_arrowButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectArrow)];
|
||||||
_rectButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectRect)];
|
_rectButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectRect)];
|
||||||
_ellipseButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectEllipse)];
|
_ellipseButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectEllipse)];
|
||||||
_textButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectText)];
|
_textButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectText)];
|
||||||
|
_mosaicButton = [NSButton buttonWithTitle:@"" target:self action:@selector(selectMosaic)];
|
||||||
_undoButton = [NSButton buttonWithTitle:@"" target:self action:@selector(undoAnnotation)];
|
_undoButton = [NSButton buttonWithTitle:@"" target:self action:@selector(undoAnnotation)];
|
||||||
_toolSettingsView = [[SnipToolSettingsView alloc] initWithFrame:NSZeroRect];
|
_toolSettingsView = [[SnipToolSettingsView alloc] initWithFrame:NSZeroRect];
|
||||||
_settingsDivider = [[NSView alloc] initWithFrame:NSZeroRect];
|
_settingsDivider = [[NSView alloc] initWithFrame:NSZeroRect];
|
||||||
_strokeSettingButtons = [NSMutableArray array];
|
_strokeSettingButtons = [NSMutableArray array];
|
||||||
_fontSettingButtons = [NSMutableArray array];
|
_fontSettingButtons = [NSMutableArray array];
|
||||||
_colorSettingButtons = [NSMutableArray array];
|
_colorSettingButtons = [NSMutableArray array];
|
||||||
|
_mosaicModeButtons = [NSMutableArray array];
|
||||||
|
_mosaicWidthButtons = [NSMutableArray array];
|
||||||
// Dark rounded background container behind the action icon buttons,
|
// Dark rounded background container behind the action icon buttons,
|
||||||
// mirroring the look of `.action-toolbar` in the Vue overlay.
|
// mirroring the look of `.action-toolbar` in the Vue overlay.
|
||||||
_actionToolbarBg = [[NSView alloc] initWithFrame:NSZeroRect];
|
_actionToolbarBg = [[NSView alloc] initWithFrame:NSZeroRect];
|
||||||
@@ -257,10 +282,10 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
// Add the action toolbar background BEFORE the buttons so it sits
|
// Add the action toolbar background BEFORE the buttons so it sits
|
||||||
// behind them in the view hierarchy (AppKit z-order = subview order).
|
// behind them in the view hierarchy (AppKit z-order = subview order).
|
||||||
[self addSubview:_actionToolbarBg];
|
[self addSubview:_actionToolbarBg];
|
||||||
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _undoButton, _toolSettingsView, _sizeLabel, _hintLabel]) {
|
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _lineButton, _arrowButton, _rectButton, _ellipseButton, _textButton, _mosaicButton, _undoButton, _toolSettingsView, _sizeLabel, _hintLabel]) {
|
||||||
[self addSubview:view];
|
[self addSubview:view];
|
||||||
}
|
}
|
||||||
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _rectButton, _ellipseButton, _textButton, _undoButton, _toolSettingsView, _actionToolbarBg]) {
|
for (NSView *view in @[_cancelButton, _clipboardButton, _saveButton, _saveRemoteButton, _ftpButton, _ocrButton, _summaryButton, _uploadButton, _penButton, _lineButton, _arrowButton, _rectButton, _ellipseButton, _textButton, _mosaicButton, _undoButton, _toolSettingsView, _actionToolbarBg]) {
|
||||||
[view setHidden:YES];
|
[view setHidden:YES];
|
||||||
}
|
}
|
||||||
[_sizeLabel setHidden:YES];
|
[_sizeLabel setHidden:YES];
|
||||||
@@ -323,7 +348,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
}
|
}
|
||||||
|
|
||||||
- (void)styleControls {
|
- (void)styleControls {
|
||||||
// Cancel / Copy / Save / Save-remote / OCR / Summary / Upload — square icon buttons
|
// Cancel / Copy / Save / SSH / FTP / OCR / Summary / S3 — square icon buttons
|
||||||
// rendered from the user-supplied SVG assets. All actions default to white
|
// rendered from the user-supplied SVG assets. All actions default to white
|
||||||
// and animate to a per-action accent color on hover (cancel = red,
|
// and animate to a per-action accent color on hover (cancel = red,
|
||||||
// others = blue). The base "white default" replaces the previous blue
|
// others = blue). The base "white default" replaces the previous blue
|
||||||
@@ -334,6 +359,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
// save-remote.svg — provided by the user; its content is the same arrow
|
// save-remote.svg — provided by the user; its content is the same arrow
|
||||||
// icon as the previous upload, so we reuse it verbatim here.
|
// icon as the previous upload, so we reuse it verbatim here.
|
||||||
NSImage *saveRemoteIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M481.749333 353.792c16.682667-16.64 43.690667-16.64 60.373334 0l120.917333 120.832 3.541333 4.010667a42.666667 42.666667 0 0 1-63.872 56.32L554.666667 486.954667V896a42.666667 42.666667 0 0 1-85.333334 0v-409.173333l-48.170666 48.128a42.666667 42.666667 0 0 1-60.330667 0l-3.541333-4.010667a42.666667 42.666667 0 0 1 3.541333-56.32zM512 85.333333c122.538667 0 227.84 73.813333 273.92 179.370667A213.333333 213.333333 0 0 1 725.333333 682.666667a42.666667 42.666667 0 0 1-4.992-85.034667L725.333333 597.333333a128 128 0 0 0 36.394667-250.794666l-38.144-11.264-15.914667-36.437334a213.376 213.376 0 0 0-407.296 58.026667l-7.381333 58.368-57.173333 13.824A85.418667 85.418667 0 0 0 256 597.333333h42.666667a42.666667 42.666667 0 0 1 0 85.333334H256a170.666667 170.666667 0 0 1-40.277333-336.554667A298.709333 298.709333 0 0 1 512 85.333333z' fill='white'/></svg>"];
|
NSImage *saveRemoteIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M481.749333 353.792c16.682667-16.64 43.690667-16.64 60.373334 0l120.917333 120.832 3.541333 4.010667a42.666667 42.666667 0 0 1-63.872 56.32L554.666667 486.954667V896a42.666667 42.666667 0 0 1-85.333334 0v-409.173333l-48.170666 48.128a42.666667 42.666667 0 0 1-60.330667 0l-3.541333-4.010667a42.666667 42.666667 0 0 1 3.541333-56.32zM512 85.333333c122.538667 0 227.84 73.813333 273.92 179.370667A213.333333 213.333333 0 0 1 725.333333 682.666667a42.666667 42.666667 0 0 1-4.992-85.034667L725.333333 597.333333a128 128 0 0 0 36.394667-250.794666l-38.144-11.264-15.914667-36.437334a213.376 213.376 0 0 0-407.296 58.026667l-7.381333 58.368-57.173333 13.824A85.418667 85.418667 0 0 0 256 597.333333h42.666667a42.666667 42.666667 0 0 1 0 85.333334H256a170.666667 170.666667 0 0 1-40.277333-336.554667A298.709333 298.709333 0 0 1 512 85.333333z' fill='white'/></svg>"];
|
||||||
|
NSImage *ftpIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M128 128h768v256H128V128zm64 64v128h640V192H192zm64 48h64v32h-64v-32zM128 448h416v64H192v192h352v64H128V448zm560-32 160 160-45.248 45.248L720 538.496V832h-64V538.496l-82.752 82.752L528 576l160-160z' fill='white'/></svg>"];
|
||||||
NSImage *ocrIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M192 160h192v64H256v128h-64V160zM640 160h192v192h-64V224H640v-64zM256 672v128h128v64H192V672h64zM832 672v192H640v-64h128V672h64zM469.333333 288h85.333334l170.666666 448h-78.933333l-39.253333-106.666667H416.853333L377.6 736H298.666667l170.666666-448zM439.466667 565.333333h144.896L512 368.981333 439.466667 565.333333z' fill='white'/></svg>"];
|
NSImage *ocrIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M192 160h192v64H256v128h-64V160zM640 160h192v192h-64V224H640v-64zM256 672v128h128v64H192V672h64zM832 672v192H640v-64h128V672h64zM469.333333 288h85.333334l170.666666 448h-78.933333l-39.253333-106.666667H416.853333L377.6 736H298.666667l170.666666-448zM439.466667 565.333333h144.896L512 368.981333 439.466667 565.333333z' fill='white'/></svg>"];
|
||||||
NSImage *summaryIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M256 128h448l192 192v576H256V128z m64 64v640h512V352H672V192H320z m416 45.248V288h50.752L736 237.248zM384 448h384v64H384v-64z m0 128h384v64H384v-64z m0 128h256v64H384v-64zM192 256v704h512v64H128V256h64z' fill='white'/></svg>"];
|
NSImage *summaryIcon = [self iconFromSVG:@"<svg viewBox='0 0 1024 1024' xmlns='http://www.w3.org/2000/svg'><path d='M256 128h448l192 192v576H256V128z m64 64v640h512V352H672V192H320z m416 45.248V288h50.752L736 237.248zM384 448h384v64H384v-64z m0 128h384v64H384v-64z m0 128h256v64H384v-64zM192 256v704h512v64H128V256h64z' fill='white'/></svg>"];
|
||||||
// upload.svg — newly replaced "send/cloud" icon supplied by the user.
|
// upload.svg — newly replaced "send/cloud" icon supplied by the user.
|
||||||
@@ -343,6 +369,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[self styleIconButton:_clipboardButton image:copyIcon];
|
[self styleIconButton:_clipboardButton image:copyIcon];
|
||||||
[self styleIconButton:_saveButton image:saveIcon];
|
[self styleIconButton:_saveButton image:saveIcon];
|
||||||
[self styleIconButton:_saveRemoteButton image:saveRemoteIcon];
|
[self styleIconButton:_saveRemoteButton image:saveRemoteIcon];
|
||||||
|
[self styleIconButton:_ftpButton image:ftpIcon];
|
||||||
[self styleIconButton:_ocrButton image:ocrIcon];
|
[self styleIconButton:_ocrButton image:ocrIcon];
|
||||||
[self styleIconButton:_summaryButton image:summaryIcon];
|
[self styleIconButton:_summaryButton image:summaryIcon];
|
||||||
[self styleIconButton:_uploadButton image:uploadIcon];
|
[self styleIconButton:_uploadButton image:uploadIcon];
|
||||||
@@ -357,6 +384,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
SnipHoverButton *clipboardHB = (SnipHoverButton *)_clipboardButton;
|
SnipHoverButton *clipboardHB = (SnipHoverButton *)_clipboardButton;
|
||||||
SnipHoverButton *saveHB = (SnipHoverButton *)_saveButton;
|
SnipHoverButton *saveHB = (SnipHoverButton *)_saveButton;
|
||||||
SnipHoverButton *saveRemoteHB = (SnipHoverButton *)_saveRemoteButton;
|
SnipHoverButton *saveRemoteHB = (SnipHoverButton *)_saveRemoteButton;
|
||||||
|
SnipHoverButton *ftpHB = (SnipHoverButton *)_ftpButton;
|
||||||
SnipHoverButton *ocrHB = (SnipHoverButton *)_ocrButton;
|
SnipHoverButton *ocrHB = (SnipHoverButton *)_ocrButton;
|
||||||
SnipHoverButton *summaryHB = (SnipHoverButton *)_summaryButton;
|
SnipHoverButton *summaryHB = (SnipHoverButton *)_summaryButton;
|
||||||
SnipHoverButton *uploadHB = (SnipHoverButton *)_uploadButton;
|
SnipHoverButton *uploadHB = (SnipHoverButton *)_uploadButton;
|
||||||
@@ -364,14 +392,22 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
clipboardHB.baseColor = baseWhite; clipboardHB.hoverColor = hoverBlue;
|
clipboardHB.baseColor = baseWhite; clipboardHB.hoverColor = hoverBlue;
|
||||||
saveHB.baseColor = baseWhite; saveHB.hoverColor = hoverBlue;
|
saveHB.baseColor = baseWhite; saveHB.hoverColor = hoverBlue;
|
||||||
saveRemoteHB.baseColor = baseWhite; saveRemoteHB.hoverColor = hoverBlue;
|
saveRemoteHB.baseColor = baseWhite; saveRemoteHB.hoverColor = hoverBlue;
|
||||||
|
ftpHB.baseColor = baseWhite; ftpHB.hoverColor = hoverBlue;
|
||||||
ocrHB.baseColor = baseWhite; ocrHB.hoverColor = hoverBlue;
|
ocrHB.baseColor = baseWhite; ocrHB.hoverColor = hoverBlue;
|
||||||
summaryHB.baseColor = baseWhite; summaryHB.hoverColor = hoverBlue;
|
summaryHB.baseColor = baseWhite; summaryHB.hoverColor = hoverBlue;
|
||||||
uploadHB.baseColor = baseWhite; uploadHB.hoverColor = hoverBlue;
|
uploadHB.baseColor = baseWhite; uploadHB.hoverColor = hoverBlue;
|
||||||
|
|
||||||
[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:_penButton image:[self iconFromSVG:@"<svg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><g fill='none' stroke='white' stroke-width='1.8' stroke-linecap='round' stroke-linejoin='round'><path d='m14.5 5.5 4-4 4 4-4 4'/><path d='m17.5 8.5-7.8 7.8'/><path d='M11 14.8c.8 2.8-.7 5.5-3.7 6.3-1.8.5-3.7.1-5.3-.9 2.1-.4 2.8-1.5 3.1-3.3.4-2.5 3.3-3.8 5.9-2.1Z'/></g></svg>"]];
|
||||||
|
[self styleIconButton:_lineButton image:[self iconFromSVG:@"<svg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><path d='M5 19 19 5' fill='none' stroke='white' stroke-width='2' stroke-linecap='round'/></svg>"]];
|
||||||
|
[self styleIconButton:_arrowButton image:[self iconFromSVG:@"<svg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'><g fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M5 19 19 5'/><path d='M11 5h8v8'/></g></svg>"]];
|
||||||
|
[_penButton setToolTip:@"画笔标记"];
|
||||||
|
[_lineButton setToolTip:@"直线标记"];
|
||||||
|
[_arrowButton setToolTip:@"箭头标记"];
|
||||||
[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:_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:_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:_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>"]];
|
[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];
|
[_toolSettingsView setWantsLayer:NO];
|
||||||
@@ -406,6 +442,37 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[_toolSettingsView addSubview:button];
|
[_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 = @[
|
NSArray *colors = @[
|
||||||
[NSColor colorWithCalibratedRed:239.0/255.0 green:68.0/255.0 blue:68.0/255.0 alpha:1.0],
|
[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],
|
[NSColor colorWithCalibratedRed:250.0/255.0 green:204.0/255.0 blue:21.0/255.0 alpha:1.0],
|
||||||
@@ -620,6 +687,63 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
}
|
}
|
||||||
continue;
|
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];
|
[color setStroke];
|
||||||
CGFloat strokeWidth = [self strokeWidthForItem:item];
|
CGFloat strokeWidth = [self strokeWidthForItem:item];
|
||||||
NSBezierPath *path = [NSBezierPath bezierPath];
|
NSBezierPath *path = [NSBezierPath bezierPath];
|
||||||
@@ -637,12 +761,35 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
} else if (points.count >= 2) {
|
} else if (points.count >= 2) {
|
||||||
NSPoint a = [points[0] pointValue];
|
NSPoint a = [points[0] pointValue];
|
||||||
NSPoint b = [[points lastObject] pointValue];
|
NSPoint b = [[points lastObject] pointValue];
|
||||||
|
NSPoint start = NSMakePoint(_selection.origin.x + a.x, _selection.origin.y + a.y);
|
||||||
|
NSPoint end = NSMakePoint(_selection.origin.x + b.x, _selection.origin.y + b.y);
|
||||||
NSRect r = NSMakeRect(
|
NSRect r = NSMakeRect(
|
||||||
_selection.origin.x + MIN(a.x, b.x),
|
_selection.origin.x + MIN(a.x, b.x),
|
||||||
_selection.origin.y + MIN(a.y, b.y),
|
_selection.origin.y + MIN(a.y, b.y),
|
||||||
fabs(b.x - a.x),
|
fabs(b.x - a.x),
|
||||||
fabs(b.y - a.y));
|
fabs(b.y - a.y));
|
||||||
if ([tool isEqualToString:@"rect"]) {
|
if ([tool isEqualToString:@"line"] || [tool isEqualToString:@"arrow"]) {
|
||||||
|
NSBezierPath *linePath = [NSBezierPath bezierPath];
|
||||||
|
[linePath moveToPoint:start];
|
||||||
|
[linePath lineToPoint:end];
|
||||||
|
[linePath setLineWidth:strokeWidth];
|
||||||
|
[linePath setLineCapStyle:NSLineCapStyleRound];
|
||||||
|
[linePath setLineJoinStyle:NSLineJoinStyleRound];
|
||||||
|
if ([tool isEqualToString:@"arrow"]) {
|
||||||
|
CGFloat dx = end.x - start.x, dy = end.y - start.y;
|
||||||
|
CGFloat length = hypot(dx, dy);
|
||||||
|
if (length >= 1.0) {
|
||||||
|
CGFloat headLength = MIN(length * 0.45, MAX(10.0, strokeWidth * 4.0));
|
||||||
|
CGFloat angle = atan2(dy, dx), spread = M_PI / 6.0;
|
||||||
|
NSPoint left = NSMakePoint(end.x - headLength * cos(angle - spread), end.y - headLength * sin(angle - spread));
|
||||||
|
NSPoint right = NSMakePoint(end.x - headLength * cos(angle + spread), end.y - headLength * sin(angle + spread));
|
||||||
|
[linePath moveToPoint:left];
|
||||||
|
[linePath lineToPoint:end];
|
||||||
|
[linePath lineToPoint:right];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[linePath stroke];
|
||||||
|
} else if ([tool isEqualToString:@"rect"]) {
|
||||||
NSBezierPath *rectPath = [NSBezierPath bezierPathWithRect:r];
|
NSBezierPath *rectPath = [NSBezierPath bezierPathWithRect:r];
|
||||||
[rectPath setLineWidth:strokeWidth];
|
[rectPath setLineWidth:strokeWidth];
|
||||||
[rectPath stroke];
|
[rectPath stroke];
|
||||||
@@ -691,6 +838,24 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
MAX(0, MIN(p.y - _selection.origin.y, _selection.size.height)));
|
MAX(0, MIN(p.y - _selection.origin.y, _selection.size.height)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Annotations use selection-local coordinates. When a top or left resize
|
||||||
|
// moves the selection origin, offset every local point in the opposite
|
||||||
|
// direction so the annotation remains attached to the same screen pixels.
|
||||||
|
- (void)preserveAnnotationScreenPositionsFromOrigin:(NSPoint)previousOrigin toOrigin:(NSPoint)nextOrigin {
|
||||||
|
CGFloat dx = previousOrigin.x - nextOrigin.x;
|
||||||
|
CGFloat dy = previousOrigin.y - nextOrigin.y;
|
||||||
|
if (fabs(dx) <= 0.001 && fabs(dy) <= 0.001) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for (NSDictionary *annotation in _annotations) {
|
||||||
|
NSMutableArray *points = (NSMutableArray *)annotation[@"points"];
|
||||||
|
for (NSUInteger i = 0; i < points.count; i++) {
|
||||||
|
NSPoint point = [points[i] pointValue];
|
||||||
|
points[i] = [NSValue valueWithPoint:NSMakePoint(point.x + dx, point.y + dy)];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Translate a selection rectangle expressed in view-local coordinates into
|
// Translate a selection rectangle expressed in view-local coordinates into
|
||||||
// the global top-left screen coordinate system used by
|
// the global top-left screen coordinate system used by
|
||||||
// `/usr/sbin/screencapture -R`.
|
// `/usr/sbin/screencapture -R`.
|
||||||
@@ -796,7 +961,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
@"tool": _activeTool,
|
@"tool": _activeTool,
|
||||||
@"color": [self hexForColor:_activeColor],
|
@"color": [self hexForColor:_activeColor],
|
||||||
@"nsColor": _activeColor,
|
@"nsColor": _activeColor,
|
||||||
@"strokeWidth": @(_activeStrokeWidth),
|
@"strokeWidth": @([_activeTool isEqualToString:@"mosaic-brush"] ? _mosaicBrushWidth : _activeStrokeWidth),
|
||||||
@"points": [NSMutableArray arrayWithObject:[NSValue valueWithPoint:local]]
|
@"points": [NSMutableArray arrayWithObject:[NSValue valueWithPoint:local]]
|
||||||
} mutableCopy];
|
} mutableCopy];
|
||||||
} else if (_hasSelection && NSPointInRect(p, _selection)) {
|
} else if (_hasSelection && NSPointInRect(p, _selection)) {
|
||||||
@@ -845,7 +1010,9 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
right = MAX(0, MIN(right, self.bounds.size.width));
|
right = MAX(0, MIN(right, self.bounds.size.width));
|
||||||
top = MAX(0, MIN(top, self.bounds.size.height));
|
top = MAX(0, MIN(top, self.bounds.size.height));
|
||||||
bottom = MAX(0, MIN(bottom, 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));
|
NSRect nextSelection = NSMakeRect(MIN(left, right), MIN(top, bottom), fabs(right - left), fabs(bottom - top));
|
||||||
|
[self preserveAnnotationScreenPositionsFromOrigin:_selection.origin toOrigin:nextSelection.origin];
|
||||||
|
_selection = nextSelection;
|
||||||
} else if (_draggingTextAnnotation && _selectedTextAnnotationIndex >= 0 && _selectedTextAnnotationIndex < (NSInteger)_annotations.count) {
|
} else if (_draggingTextAnnotation && _selectedTextAnnotationIndex >= 0 && _selectedTextAnnotationIndex < (NSInteger)_annotations.count) {
|
||||||
NSMutableDictionary *item = (NSMutableDictionary *)_annotations[(NSUInteger)_selectedTextAnnotationIndex];
|
NSMutableDictionary *item = (NSMutableDictionary *)_annotations[(NSUInteger)_selectedTextAnnotationIndex];
|
||||||
NSMutableArray *points = (NSMutableArray *)item[@"points"];
|
NSMutableArray *points = (NSMutableArray *)item[@"points"];
|
||||||
@@ -860,7 +1027,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
} else if (_annotating && _draftAnnotation != nil) {
|
} else if (_annotating && _draftAnnotation != nil) {
|
||||||
NSMutableArray *points = _draftAnnotation[@"points"];
|
NSMutableArray *points = _draftAnnotation[@"points"];
|
||||||
NSPoint local = [self localPoint:p];
|
NSPoint local = [self localPoint:p];
|
||||||
if ([_activeTool isEqualToString:@"pen"]) {
|
if ([_activeTool isEqualToString:@"pen"] || [_activeTool isEqualToString:@"mosaic-brush"]) {
|
||||||
[points addObject:[NSValue valueWithPoint:local]];
|
[points addObject:[NSValue valueWithPoint:local]];
|
||||||
} else {
|
} else {
|
||||||
if (points.count == 1) {
|
if (points.count == 1) {
|
||||||
@@ -921,14 +1088,18 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[_clipboardButton setHidden:!visible];
|
[_clipboardButton setHidden:!visible];
|
||||||
[_saveButton setHidden:!visible];
|
[_saveButton setHidden:!visible];
|
||||||
[_saveRemoteButton setHidden:!visible];
|
[_saveRemoteButton setHidden:!visible];
|
||||||
|
[_ftpButton setHidden:!visible];
|
||||||
[_ocrButton setHidden:!visible];
|
[_ocrButton setHidden:!visible];
|
||||||
[_summaryButton setHidden:!visible];
|
[_summaryButton setHidden:!visible];
|
||||||
[_uploadButton setHidden:!visible];
|
[_uploadButton setHidden:!visible];
|
||||||
[_actionToolbarBg setHidden:!visible];
|
[_actionToolbarBg setHidden:!visible];
|
||||||
[_penButton setHidden:!visible];
|
[_penButton setHidden:!visible];
|
||||||
|
[_lineButton setHidden:!visible];
|
||||||
|
[_arrowButton setHidden:!visible];
|
||||||
[_rectButton setHidden:!visible];
|
[_rectButton setHidden:!visible];
|
||||||
[_ellipseButton setHidden:!visible];
|
[_ellipseButton setHidden:!visible];
|
||||||
[_textButton setHidden:!visible];
|
[_textButton setHidden:!visible];
|
||||||
|
[_mosaicButton setHidden:!visible];
|
||||||
[_undoButton setHidden:!visible];
|
[_undoButton setHidden:!visible];
|
||||||
[_toolSettingsView setHidden:!visible || _activeTool == nil];
|
[_toolSettingsView setHidden:!visible || _activeTool == nil];
|
||||||
[_sizeLabel setHidden:!visible];
|
[_sizeLabel setHidden:!visible];
|
||||||
@@ -941,12 +1112,12 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[_sizeLabel setStringValue:[NSString stringWithFormat:@"%.0f × %.0f", _selection.size.width, _selection.size.height]];
|
[_sizeLabel setStringValue:[NSString stringWithFormat:@"%.0f × %.0f", _selection.size.width, _selection.size.height]];
|
||||||
[_sizeLabel setFrame:NSMakeRect(_selection.origin.x, MAX(0, _selection.origin.y - 26), 110, 22)];
|
[_sizeLabel setFrame:NSMakeRect(_selection.origin.x, MAX(0, _selection.origin.y - 26), 110, 22)];
|
||||||
|
|
||||||
// Action toolbar layout — 7 icon buttons, each 28x28, separated by 8px,
|
// Action toolbar layout — 8 icon buttons, each 28x28, separated by 8px,
|
||||||
// with 4px outer padding. Total = 7*28 + 6*8 + 2*4 = 252px wide.
|
// with 4px outer padding. Total = 8*28 + 7*8 + 2*4 = 288px wide.
|
||||||
CGFloat actionBtnSize = 28;
|
CGFloat actionBtnSize = 28;
|
||||||
CGFloat actionGap = 8;
|
CGFloat actionGap = 8;
|
||||||
CGFloat actionPad = 4;
|
CGFloat actionPad = 4;
|
||||||
NSInteger actionCount = 7;
|
NSInteger actionCount = 8;
|
||||||
CGFloat toolbarW = actionPad * 2 + actionBtnSize * actionCount + actionGap * (actionCount - 1);
|
CGFloat toolbarW = actionPad * 2 + actionBtnSize * actionCount + actionGap * (actionCount - 1);
|
||||||
CGFloat toolbarH = 40;
|
CGFloat toolbarH = 40;
|
||||||
CGFloat x = _selection.origin.x + _selection.size.width - toolbarW;
|
CGFloat x = _selection.origin.x + _selection.size.width - toolbarW;
|
||||||
@@ -964,26 +1135,32 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[_clipboardButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 1, btnY, actionBtnSize, actionBtnSize)];
|
[_clipboardButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 1, btnY, actionBtnSize, actionBtnSize)];
|
||||||
[_saveButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 2, btnY, actionBtnSize, actionBtnSize)];
|
[_saveButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 2, btnY, actionBtnSize, actionBtnSize)];
|
||||||
[_saveRemoteButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 3, btnY, actionBtnSize, actionBtnSize)];
|
[_saveRemoteButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 3, btnY, actionBtnSize, actionBtnSize)];
|
||||||
[_ocrButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 4, btnY, actionBtnSize, actionBtnSize)];
|
[_ftpButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 4, btnY, actionBtnSize, actionBtnSize)];
|
||||||
[_summaryButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 5, btnY, actionBtnSize, actionBtnSize)];
|
[_ocrButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 5, btnY, actionBtnSize, actionBtnSize)];
|
||||||
[_uploadButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 6, btnY, actionBtnSize, actionBtnSize)];
|
[_summaryButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 6, btnY, actionBtnSize, actionBtnSize)];
|
||||||
|
[_uploadButton setFrame:NSMakeRect(baseX + (actionBtnSize + actionGap) * 7, btnY, actionBtnSize, actionBtnSize)];
|
||||||
|
|
||||||
// Mark toolbar sits to the LEFT of the action toolbar (same row) with an
|
// 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.
|
// 8px gap between the two groups, so they never overlap on tiny selections.
|
||||||
CGFloat markW = 178;
|
CGFloat markW = 280;
|
||||||
CGFloat markGap = 8;
|
CGFloat markGap = 8;
|
||||||
CGFloat markX = MAX(0, x - markGap - markW);
|
CGFloat markX = MAX(0, x - markGap - markW);
|
||||||
[_penButton setFrame:NSMakeRect(markX + 4, y + 4, 28, 28)];
|
[_penButton setFrame:NSMakeRect(markX + 4, y + 4, 28, 28)];
|
||||||
[_rectButton setFrame:NSMakeRect(markX + 38, y + 4, 28, 28)];
|
[_lineButton setFrame:NSMakeRect(markX + 38, y + 4, 28, 28)];
|
||||||
[_ellipseButton setFrame:NSMakeRect(markX + 72, y + 4, 28, 28)];
|
[_arrowButton setFrame:NSMakeRect(markX + 72, y + 4, 28, 28)];
|
||||||
[_textButton setFrame:NSMakeRect(markX + 106, y + 4, 28, 28)];
|
[_rectButton setFrame:NSMakeRect(markX + 106, y + 4, 28, 28)];
|
||||||
[_undoButton setFrame:NSMakeRect(markX + 144, y + 4, 28, 28)];
|
[_ellipseButton setFrame:NSMakeRect(markX + 140, y + 4, 28, 28)];
|
||||||
|
[_textButton setFrame:NSMakeRect(markX + 174, y + 4, 28, 28)];
|
||||||
|
[_mosaicButton setFrame:NSMakeRect(markX + 208, y + 4, 28, 28)];
|
||||||
|
[_undoButton setFrame:NSMakeRect(markX + 246, y + 4, 28, 28)];
|
||||||
[_undoButton setEnabled:YES];
|
[_undoButton setEnabled:YES];
|
||||||
[[_undoButton layer] setOpacity:_annotations.count > 0 ? 1.0 : 0.35];
|
[[_undoButton layer] setOpacity:_annotations.count > 0 ? 1.0 : 0.35];
|
||||||
|
|
||||||
if (_activeTool != nil) {
|
if (_activeTool != nil) {
|
||||||
BOOL isText = [_activeTool isEqualToString:@"text"];
|
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 settingsH = 58;
|
||||||
CGFloat settingsX = MAX(8, MIN(markX, self.bounds.size.width - settingsW - 8));
|
CGFloat settingsX = MAX(8, MIN(markX, self.bounds.size.width - settingsW - 8));
|
||||||
CGFloat settingsY = y + toolbarH + 4;
|
CGFloat settingsY = y + toolbarH + 4;
|
||||||
@@ -991,9 +1168,12 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
settingsY = y - settingsH - 8;
|
settingsY = y - settingsH - 8;
|
||||||
}
|
}
|
||||||
CGFloat activeCenter = markX + 18;
|
CGFloat activeCenter = markX + 18;
|
||||||
if ([_activeTool isEqualToString:@"rect"]) activeCenter = markX + 52;
|
if ([_activeTool isEqualToString:@"line"]) activeCenter = markX + 52;
|
||||||
if ([_activeTool isEqualToString:@"ellipse"]) activeCenter = markX + 86;
|
if ([_activeTool isEqualToString:@"arrow"]) activeCenter = markX + 86;
|
||||||
if ([_activeTool isEqualToString:@"text"]) activeCenter = markX + 120;
|
if ([_activeTool isEqualToString:@"rect"]) activeCenter = markX + 120;
|
||||||
|
if ([_activeTool isEqualToString:@"ellipse"]) activeCenter = markX + 154;
|
||||||
|
if ([_activeTool isEqualToString:@"text"]) activeCenter = markX + 188;
|
||||||
|
if (isMosaic) activeCenter = markX + 222;
|
||||||
[_toolSettingsView setFrame:NSMakeRect(settingsX, settingsY, settingsW, settingsH)];
|
[_toolSettingsView setFrame:NSMakeRect(settingsX, settingsY, settingsW, settingsH)];
|
||||||
[_toolSettingsView setArrowX:MAX(18, MIN(activeCenter - settingsX, settingsW - 18))];
|
[_toolSettingsView setArrowX:MAX(18, MIN(activeCenter - settingsX, settingsW - 18))];
|
||||||
[_toolSettingsView setNeedsDisplay:YES];
|
[_toolSettingsView setNeedsDisplay:YES];
|
||||||
@@ -1001,21 +1181,34 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
CGFloat contentY = 18;
|
CGFloat contentY = 18;
|
||||||
CGFloat xCursor = 14;
|
CGFloat xCursor = 14;
|
||||||
for (NSButton *button in _strokeSettingButtons) {
|
for (NSButton *button in _strokeSettingButtons) {
|
||||||
[button setHidden:isText];
|
[button setHidden:isText || isMosaic];
|
||||||
[button setFrame:NSMakeRect(xCursor, contentY, 32, 32)];
|
[button setFrame:NSMakeRect(xCursor, contentY, 32, 32)];
|
||||||
xCursor += 42;
|
xCursor += 42;
|
||||||
}
|
}
|
||||||
xCursor = 14;
|
xCursor = 14;
|
||||||
for (NSButton *button in _fontSettingButtons) {
|
for (NSButton *button in _fontSettingButtons) {
|
||||||
[button setHidden:!isText];
|
[button setHidden:!isText || isMosaic];
|
||||||
[button setFrame:NSMakeRect(xCursor, contentY, 40, 32)];
|
[button setFrame:NSMakeRect(xCursor, contentY, 40, 32)];
|
||||||
xCursor += 48;
|
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 groupW = isText ? (4 * 40 + 3 * 8) : (3 * 32 + 2 * 10);
|
||||||
CGFloat dividerX = 14 + groupW + 12;
|
CGFloat dividerX = 14 + groupW + 12;
|
||||||
|
[_settingsDivider setHidden:isMosaic && !mosaicBrush];
|
||||||
|
if (isMosaic) dividerX = 102;
|
||||||
[_settingsDivider setFrame:NSMakeRect(dividerX, contentY + 3, 1, 26)];
|
[_settingsDivider setFrame:NSMakeRect(dividerX, contentY + 3, 1, 26)];
|
||||||
CGFloat colorX = dividerX + 18;
|
CGFloat colorX = dividerX + 18;
|
||||||
for (NSButton *button in _colorSettingButtons) {
|
for (NSButton *button in _colorSettingButtons) {
|
||||||
|
[button setHidden:isMosaic];
|
||||||
[button setFrame:NSMakeRect(colorX, contentY + 5, 22, 22)];
|
[button setFrame:NSMakeRect(colorX, contentY + 5, 22, 22)];
|
||||||
colorX += 34;
|
colorX += 34;
|
||||||
}
|
}
|
||||||
@@ -1024,7 +1217,7 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
}
|
}
|
||||||
|
|
||||||
- (void)updateToolButtonStates {
|
- (void)updateToolButtonStates {
|
||||||
NSDictionary *buttons = @{@"pen": _penButton, @"rect": _rectButton, @"ellipse": _ellipseButton, @"text": _textButton};
|
NSDictionary *buttons = @{@"pen": _penButton, @"line": _lineButton, @"arrow": _arrowButton, @"rect": _rectButton, @"ellipse": _ellipseButton, @"text": _textButton};
|
||||||
for (NSString *tool in buttons) {
|
for (NSString *tool in buttons) {
|
||||||
NSButton *button = buttons[tool];
|
NSButton *button = buttons[tool];
|
||||||
NSColor *bg = [tool isEqualToString:_activeTool]
|
NSColor *bg = [tool isEqualToString:_activeTool]
|
||||||
@@ -1032,6 +1225,8 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
: [NSColor clearColor];
|
: [NSColor clearColor];
|
||||||
[[button layer] setBackgroundColor:[bg CGColor]];
|
[[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];
|
[self updateToolSettingsStates];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1059,6 +1254,23 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[button setAttributedTitle:title];
|
[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];
|
NSString *activeHex = [self hexForColor:_activeColor];
|
||||||
NSArray *colors = objc_getAssociatedObject(_toolSettingsView, "snapgoColors");
|
NSArray *colors = objc_getAssociatedObject(_toolSettingsView, "snapgoColors");
|
||||||
@@ -1076,9 +1288,12 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[self syncControls];
|
[self syncControls];
|
||||||
}
|
}
|
||||||
- (void)selectPen { [self selectTool:@"pen"]; }
|
- (void)selectPen { [self selectTool:@"pen"]; }
|
||||||
|
- (void)selectLine { [self selectTool:@"line"]; }
|
||||||
|
- (void)selectArrow { [self selectTool:@"arrow"]; }
|
||||||
- (void)selectRect { [self selectTool:@"rect"]; }
|
- (void)selectRect { [self selectTool:@"rect"]; }
|
||||||
- (void)selectEllipse { [self selectTool:@"ellipse"]; }
|
- (void)selectEllipse { [self selectTool:@"ellipse"]; }
|
||||||
- (void)selectText { [self selectTool:@"text"]; }
|
- (void)selectText { [self selectTool:@"text"]; }
|
||||||
|
- (void)selectMosaic { [self selectTool:[_mosaicMode isEqualToString:@"brush"] ? @"mosaic-brush" : @"mosaic-rect"]; }
|
||||||
- (void)undoAnnotation {
|
- (void)undoAnnotation {
|
||||||
if (_annotations.count == 0 && _textEditor == nil) {
|
if (_annotations.count == 0 && _textEditor == nil) {
|
||||||
return;
|
return;
|
||||||
@@ -1217,6 +1432,16 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
[self updateToolSettingsStates];
|
[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 {
|
- (void)selectFontSize:(NSButton *)sender {
|
||||||
_activeFontSize = MAX(8.0, (CGFloat)sender.tag);
|
_activeFontSize = MAX(8.0, (CGFloat)sender.tag);
|
||||||
if (_textEditor != nil) {
|
if (_textEditor != nil) {
|
||||||
@@ -1351,6 +1576,17 @@ static id nativeOverlayKeyMonitor = nil;
|
|||||||
nativeOverlaySaveRemote((int)llround(r.origin.x), (int)llround(r.origin.y), (int)llround(r.size.width), (int)llround(r.size.height), [json UTF8String]);
|
nativeOverlaySaveRemote((int)llround(r.origin.x), (int)llround(r.origin.y), (int)llround(r.size.width), (int)llround(r.size.height), [json UTF8String]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// `uploadFTPSelection` dispatches the dedicated FTP/SFTP upload action.
|
||||||
|
- (void)uploadFTPSelection {
|
||||||
|
if (!_hasSelection) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
NSRect r = [self globalRectForSelection:_selection];
|
||||||
|
NSString *json = [self annotationsJSON];
|
||||||
|
[self closeOverlayWindow];
|
||||||
|
nativeOverlayUploadFTP((int)llround(r.origin.x), (int)llround(r.origin.y), (int)llround(r.size.width), (int)llround(r.size.height), [json UTF8String]);
|
||||||
|
}
|
||||||
|
|
||||||
// `ocrSelection` sends the screenshot to the configured OCR provider and
|
// `ocrSelection` sends the screenshot to the configured OCR provider and
|
||||||
// copies the extracted text.
|
// copies the extracted text.
|
||||||
- (void)ocrSelection {
|
- (void)ocrSelection {
|
||||||
@@ -1399,6 +1635,60 @@ static NSScreen *snipScreenContainingCursor(void) {
|
|||||||
return [[NSScreen screens] firstObject];
|
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) {
|
static void snipShowNativeOverlay(int width, int height) {
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
NSScreen *screen = snipScreenContainingCursor();
|
NSScreen *screen = snipScreenContainingCursor();
|
||||||
@@ -1408,6 +1698,7 @@ static void snipShowNativeOverlay(int width, int height) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
NSRect frame = [screen frame];
|
NSRect frame = [screen frame];
|
||||||
|
NSImage *mosaicPreview = snipMosaicPreviewImage(screen);
|
||||||
[NSApp activateIgnoringOtherApps:YES];
|
[NSApp activateIgnoringOtherApps:YES];
|
||||||
|
|
||||||
nativeOverlayWindow = [[SnipNativeOverlayPanel alloc]
|
nativeOverlayWindow = [[SnipNativeOverlayPanel alloc]
|
||||||
@@ -1428,6 +1719,7 @@ static void snipShowNativeOverlay(int width, int height) {
|
|||||||
|
|
||||||
SnipNativeOverlayView *view = [[SnipNativeOverlayView alloc]
|
SnipNativeOverlayView *view = [[SnipNativeOverlayView alloc]
|
||||||
initWithFrame:NSMakeRect(0, 0, frame.size.width, frame.size.height)];
|
initWithFrame:NSMakeRect(0, 0, frame.size.width, frame.size.height)];
|
||||||
|
[view setMosaicPreviewImage:mosaicPreview];
|
||||||
[nativeOverlayWindow setContentView:view];
|
[nativeOverlayWindow setContentView:view];
|
||||||
[nativeOverlayWindow makeKeyAndOrderFront:nil];
|
[nativeOverlayWindow makeKeyAndOrderFront:nil];
|
||||||
[nativeOverlayWindow makeFirstResponder:view];
|
[nativeOverlayWindow makeFirstResponder:view];
|
||||||
|
|||||||
@@ -4,3 +4,7 @@ dist-ssr
|
|||||||
.vite
|
.vite
|
||||||
.DS_Store
|
.DS_Store
|
||||||
*.log
|
*.log
|
||||||
|
|
||||||
|
tsconfig.node.tsbuildinfo
|
||||||
|
tsconfig.app.tsbuildinfo
|
||||||
|
upload_koodo.py
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/png" href="%BASE_URL%favicon.png" />
|
<link rel="icon" type="image/png" sizes="64x64" href="%BASE_URL%favicon.png" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<meta
|
<meta
|
||||||
name="description"
|
name="description"
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 8.1 KiB |
+100
-24
@@ -1,5 +1,6 @@
|
|||||||
import { useMemo, useRef, useState } from "react";
|
import { useMemo, useRef, useState, type AnimationEvent } from "react";
|
||||||
import logoUrl from "./assets/logo-universal.png";
|
import logoUrl from "./assets/logo-universal.png";
|
||||||
|
import ShowcaseVisual from "./ShowcaseVisual";
|
||||||
|
|
||||||
const slides = [
|
const slides = [
|
||||||
{
|
{
|
||||||
@@ -32,6 +33,13 @@ const slides = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
|
type SlideDirection = -1 | 1;
|
||||||
|
|
||||||
|
type SlideTransition = {
|
||||||
|
from: number;
|
||||||
|
direction: SlideDirection;
|
||||||
|
};
|
||||||
|
|
||||||
function Logo() {
|
function Logo() {
|
||||||
return (
|
return (
|
||||||
<div className="brand" aria-label="SnapGo logo">
|
<div className="brand" aria-label="SnapGo logo">
|
||||||
@@ -48,9 +56,40 @@ function Logo() {
|
|||||||
|
|
||||||
export default function App() {
|
export default function App() {
|
||||||
const [activeSlide, setActiveSlide] = useState(0);
|
const [activeSlide, setActiveSlide] = useState(0);
|
||||||
|
const [slideTransition, setSlideTransition] = useState<SlideTransition | null>(null);
|
||||||
const dragStartX = useRef<number | null>(null);
|
const dragStartX = useRef<number | null>(null);
|
||||||
const active = slides[activeSlide];
|
const active = slides[activeSlide];
|
||||||
|
|
||||||
|
function getTransitionClass(role: "entering" | "exiting") {
|
||||||
|
if (!slideTransition) {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const edge = slideTransition.direction === 1 ? "right" : "left";
|
||||||
|
return `is-${role}-from-${edge}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function finishSlideTransition(event: AnimationEvent<HTMLElement>) {
|
||||||
|
if (event.target === event.currentTarget) {
|
||||||
|
setSlideTransition(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectSlide(nextSlide: number, direction: SlideDirection) {
|
||||||
|
if (slideTransition || nextSlide === activeSlide) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSlideTransition({ from: activeSlide, direction });
|
||||||
|
setActiveSlide(nextSlide);
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectDotSlide(nextSlide: number) {
|
||||||
|
const forwardDistance = (nextSlide - activeSlide + slides.length) % slides.length;
|
||||||
|
const backwardDistance = (activeSlide - nextSlide + slides.length) % slides.length;
|
||||||
|
selectSlide(nextSlide, forwardDistance <= backwardDistance ? 1 : -1);
|
||||||
|
}
|
||||||
|
|
||||||
const accentDots = useMemo(
|
const accentDots = useMemo(
|
||||||
() =>
|
() =>
|
||||||
slides.map((slide, index) => (
|
slides.map((slide, index) => (
|
||||||
@@ -59,14 +98,15 @@ export default function App() {
|
|||||||
className={`dot ${index === activeSlide ? "is-active" : ""}`}
|
className={`dot ${index === activeSlide ? "is-active" : ""}`}
|
||||||
type="button"
|
type="button"
|
||||||
aria-label={`查看 ${slide.title}`}
|
aria-label={`查看 ${slide.title}`}
|
||||||
onClick={() => setActiveSlide(index)}
|
onClick={() => selectDotSlide(index)}
|
||||||
/>
|
/>
|
||||||
)),
|
)),
|
||||||
[activeSlide],
|
[activeSlide, slideTransition],
|
||||||
);
|
);
|
||||||
|
|
||||||
function moveSlide(direction: -1 | 1) {
|
function moveSlide(direction: SlideDirection) {
|
||||||
setActiveSlide((current) => (current + direction + slides.length) % slides.length);
|
const nextSlide = (activeSlide + direction + slides.length) % slides.length;
|
||||||
|
selectSlide(nextSlide, direction);
|
||||||
}
|
}
|
||||||
|
|
||||||
function handlePointerEnd(clientX: number) {
|
function handlePointerEnd(clientX: number) {
|
||||||
@@ -136,6 +176,9 @@ export default function App() {
|
|||||||
onPointerCancel={() => {
|
onPointerCancel={() => {
|
||||||
dragStartX.current = null;
|
dragStartX.current = null;
|
||||||
}}
|
}}
|
||||||
|
onPointerLeave={() => {
|
||||||
|
dragStartX.current = null;
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
<div className="window-chrome" aria-hidden="true">
|
<div className="window-chrome" aria-hidden="true">
|
||||||
<span />
|
<span />
|
||||||
@@ -144,26 +187,44 @@ export default function App() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="preview-stage">
|
<div className="preview-stage">
|
||||||
<div className="capture-frame">
|
{slideTransition && (
|
||||||
<span className="corner top-left" />
|
<div
|
||||||
<span className="corner top-right" />
|
key={`visual-${slideTransition.from}`}
|
||||||
<span className="corner bottom-left" />
|
className={`carousel-slide is-exiting ${getTransitionClass("exiting")}`}
|
||||||
<span className="corner bottom-right" />
|
aria-hidden="true"
|
||||||
<div className="preview-card floating-card card-one">
|
>
|
||||||
<span>Upload</span>
|
<ShowcaseVisual activeIndex={slideTransition.from} />
|
||||||
<strong>snapgo/2026/capture.png</strong>
|
|
||||||
</div>
|
|
||||||
<div className="preview-card floating-card card-two">
|
|
||||||
<span>Copied</span>
|
|
||||||
<strong>https://cdn.example.com/...</strong>
|
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
key={`visual-${activeSlide}`}
|
||||||
|
className={`carousel-slide ${slideTransition ? `is-entering ${getTransitionClass("entering")}` : ""}`}
|
||||||
|
onAnimationEnd={finishSlideTransition}
|
||||||
|
>
|
||||||
|
<ShowcaseVisual activeIndex={activeSlide} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="slide-panel" key={active.title}>
|
<div className="slide-panel-viewport">
|
||||||
<p>{active.eyebrow}</p>
|
{slideTransition && (
|
||||||
<h2>{active.title}</h2>
|
<div
|
||||||
<span>{active.body}</span>
|
key={`copy-${slideTransition.from}`}
|
||||||
|
className={`slide-panel is-exiting ${getTransitionClass("exiting")}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<p>{slides[slideTransition.from].eyebrow}</p>
|
||||||
|
<h2>{slides[slideTransition.from].title}</h2>
|
||||||
|
<span>{slides[slideTransition.from].body}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
key={`copy-${activeSlide}`}
|
||||||
|
className={`slide-panel ${slideTransition ? `is-entering ${getTransitionClass("entering")}` : ""}`}
|
||||||
|
>
|
||||||
|
<p>{active.eyebrow}</p>
|
||||||
|
<h2>{active.title}</h2>
|
||||||
|
<span>{active.body}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@@ -173,9 +234,24 @@ export default function App() {
|
|||||||
<path d="m12 5-5 5 5 5" />
|
<path d="m12 5-5 5 5 5" />
|
||||||
</svg>
|
</svg>
|
||||||
</button>
|
</button>
|
||||||
<div className="slide-meta" aria-live="polite">
|
<div className="slide-meta-viewport" aria-live="polite">
|
||||||
<strong>{active.metric}</strong>
|
{slideTransition && (
|
||||||
<span>{active.feature}</span>
|
<div
|
||||||
|
key={`meta-${slideTransition.from}`}
|
||||||
|
className={`slide-meta is-exiting ${getTransitionClass("exiting")}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<strong>{slides[slideTransition.from].metric}</strong>
|
||||||
|
<span>{slides[slideTransition.from].feature}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div
|
||||||
|
key={`meta-${activeSlide}`}
|
||||||
|
className={`slide-meta ${slideTransition ? `is-entering ${getTransitionClass("entering")}` : ""}`}
|
||||||
|
>
|
||||||
|
<strong>{active.metric}</strong>
|
||||||
|
<span>{active.feature}</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="dots" aria-label="轮播分页">
|
<div className="dots" aria-label="轮播分页">
|
||||||
{accentDots}
|
{accentDots}
|
||||||
|
|||||||
@@ -0,0 +1,435 @@
|
|||||||
|
import { useState, type PointerEvent } from "react";
|
||||||
|
|
||||||
|
type ShowcaseVisualProps = {
|
||||||
|
activeIndex: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type CaptureTool = "rect" | "arrow" | "pen" | "mosaic";
|
||||||
|
type OcrLanguage = "zh" | "en" | "auto";
|
||||||
|
type UploadDestination = {
|
||||||
|
id: "obs" | "ssh" | "ftp";
|
||||||
|
label: string;
|
||||||
|
detail: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const destinations: UploadDestination[] = [
|
||||||
|
{ id: "obs", label: "OBS", detail: "Bucket" },
|
||||||
|
{ id: "ssh", label: "SSH", detail: "Server" },
|
||||||
|
{ id: "ftp", label: "FTP", detail: "Remote" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const uploadRoutes: Record<UploadDestination["id"], string> = {
|
||||||
|
obs: "M 50 30 C 59 30 61 17 71 17",
|
||||||
|
ssh: "M 50 30 C 58 30 63 30 71 30",
|
||||||
|
ftp: "M 50 30 C 59 30 61 43 71 43",
|
||||||
|
};
|
||||||
|
|
||||||
|
const ocrModes: Array<{
|
||||||
|
id: OcrLanguage;
|
||||||
|
label: string;
|
||||||
|
name: string;
|
||||||
|
lines: string[];
|
||||||
|
characters: number;
|
||||||
|
confidence: string;
|
||||||
|
}> = [
|
||||||
|
{
|
||||||
|
id: "zh",
|
||||||
|
label: "中",
|
||||||
|
name: "中文",
|
||||||
|
lines: ["让每一次截图直接进入下一步。"],
|
||||||
|
characters: 15,
|
||||||
|
confidence: "99.5%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "en",
|
||||||
|
label: "EN",
|
||||||
|
name: "English",
|
||||||
|
lines: ["Capture, understand, share."],
|
||||||
|
characters: 27,
|
||||||
|
confidence: "99.1%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "auto",
|
||||||
|
label: "AUTO",
|
||||||
|
name: "中英混排",
|
||||||
|
lines: ["Capture, understand, share.", "让每一次截图直接进入下一步。"],
|
||||||
|
characters: 42,
|
||||||
|
confidence: "99.2%",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const aiModes = [
|
||||||
|
{
|
||||||
|
id: "vision",
|
||||||
|
label: "识图",
|
||||||
|
result: "检测到系统权限弹窗,截图权限尚未开启。",
|
||||||
|
score: "96%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "summary",
|
||||||
|
label: "总结",
|
||||||
|
result: "当前页面包含 3 个设置项,建议先开启屏幕录制权限。",
|
||||||
|
score: "93%",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "question",
|
||||||
|
label: "问答",
|
||||||
|
result: "前往系统设置中的隐私与安全性即可完成授权。",
|
||||||
|
score: "98%",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const captureTools: Array<{ id: CaptureTool; label: string }> = [
|
||||||
|
{ id: "rect", label: "矩形" },
|
||||||
|
{ id: "arrow", label: "箭头" },
|
||||||
|
{ id: "pen", label: "画笔" },
|
||||||
|
{ id: "mosaic", label: "马赛克" },
|
||||||
|
];
|
||||||
|
|
||||||
|
function stopSceneDrag(event: PointerEvent<HTMLElement>) {
|
||||||
|
event.stopPropagation();
|
||||||
|
}
|
||||||
|
|
||||||
|
function UploadScene() {
|
||||||
|
const [selected, setSelected] = useState<UploadDestination>(destinations[0]);
|
||||||
|
const routePath = uploadRoutes[selected.id];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`visual-scene upload-scene target-${selected.id}`}>
|
||||||
|
<div className="upload-file-card">
|
||||||
|
<div className="upload-file-preview" aria-hidden="true">
|
||||||
|
<div className="screenshot-window-bar">
|
||||||
|
<span><i /><i /><i /></span>
|
||||||
|
<b className="screenshot-address-bar" />
|
||||||
|
</div>
|
||||||
|
<div className="screenshot-window-body">
|
||||||
|
<div className="screenshot-sidebar"><i /><i /><i /><i /></div>
|
||||||
|
<div className="screenshot-main">
|
||||||
|
<span className="screenshot-heading" />
|
||||||
|
<span className="screenshot-row row-long" />
|
||||||
|
<span className="screenshot-row row-medium" />
|
||||||
|
<div className="screenshot-card-grid">
|
||||||
|
<i /><i /><i />
|
||||||
|
</div>
|
||||||
|
<div className="screenshot-copy-lines">
|
||||||
|
<i /><i /><i />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="upload-capture-frame">
|
||||||
|
<i className="upload-capture-corner corner-nw" />
|
||||||
|
<i className="upload-capture-corner corner-ne" />
|
||||||
|
<i className="upload-capture-corner corner-sw" />
|
||||||
|
<i className="upload-capture-corner corner-se" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="upload-file-copy">
|
||||||
|
<span>SCREENSHOT-1428.PNG</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<svg
|
||||||
|
className="upload-route"
|
||||||
|
viewBox="0 0 100 60"
|
||||||
|
preserveAspectRatio="none"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
key={`route-${selected.id}`}
|
||||||
|
className="upload-route-line"
|
||||||
|
d={routePath}
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
key={`shimmer-${selected.id}`}
|
||||||
|
className="upload-route-shimmer"
|
||||||
|
d={routePath}
|
||||||
|
pathLength="100"
|
||||||
|
strokeDasharray="16 84"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
<span key={`packet-${selected.id}`} className={`upload-packet packet-${selected.id}`} aria-hidden="true">
|
||||||
|
<svg viewBox="0 0 20 20">
|
||||||
|
<path d="M 5 10 H 14 M 10.5 6.5 L 14 10 L 10.5 13.5" />
|
||||||
|
</svg>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<div className="upload-destinations" role="group" aria-label="上传目标">
|
||||||
|
{destinations.map((destination) => (
|
||||||
|
<button
|
||||||
|
key={destination.id}
|
||||||
|
type="button"
|
||||||
|
className={destination.id === selected.id ? "is-selected" : ""}
|
||||||
|
aria-pressed={destination.id === selected.id}
|
||||||
|
aria-label={`选择 ${destination.label} 上传目标`}
|
||||||
|
onPointerDown={stopSceneDrag}
|
||||||
|
onClick={() => setSelected(destination)}
|
||||||
|
>
|
||||||
|
<span className="destination-status" />
|
||||||
|
<strong>{destination.label}</strong>
|
||||||
|
<small>{destination.detail}</small>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="upload-result scene-float-delayed" aria-live="polite">
|
||||||
|
<span className="result-check" aria-hidden="true">✓</span>
|
||||||
|
<div>
|
||||||
|
<small>LINK COPIED</small>
|
||||||
|
<strong>cdn.snapgo.dev/{selected.id}/...</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function IdentificationScene() {
|
||||||
|
const [mode, setMode] = useState(aiModes[0]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="visual-scene identification-scene">
|
||||||
|
<div className="ai-source-card">
|
||||||
|
<div className="mini-window-bar" aria-hidden="true">
|
||||||
|
<span />
|
||||||
|
<span />
|
||||||
|
<span />
|
||||||
|
</div>
|
||||||
|
<div className="ai-source-content">
|
||||||
|
<span className="source-sidebar" />
|
||||||
|
<div className="source-settings">
|
||||||
|
<i />
|
||||||
|
<i />
|
||||||
|
<i />
|
||||||
|
</div>
|
||||||
|
<div className="source-dialog">
|
||||||
|
<span className="dialog-icon">!</span>
|
||||||
|
<div>
|
||||||
|
<strong>Permission required</strong>
|
||||||
|
<small>Screen Recording</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span className="ai-scan-line" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ai-core" aria-hidden="true">
|
||||||
|
<span>AI</span>
|
||||||
|
<i className="ai-orbit orbit-one" />
|
||||||
|
<i className="ai-orbit orbit-two" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ai-result-card scene-float-soft" aria-live="polite">
|
||||||
|
<div className="ai-result-heading">
|
||||||
|
<span className="ai-spark" aria-hidden="true">✦</span>
|
||||||
|
<strong>SnapGo Vision</strong>
|
||||||
|
<i />
|
||||||
|
</div>
|
||||||
|
<p>{mode.result}</p>
|
||||||
|
<div className="confidence-row">
|
||||||
|
<span><i /></span>
|
||||||
|
<small>{mode.score} confidence</small>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ai-mode-switch" role="group" aria-label="AI 处理模式">
|
||||||
|
{aiModes.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
className={item.id === mode.id ? "is-selected" : ""}
|
||||||
|
aria-pressed={item.id === mode.id}
|
||||||
|
onPointerDown={stopSceneDrag}
|
||||||
|
onClick={() => setMode(item)}
|
||||||
|
>
|
||||||
|
{item.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function OcrScene() {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
const [language, setLanguage] = useState<OcrLanguage>("auto");
|
||||||
|
const activeMode = ocrModes.find((mode) => mode.id === language) ?? ocrModes[2];
|
||||||
|
|
||||||
|
function selectLanguage(mode: OcrLanguage) {
|
||||||
|
setLanguage(mode);
|
||||||
|
setCopied(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="visual-scene ocr-scene">
|
||||||
|
<div className="ocr-document">
|
||||||
|
<div className="document-header">
|
||||||
|
<span />
|
||||||
|
<div><i /><i /><i /></div>
|
||||||
|
</div>
|
||||||
|
<div className="document-copy">
|
||||||
|
<strong>Release notes</strong>
|
||||||
|
<span className="text-line line-long" />
|
||||||
|
<span className="text-line line-medium" />
|
||||||
|
<span className="text-line line-highlight"><i>Capture, understand, share.</i></span>
|
||||||
|
<span className="text-line line-long" />
|
||||||
|
<span className="text-line line-short" />
|
||||||
|
<span className="text-line line-highlight secondary"><i>让每一次截图直接进入下一步。</i></span>
|
||||||
|
</div>
|
||||||
|
<span className="ocr-scan-bar" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ocr-selection-card scene-float-delayed">
|
||||||
|
<div className="selection-heading">
|
||||||
|
<span>OCR</span>
|
||||||
|
<small>{activeMode.name}</small>
|
||||||
|
</div>
|
||||||
|
<p>
|
||||||
|
{activeMode.lines.map((line) => <span key={line}>{line}</span>)}
|
||||||
|
</p>
|
||||||
|
<div className="selection-meta">
|
||||||
|
<span>{activeMode.characters} characters</span>
|
||||||
|
<strong>{activeMode.confidence}</strong>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className={copied ? "is-copied" : ""}
|
||||||
|
aria-pressed={copied}
|
||||||
|
onPointerDown={stopSceneDrag}
|
||||||
|
onClick={() => setCopied((current) => !current)}
|
||||||
|
>
|
||||||
|
<span aria-hidden="true">{copied ? "✓" : "⌘C"}</span>
|
||||||
|
{copied ? "已复制" : "复制文本"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="ocr-language-pills" role="group" aria-label="OCR 识别语言">
|
||||||
|
{ocrModes.map((mode) => (
|
||||||
|
<button
|
||||||
|
key={mode.id}
|
||||||
|
type="button"
|
||||||
|
className={mode.id === language ? "is-selected" : ""}
|
||||||
|
aria-pressed={mode.id === language}
|
||||||
|
onPointerDown={stopSceneDrag}
|
||||||
|
onClick={() => selectLanguage(mode.id)}
|
||||||
|
>
|
||||||
|
{mode.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToolGlyph({ tool }: { tool: CaptureTool }) {
|
||||||
|
if (tool === "rect") {
|
||||||
|
return <svg viewBox="0 0 20 20" aria-hidden="true"><rect x="4" y="4" width="12" height="12" rx="2" /></svg>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tool === "arrow") {
|
||||||
|
return <svg viewBox="0 0 20 20" aria-hidden="true"><path d="M4 15 15 4M9 4h6v6" /></svg>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tool === "pen") {
|
||||||
|
return <svg viewBox="0 0 20 20" aria-hidden="true"><path d="m5 15 2.2-4.7L13.8 3.7l2.5 2.5-6.6 6.6L5 15Z" /><path d="m11.8 5.7 2.5 2.5" /></svg>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<svg viewBox="0 0 20 20" aria-hidden="true">
|
||||||
|
<rect x="3" y="3" width="5" height="5" />
|
||||||
|
<rect x="12" y="3" width="5" height="5" />
|
||||||
|
<rect x="3" y="12" width="5" height="5" />
|
||||||
|
<rect x="12" y="12" width="5" height="5" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AnnotationPreview({ tool }: { tool: CaptureTool }) {
|
||||||
|
if (tool === "arrow") {
|
||||||
|
return (
|
||||||
|
<svg className="annotation-arrow" viewBox="0 0 180 110" aria-hidden="true">
|
||||||
|
<path d="M28 84C66 78 91 56 139 31" />
|
||||||
|
<path d="m121 27 20 3-8 18" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tool === "pen") {
|
||||||
|
return (
|
||||||
|
<svg className="annotation-pen" viewBox="0 0 180 110" aria-hidden="true">
|
||||||
|
<path d="M24 76c20-42 36 25 57-6s33-33 48-4c9 18 21 13 29-7" />
|
||||||
|
</svg>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (tool === "mosaic") {
|
||||||
|
return <div className="annotation-mosaic" aria-hidden="true">{Array.from({ length: 20 }, (_, index) => <span key={index} />)}</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <div className="annotation-rect" aria-hidden="true"><span /><span /><span /><span /></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function CaptureScene() {
|
||||||
|
const [tool, setTool] = useState<CaptureTool>("rect");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="visual-scene capture-scene">
|
||||||
|
<div className="capture-canvas">
|
||||||
|
<div className="canvas-app-bar">
|
||||||
|
<span />
|
||||||
|
<strong>Project overview</strong>
|
||||||
|
<i />
|
||||||
|
</div>
|
||||||
|
<div className="canvas-layout" aria-hidden="true">
|
||||||
|
<span className="canvas-sidebar" />
|
||||||
|
<div className="canvas-content">
|
||||||
|
<i className="canvas-heading" />
|
||||||
|
<i className="canvas-line" />
|
||||||
|
<i className="canvas-line short" />
|
||||||
|
<div className="canvas-chart"><span /><span /><span /><span /><span /></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="capture-selection">
|
||||||
|
<span className="selection-size">1280 × 720</span>
|
||||||
|
<i className="selection-handle handle-nw" />
|
||||||
|
<i className="selection-handle handle-ne" />
|
||||||
|
<i className="selection-handle handle-sw" />
|
||||||
|
<i className="selection-handle handle-se" />
|
||||||
|
<AnnotationPreview tool={tool} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="capture-toolbar" role="toolbar" aria-label="截图标注工具">
|
||||||
|
{captureTools.map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
className={item.id === tool ? "is-selected" : ""}
|
||||||
|
aria-label={item.label}
|
||||||
|
aria-pressed={item.id === tool}
|
||||||
|
title={item.label}
|
||||||
|
onPointerDown={stopSceneDrag}
|
||||||
|
onClick={() => setTool(item.id)}
|
||||||
|
>
|
||||||
|
<ToolGlyph tool={item.id} />
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
<span className="toolbar-divider" />
|
||||||
|
<span className="toolbar-color" aria-hidden="true" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const scenes = [UploadScene, IdentificationScene, OcrScene, CaptureScene];
|
||||||
|
|
||||||
|
export default function ShowcaseVisual({ activeIndex }: ShowcaseVisualProps) {
|
||||||
|
const Scene = scenes[activeIndex] ?? UploadScene;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="scene-parallax" data-testid="showcase-visual">
|
||||||
|
<Scene />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+1893
-109
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user