item-atlas/apps/ios/ItemAtlas/ItemPhotos.swift

260 lines
11 KiB
Swift

import ImageIO
import PhotosUI
import SwiftUI
import UniformTypeIdentifiers
struct PhotoImage: View {
let store: InventoryStore
let item: UUID
let photo: UUID?
let thumbnail: Bool
@State private var image: UIImage?
@State private var error = false
@State private var retry = 0
var body: some View {
GeometryReader { geometry in
ZStack {
Color.atlasBlue.opacity(0.08)
if let image {
let resized = Image(uiImage: image).resizable()
if thumbnail { resized.scaledToFill().frame(width: geometry.size.width, height: geometry.size.height) }
else { resized.scaledToFit().frame(width: geometry.size.width, height: geometry.size.height) }
} else if !thumbnail, photo != nil && !error {
ProgressView()
} else if !thumbnail, error {
Button("重新加载图片") { retry += 1 }
} else {
Image(systemName: error ? "photo" : "archivebox").foregroundStyle(Color.atlasBlue)
}
}
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
.task(id: "\(photo?.uuidString ?? ""):\(retry)") {
image = nil
error = false
guard let photo else { return }
do {
let bytes = try await store.image(item: item, photo: photo, thumbnail: thumbnail)
try Task.checkCancellation()
image = UIImage(data: bytes)
error = image == nil
} catch where !Task.isCancelled { self.error = true }
catch {}
}
}
}
struct ItemPhotos: View {
let store: InventoryStore
let item: UUID
@State private var photos: [Photo] = []
@State private var picker: PhotosPickerItem?
@State private var crop: CropSource?
@State private var preview: Photo?
@State private var busy = false
@State private var error: String?
var body: some View {
Section("照片") {
if !photos.isEmpty {
ScrollView(.horizontal) {
HStack {
ForEach(photos) { photo in
Button { preview = photo } label: {
PhotoImage(store: store, item: item, photo: photo.id, thumbnail: true)
.frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9))
}
.buttonStyle(.plain)
.accessibilityLabel("查看照片")
}
}
}
.scrollIndicators(.hidden)
} else { Text("暂无照片").foregroundStyle(.secondary) }
if store.canWrite && photos.count < 6 {
PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) {
Label("添加照片", systemImage: "photo.badge.plus")
}.disabled(busy)
}
if busy { ProgressView() }
if let error { Text(error).foregroundStyle(.red); Button("刷新照片") { Task { await load() } } }
}
.task(id: store.revision) { await load() }
.task(id: picker) {
guard let picker else { return }
busy = true
defer { busy = false; self.picker = nil }
do {
guard let source = try await picker.loadTransferable(type: CropSource.self) else {
throw AtlasError("这张图片无法读取,请重新选择。")
}
try Task.checkCancellation()
error = nil
crop = source
} catch { self.error = error.localizedDescription }
}
.sheet(item: $crop) { source in
CropEditor(source: source) { image in
try await store.upload(image, item: item)
}
}
.sheet(item: $preview) { photo in
PhotoPreview(store: store, item: item, photo: photo)
}
}
private func load() async {
do { photos = try await store.get(store.itemPath(item) + "/photos"); error = nil }
catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
}
private struct CropSource: Transferable, Identifiable {
let id = UUID()
let image: CGImage
static var transferRepresentation: some TransferRepresentation {
FileRepresentation(importedContentType: .image) { source in
let size = try source.file.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0
guard size > 0, size <= 30 * 1024 * 1024 else { throw AtlasError("请选择 30 MiB 以内的照片。") }
guard let imageSource = CGImageSourceCreateWithURL(source.file as CFURL, nil),
let image = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceThumbnailMaxPixelSize: 2400
] as CFDictionary) else { throw AtlasError("这张图片无法打开,请重新选择。") }
return CropSource(image: image)
}
}
}
private struct CropEditor: View {
let source: CropSource
let save: (Data) async throws -> Void
@Environment(\.dismiss) private var dismiss
@State private var zoom: Double = 1
@State private var offset = CGSize.zero
@GestureState private var drag = CGSize.zero
@State private var busy = false
@State private var error: String?
@State private var side: CGFloat = 1
var body: some View {
NavigationStack {
VStack(spacing: 20) {
GeometryReader { geometry in
let side = min(geometry.size.width, geometry.size.height)
let bounds = displayedSize(side: side)
let current = clamp(CGSize(width: offset.width + drag.width, height: offset.height + drag.height), to: bounds, side: side)
Image(uiImage: UIImage(cgImage: source.image)).resizable()
.frame(width: bounds.width, height: bounds.height)
.offset(current)
.frame(width: side, height: side)
.clipped()
.overlay { Rectangle().strokeBorder(.white.opacity(0.7), lineWidth: 1) }
.contentShape(Rectangle())
.gesture(DragGesture().updating($drag) { value, state, _ in state = value.translation }
.onEnded { value in
offset = clamp(CGSize(width: offset.width + value.translation.width,
height: offset.height + value.translation.height), to: bounds, side: side)
})
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onChange(of: side, initial: true) { _, value in self.side = value }
}
Text("拖动图片调整裁剪位置").font(.footnote).foregroundStyle(.secondary)
Slider(value: $zoom, in: 1...4) { Text("放大图片") }
.onChange(of: zoom) { _, _ in offset = clamp(offset, to: displayedSize(side: side), side: side) }
if busy { ProgressView("上传中") }
if let error { Text(error).foregroundStyle(.red).font(.footnote) }
}
.padding()
.navigationTitle("裁剪照片")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("取消") { dismiss() }.disabled(busy) }
ToolbarItem(placement: .confirmationAction) {
Button("上传") { Task { await upload() } }.disabled(busy || side <= 1)
}
}
}
.interactiveDismissDisabled(busy)
}
private func displayedSize(side: CGFloat) -> CGSize {
let factor = side * zoom / CGFloat(min(source.image.width, source.image.height))
return CGSize(width: CGFloat(source.image.width) * factor, height: CGFloat(source.image.height) * factor)
}
private func clamp(_ point: CGSize, to bounds: CGSize, side: CGFloat) -> CGSize {
let dx = max(0, (bounds.width - side) / 2), dy = max(0, (bounds.height - side) / 2)
return CGSize(width: min(dx, max(-dx, point.width)), height: min(dy, max(-dy, point.height)))
}
private func upload() async {
busy = true
defer { busy = false }
do {
let bounds = displayedSize(side: side)
let current = clamp(offset, to: bounds, side: side)
let factor = CGFloat(source.image.width) / bounds.width
let rect = CGRect(x: ((bounds.width - side) / 2 - current.width) * factor,
y: ((bounds.height - side) / 2 - current.height) * factor,
width: side * factor, height: side * factor).integral
guard let cropped = source.image.cropping(to: rect) else { throw AtlasError("裁剪失败,请重新选择。") }
let length = min(1600, min(cropped.width, cropped.height))
let dimension = CGSize(width: length, height: length)
let settings = UIGraphicsImageRendererFormat()
settings.scale = 1
settings.opaque = true
let jpeg = UIGraphicsImageRenderer(size: dimension, format: settings).jpegData(withCompressionQuality: 0.83) { _ in
UIImage(cgImage: cropped).draw(in: CGRect(origin: .zero, size: dimension))
}
try await save(jpeg)
dismiss()
} catch { self.error = error.localizedDescription }
}
}
private struct PhotoPreview: View {
let store: InventoryStore
let item: UUID
let photo: Photo
@Environment(\.dismiss) private var dismiss
@State private var confirm = false
@State private var busy = false
@State private var error: String?
var body: some View {
NavigationStack {
VStack {
PhotoImage(store: store, item: item, photo: photo.id, thumbnail: false)
if let error { Text(error).foregroundStyle(.red) }
}
.navigationTitle("物品照片")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
ToolbarItem(placement: .cancellationAction) { Button("关闭") { dismiss() }.disabled(busy) }
if store.canWrite {
ToolbarItem(placement: .destructiveAction) {
Button("删除", role: .destructive) { confirm = true }.disabled(busy)
}
}
}
.confirmationDialog("删除这张照片?", isPresented: $confirm, titleVisibility: .visible) {
Button("删除照片", role: .destructive) { Task { await delete() } }
}
}
.interactiveDismissDisabled(busy)
}
private func delete() async {
busy = true
defer { busy = false }
do { try await store.delete(store.itemPath(item) + "/photos/\(photo.id)"); dismiss() }
catch { self.error = error.localizedDescription }
}
}