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

389 lines
16 KiB
Swift

import AVFoundation
import ImageIO
import PhotosUI
import SwiftUI
import UniformTypeIdentifiers
struct PhotoImage: View {
let store: InventoryStore
let target: PhotoTarget
let photo: UUID?
let thumbnail: Bool
var placeholderSymbol = "shippingbox.fill"
var placeholderTint: Color = .teal
@State private var image: UIImage?
@State private var displayed: UUID?
@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, displayed == photo {
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" : placeholderSymbol)
.foregroundStyle(error ? Color.secondary : placeholderTint)
}
}
.frame(width: geometry.size.width, height: geometry.size.height)
.clipped()
}
.task(id: "\(photo?.uuidString ?? ""):\(retry)") {
error = false
guard let photo else { image = nil; displayed = nil; return }
if displayed != photo, thumbnail,
let bytes = store.account.cachedPreview(store.imagePath(target: target, photo: photo, thumbnail: true)) {
image = UIImage(data: bytes)
displayed = photo
}
do {
let bytes = try await store.image(target: target, photo: photo, thumbnail: thumbnail, refresh: retry > 0)
try Task.checkCancellation()
image = UIImage(data: bytes)
displayed = photo
error = image == nil
} catch is CancellationError {
} catch where !Task.isCancelled {
if (error as? AtlasError)?.resourceUnavailable == true { image = nil }
self.error = true
}
catch {}
}
}
}
struct PhotoGallery: View {
let store: InventoryStore
let target: PhotoTarget
let embedded: Bool
@State private var photos: [Photo]?
@State private var picker: PhotosPickerItem?
@State private var crop: CropSource?
@State private var cameraCrop: CropSource?
@State private var showingCamera = false
@State private var preview: Photo?
@State private var busy = false
@State private var error: String?
init(store: InventoryStore, target: PhotoTarget, embedded: Bool = false) {
self.store = store
self.target = target
self.embedded = embedded
_photos = State(initialValue: store.account.cached(store.root + target.path))
}
var body: some View {
if embedded { gallery }
else { Section(target.title) { gallery } }
}
private var gallery: some View {
VStack(alignment: .leading, spacing: embedded ? 10 : 14) {
if embedded { Text("位置照片").font(.subheadline.weight(.semibold)) }
if let photos, !photos.isEmpty {
ScrollView(.horizontal) {
HStack {
ForEach(photos) { photo in
Button { preview = photo } label: {
PhotoImage(store: store, target: target, photo: photo.id, thumbnail: true)
.frame(width: 74, height: 74).clipShape(.rect(cornerRadius: 9))
}
.buttonStyle(.plain)
.accessibilityLabel("查看照片")
}
}
}
.scrollIndicators(.hidden)
} else if photos != nil { Text("暂无照片").foregroundStyle(.secondary) }
if store.canWrite && (photos?.count ?? 0) < 6 {
HStack(spacing: 20) {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
Button { Task { await openCamera() } } label: {
Label("拍照", systemImage: "camera")
}
.buttonStyle(.borderless)
}
PhotosPicker(selection: $picker, matching: .images, preferredItemEncoding: .current) {
Label("从相册选", systemImage: "photo.badge.plus")
}
.buttonStyle(.borderless)
}
.disabled(busy)
}
if busy { ProgressView() }
if let error { Text(error).foregroundStyle(.red).font(.footnote) }
if error != nil {
Button("刷新照片") { Task { await load(refresh: true) } }.buttonStyle(.borderless)
}
}
.padding(.vertical, 4)
.task(id: store.revision) { await load() }
.task(id: picker) {
guard let selection = picker else { return }
busy = true
defer {
if picker == selection {
busy = false
picker = nil
}
}
do {
guard let source = try await selection.loadTransferable(type: CropSource.self) else {
throw AtlasError("这张图片无法读取,请重新选择。")
}
try Task.checkCancellation()
error = nil
crop = source
} catch where !Task.isCancelled { self.error = error.localizedDescription }
catch {}
}
.fullScreenCover(isPresented: $showingCamera, onDismiss: {
crop = cameraCrop
cameraCrop = nil
}) {
CameraPicker { image in
if let image {
cameraCrop = CropSource.cameraImage(image)
if cameraCrop == nil { error = "照片无法读取,请重新拍摄。" }
}
showingCamera = false
}
.ignoresSafeArea()
}
.sheet(item: $crop) { source in
CropEditor(source: source) { image in
try await store.upload(image, target: target, idempotencyKey: source.id)
}
}
.sheet(item: $preview) { photo in
PhotoPreview(store: store, target: target, photo: photo)
}
}
private func openCamera() async {
guard !busy, UIImagePickerController.isSourceTypeAvailable(.camera) else { return }
busy = true
defer { busy = false }
guard await AVCaptureDevice.requestAccess(for: .video) else {
error = "相机权限未开启。可以在系统设置中开启,或从相册选图。"
return
}
error = nil
showingCamera = true
}
private func load(refresh: Bool = false) async {
do {
let updated: [Photo] = try await store.account.read(store.root + target.path, refresh: refresh)
try Task.checkCancellation()
photos = updated
error = nil
} catch is CancellationError {
} catch where !Task.isCancelled {
if (error as? AtlasError)?.resourceUnavailable == true { photos = nil }
self.error = error.localizedDescription
}
catch {}
}
}
private struct CameraPicker: UIViewControllerRepresentable {
let complete: (UIImage?) -> Void
func makeCoordinator() -> Coordinator { Coordinator(complete: complete) }
func makeUIViewController(context: Context) -> UIImagePickerController {
let camera = UIImagePickerController()
camera.sourceType = .camera
camera.cameraCaptureMode = .photo
camera.delegate = context.coordinator
return camera
}
func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}
final class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
let complete: (UIImage?) -> Void
init(complete: @escaping (UIImage?) -> Void) { self.complete = complete }
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { complete(nil) }
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
complete(info[.originalImage] as? UIImage)
}
}
}
struct CropSource: Transferable, Identifiable {
let id = UUID()
let image: CGImage
@MainActor
static func cameraImage(_ photo: UIImage) -> CropSource? {
let longest = max(photo.size.width, photo.size.height)
guard longest.isFinite, longest > 0 else { return nil }
let factor = min(1, 2400 / longest)
let size = CGSize(width: photo.size.width * factor, height: photo.size.height * factor)
guard size.width > 0, size.height > 0 else { return nil }
let format = UIGraphicsImageRendererFormat()
format.scale = 1
format.opaque = true
let rendered = UIGraphicsImageRenderer(size: size, format: format).image { _ in
photo.draw(in: CGRect(origin: .zero, size: size))
}
return rendered.cgImage.map { CropSource(image: $0) }
}
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)
}
}
}
struct CropEditor: View {
let source: CropSource
var actionTitle = "上传"
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(actionTitle) { 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 target: PhotoTarget
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, target: target, photo: photo.id, thumbnail: false)
if let error { Text(error).foregroundStyle(.red) }
}
.navigationTitle(target.title)
.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.root + target.path + "/\(photo.id)"); dismiss() }
catch { self.error = error.localizedDescription }
}
}