SPB Git

Repository Public License

ViewerScreen.swift 13.5 KB 291 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Features/Library/ViewerScreen.swift10// Description      : Full-screen viewer: pages through the current list,11//                    zoomable stills (RAW developed, recipe applied), video12//                    playback, and the item actions (favourite, edit, info,13//                    export, save to Photos, delete).14// Module           : Features15// Repository       : https://git.spboucher.ai/orix-camera16// Project Website  : https://www.orixlab.dev17// Created          : 2026-11-2118// Last Modified    : 2026-11-2119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : Proprietary, all rights reserved (see license file)85// License File     : LICENSE86// Maintainer       : Simon-Pierre Boucher87// Technical Contact: dev@spboucher.ai88//89// =============================================================================90// END OF SP BOUCHER SOURCE HEADER91// =============================================================================9293import AVKit94import ORIXDesign95import ORIXImaging96import SwiftUI9798struct ViewerScreen: View {99    @Bindable var model: LibraryModel100    let camera: CameraModel101    let startID: UUID102103    @Environment(\.dismiss) private var dismiss104    @State private var currentID: UUID?105    @State private var showInfo = false106    @State private var showExport = false107    @State private var showEditor = false108    @State private var showAlbumPicker = false109    @State private var confirmDelete = false110    @State private var didRunDebug = false111112    private var current: MediaItem? { model.items.first { $0.id == (currentID ?? startID) } }113114    var body: some View {115        ZStack {116            Color.black.ignoresSafeArea()117            TabView(selection: Binding(get: { currentID ?? startID }, set: { currentID = $0 })) {118                ForEach(model.items, id: \.id) { item in119                    ViewerPage(item: model.snapshot(item)).tag(item.id)120                }121            }122            .tabViewStyle(.page(indexDisplayMode: .never))123            .ignoresSafeArea(edges: .horizontal)124        }125        .navigationBarBackButtonHidden()126        .toolbarBackground(.visible, for: .navigationBar, .bottomBar)127        .toolbarColorScheme(.dark, for: .navigationBar, .bottomBar)128        .toolbar(.hidden, for: .tabBar)129        .toolbar {130            ToolbarItem(placement: .topBarLeading) {131                Button { dismiss() } label: { Label("Library", systemImage: "chevron.backward") }.accessibilityIdentifier("viewer.close")132            }133            ToolbarItem(placement: .principal) {134                if let item = current {135                    VStack(spacing: 0) {136                        Text(item.createdAt.formatted(date: .abbreviated, time: .shortened)).font(.footnote.weight(.semibold))137                        Text(MediaFormat.kindTitle(item.kind)).font(.caption2).foregroundStyle(.secondary)138                    }139                    .accessibilityElement(children: .combine)140                }141            }142            ToolbarItem(placement: .topBarTrailing) {143                Menu {144                    Button { if let current { Task { await camera.copyToPhotos(current) } } } label: { Label("Save to Photos", systemImage: "square.and.arrow.down") }145                    Button { showAlbumPicker = true } label: { Label("Add to Album", systemImage: "rectangle.stack.badge.plus") }146                } label: { Label("More", systemImage: "ellipsis.circle") }147                    .accessibilityIdentifier("viewer.more")148            }149            ToolbarItemGroup(placement: .bottomBar) {150                if let item = current {151                    Button { model.toggleFavorite(item) } label: { Label(item.isFavorite ? "Remove from Favorites" : "Add to Favorites", systemImage: item.isFavorite ? "heart.fill" : "heart") }152                        .accessibilityIdentifier("viewer.favorite").accessibilityAddTraits(item.isFavorite ? .isSelected : [])153                    Spacer()154                    Button { showEditor = true } label: { Label("Edit", systemImage: "slider.horizontal.3") }155                        .disabled(item.kind.isVideo)156                        .accessibilityIdentifier("viewer.edit")157                        .accessibilityHint(item.kind.isVideo ? Text("Videos cannot be edited in this version") : Text("Opens the non-destructive editor"))158                    Spacer()159                    Button { showInfo = true } label: { Label("Info", systemImage: "info.circle") }.accessibilityIdentifier("viewer.info")160                    Spacer()161                    Button { showExport = true } label: { Label("Export", systemImage: "square.and.arrow.up") }.accessibilityIdentifier("viewer.export")162                    Spacer()163                    Button(role: .destructive) { confirmDelete = true } label: { Label("Delete", systemImage: "trash") }.accessibilityIdentifier("viewer.delete")164                }165            }166        }167        .sheet(isPresented: $showInfo) { if let current { MetadataView(item: model.snapshot(current), storage: model.library.storage) } }168        .sheet(isPresented: $showExport) {169            if let current { ExportSheet(items: [model.snapshot(current)], storage: model.library.storage, defaultStripLocation: camera.settings.stripLocationOnExport) }170        }171        .sheet(isPresented: $showAlbumPicker) { if let current { AlbumPicker(model: model, items: [current]) } }172        .fullScreenCover(isPresented: $showEditor, onDismiss: { model.reload() }) {173            if let current { EditorScreen(item: current, library: model.library) }174        }175        .confirmationDialog(Text("Delete this item?"), isPresented: $confirmDelete, titleVisibility: .visible) {176            Button("Delete from this device", role: .destructive) { deleteCurrent() }177            Button("Cancel", role: .cancel) {}178        } message: {179            Text("The file is removed from ORIX Camera on this device. Copies you saved to Photos or exported elsewhere are not affected. This cannot be undone.")180        }181        .onAppear {182            if currentID == nil { currentID = startID }183            guard !didRunDebug else { return }184            didRunDebug = true185            if DebugHooks.openEditor, current?.kind.isVideo == false { showEditor = true }186            if LibraryDebug.show == "metadata" { showInfo = true }187            if LibraryDebug.show == "export" { showExport = true }188        }189    }190191    private func deleteCurrent() {192        guard let item = current else { return }193        let index = model.items.firstIndex { $0.id == item.id } ?? 0194        model.delete([item])195        if model.items.isEmpty { dismiss() } else { currentID = model.items[min(index, model.items.count - 1)].id }196    }197}198199private struct ViewerPage: View {200    let item: ItemSnapshot201    @State private var image: UIImage?202    @State private var failed = false203    @State private var player: AVPlayer?204205    var body: some View {206        Group {207            if item.isVideo {208                if let player {209                    VideoPlayer(player: player).accessibilityLabel(Text("Video player"))210                } else {211                    ProgressView().tint(.white)212                }213            } else if let image {214                ZoomableImage(image: image)215            } else if failed {216                VStack(spacing: 10) {217                    Image(systemName: "exclamationmark.triangle").font(.largeTitle)218                    Text("This file could not be opened.").font(.callout)219                }220                .foregroundStyle(.white.opacity(0.8))221            } else {222                ProgressView().tint(.white)223            }224        }225        .frame(maxWidth: .infinity, maxHeight: .infinity)226        .task(id: ThumbnailCache.key(item)) {227            if item.isVideo {228                if player == nil { player = AVPlayer(url: item.url) }229                return230            }231            // Thumbnail first for an instant picture, then the screen-resolution render.232            if image == nil { image = ThumbnailCache.shared.cached(item) }233            let snapshot = item234            let scale = UIScreen.main.scale235            let side = max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) * scale236            let cg = await Task.detached(priority: .userInitiated) { MediaRenderer.rendered(snapshot, maxDimension: min(side * 1.5, 4096)) }.value237            if let cg { image = UIImage(cgImage: cg) } else if image == nil { failed = true }238        }239        .onDisappear { player?.pause() }240    }241}242243/// Pinch to zoom (1×–8×), drag to pan when zoomed, double tap to toggle 1× / 3×.244struct ZoomableImage: View {245    let image: UIImage246    @State private var scale: CGFloat = 1247    @State private var baseScale: CGFloat = 1248    @State private var offset: CGSize = .zero249    @State private var baseOffset: CGSize = .zero250251    var body: some View {252        GeometryReader { proxy in253            Image(uiImage: image)254                .resizable().scaledToFit()255                .scaleEffect(scale).offset(offset)256                .frame(width: proxy.size.width, height: proxy.size.height)257                .contentShape(Rectangle())258                .gesture(MagnifyGesture()259                    .onChanged { value in scale = min(max(baseScale * value.magnification, 1), 8) }260                    .onEnded { _ in baseScale = scale; if scale <= 1.01 { reset() } else { clamp(in: proxy.size) } })261                .simultaneousGesture(scale > 1.01 ? DragGesture()262                    .onChanged { value in offset = CGSize(width: baseOffset.width + value.translation.width, height: baseOffset.height + value.translation.height) }263                    .onEnded { _ in clamp(in: proxy.size) } : nil)264                .onTapGesture(count: 2) {265                    withAnimation(.snappy) { if scale > 1.01 { reset() } else { scale = 3; baseScale = 3 } }266                }267        }268        .accessibilityElement()269        .accessibilityLabel(Text("Photo"))270        .accessibilityValue(Text("Zoom \(Double(scale).formatted(.number.precision(.fractionLength(1))))×"))271        .accessibilityHint(Text("Double tap to zoom in or out"))272        .accessibilityAdjustableAction { direction in273            switch direction {274            case .increment: scale = min(scale * 1.5, 8); baseScale = scale275            case .decrement: scale = max(scale / 1.5, 1); baseScale = scale; if scale <= 1.01 { reset() }276            @unknown default: break277            }278        }279    }280281    private func reset() { scale = 1; baseScale = 1; offset = .zero; baseOffset = .zero }282283    private func clamp(in size: CGSize) {284        let limitX = size.width * (scale - 1) / 2, limitY = size.height * (scale - 1) / 2285        withAnimation(.snappy) {286            offset = CGSize(width: min(max(offset.width, -limitX), limitX), height: min(max(offset.height, -limitY), limitY))287        }288        baseOffset = offset289    }290}291
Files main
Menu

Theme