SPB Git

Repository Public License

EditorScreen.swift 26.1 KB 512 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Camera9// File             : App/Sources/Features/Editor/EditorScreen.swift10// Description      : The non-destructive photo editor: presets, light, colour,11//                    detail, tone curve, crop and RAW development, with12//                    undo/redo and a press-and-hold comparison. Saving stores a13//                    recipe; the original file is never written.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 CoreImage94import ORIXDesign95import ORIXImaging96import SwiftUI9798nonisolated enum EditorTab: String, CaseIterable, Sendable, Identifiable {99    case presets, light, colour, detail, curve, crop, raw100    var id: String { rawValue }101    var title: LocalizedStringResource {102        switch self {103        case .presets: "Presets"104        case .light: "Light"105        case .colour: "Colour"106        case .detail: "Detail"107        case .curve: "Curve"108        case .crop: "Crop"109        case .raw: "RAW"110        }111    }112    var symbol: String {113        switch self {114        case .presets: "wand.and.stars"115        case .light: "sun.max"116        case .colour: "drop"117        case .detail: "triangle"118        case .curve: "point.topleft.down.to.point.bottomright.curvepath"119        case .crop: "crop.rotate"120        case .raw: "camera.aperture"121        }122    }123}124125struct EditorScreen: View {126    let item: MediaItem127    let library: MediaLibrary128129    @Environment(\.dismiss) private var dismiss130    @Environment(\.accessibilityReduceMotion) private var reduceMotion131    @State private var session: EditorSession132    @State private var source: ItemSnapshot133    @State private var tab: EditorTab = EditorTab(rawValue: LibraryDebug.editorTab ?? "") ?? .light134    @State private var base: CGImage?135    @State private var baseRAW: RAWSettings?136    @State private var preview: CGImage?137    @State private var before: CGImage?138    @State private var presetThumbnails: [String: CGImage] = [:]139    @State private var rawInfo: RAWInfo?140    @State private var comparing = false141    @State private var loadFailed = false142    @State private var confirmDiscard = false143    @State private var confirmReset = false144    @State private var renderTask: Task<Void, Never>?145    @State private var baseTask: Task<Void, Never>?146147    init(item: MediaItem, library: MediaLibrary) {148        self.item = item149        self.library = library150        _session = State(initialValue: EditorSession(recipe: item.recipe))151        _source = State(initialValue: item.snapshot(storage: library.storage))152    }153154    private var tabs: [EditorTab] { EditorTab.allCases.filter { $0 != .raw || source.isRAW } }155156    var body: some View {157        GeometryReader { proxy in158            let wide = proxy.size.width > proxy.size.height * 1.1159            VStack(spacing: 0) {160                topBar161                if wide {162                    HStack(spacing: 0) {163                        canvas164                        VStack(spacing: 0) { controls; tabBar }.frame(width: min(400, proxy.size.width * 0.38)).background(Instrument.panel)165                    }166                } else {167                    canvas168                    VStack(spacing: 0) { controls.frame(height: min(280, proxy.size.height * 0.36)); tabBar }.background(Instrument.panel)169                }170            }171            .background(Instrument.body.ignoresSafeArea())172        }173        .preferredColorScheme(.dark)174        .tint(Instrument.accent)175        .task { await loadBase(raw: session.recipe.raw, first: true) }176        .onChange(of: session.recipe) { old, new in177            if old.raw != new.raw { scheduleBase() } else { scheduleRender() }178        }179        .onChange(of: tab) { scheduleRender() }180        .confirmationDialog(Text("Discard your changes?"), isPresented: $confirmDiscard, titleVisibility: .visible) {181            Button("Discard Changes", role: .destructive) { dismiss() }182            Button("Keep Editing", role: .cancel) {}183        }184        .confirmationDialog(Text("Reset to the original?"), isPresented: $confirmReset, titleVisibility: .visible) {185            Button("Reset All Edits", role: .destructive) { session.reset() }186            Button("Cancel", role: .cancel) {}187        } message: { Text("Every adjustment, the crop and the rotation are removed. You can undo this.") }188    }189190    // MARK: Bars191192    private var topBar: some View {193        HStack(spacing: 4) {194            Button("Cancel") { if session.hasChanges { confirmDiscard = true } else { dismiss() } }195                .accessibilityIdentifier("editor.cancel")196            Spacer()197            barIcon("arrow.uturn.backward", "Undo", id: "editor.undo") { session.undo() }.disabled(!session.canUndo)198            barIcon("arrow.uturn.forward", "Redo", id: "editor.redo") { session.redo() }.disabled(!session.canRedo)199            Image(systemName: "square.split.2x1")200                .font(.body.weight(.semibold))201                .foregroundStyle(comparing ? Instrument.manual : Instrument.text)202                .frame(width: 44, height: 44)203                .contentShape(Rectangle())204                .onLongPressGesture(minimumDuration: 0, maximumDistance: 80, perform: {}, onPressingChanged: { pressing in setComparing(pressing) })205                .accessibilityElement()206                .accessibilityLabel(Text("Compare with original"))207                .accessibilityHint(Text("Press and hold to see the photo without your adjustments"))208                .accessibilityAddTraits(comparing ? [.isButton, .isSelected] : .isButton)209                .accessibilityAction { setComparing(!comparing) }210                .accessibilityIdentifier("editor.compare")211            barIcon("arrow.counterclockwise", "Reset all edits", id: "editor.reset") { confirmReset = true }.disabled(session.isPristine)212            Spacer()213            Button("Done") { save() }.fontWeight(.semibold).accessibilityIdentifier("editor.done")214        }215        .padding(.horizontal, 12)216        .frame(height: 50)217        .foregroundStyle(Instrument.text)218    }219220    private func barIcon(_ symbol: String, _ label: LocalizedStringKey, id: String, action: @escaping () -> Void) -> some View {221        Button(action: action) { Image(systemName: symbol).font(.body.weight(.semibold)).frame(width: 44, height: 44) }222            .accessibilityLabel(Text(label)).accessibilityIdentifier(id)223    }224225    private var tabBar: some View {226        ScrollView(.horizontal, showsIndicators: false) {227            HStack(spacing: 2) {228                ForEach(tabs) { entry in229                    Button { tab = entry } label: {230                        VStack(spacing: 3) {231                            Image(systemName: entry.symbol).font(.system(size: 17, weight: .medium))232                            Text(entry.title).font(.caption2.weight(.semibold))233                        }234                        .foregroundStyle(tab == entry ? Instrument.manual : Instrument.textDim)235                        .frame(minWidth: 62, minHeight: 50)236                        .contentShape(Rectangle())237                    }238                    .buttonStyle(.plain)239                    .accessibilityIdentifier("editor.tab.\(entry.rawValue)")240                    .accessibilityAddTraits(tab == entry ? .isSelected : [])241                }242            }243            .padding(.horizontal, 8)244        }245        .frame(maxWidth: .infinity)246        .background(Instrument.body)247    }248249    // MARK: Canvas250251    private var canvas: some View {252        GeometryReader { proxy in253            let shown = comparing ? (before ?? preview) : preview254            ZStack {255                if let shown {256                    let fitted = Self.fit(CGSize(width: shown.width, height: shown.height), in: proxy.size, padding: tab == .crop ? 26 : 8)257                    Image(decorative: shown, scale: 1).resizable()258                        .frame(width: fitted.width, height: fitted.height)259                        .overlay {260                            if tab == .crop, !comparing {261                                CropOverlay(rect: session.cropRect, ratio: session.cropAspect.ratio(imageAspect: session.imageAspect), imageAspect: session.imageAspect,262                                            change: { session.setCrop($0) }, commit: { session.commit() })263                            }264                        }265                        .position(x: fitted.midX, y: fitted.midY)266                        .accessibilityElement(children: .contain)267                        .accessibilityLabel(Text(comparing ? "Photo without adjustments" : "Edited photo preview"))268                } else if loadFailed {269                    Label("This photo could not be opened for editing.", systemImage: "exclamationmark.triangle").foregroundStyle(Instrument.textDim)270                } else {271                    ProgressView().tint(.white)272                }273                if comparing {274                    VStack { MonitorBadge(text: String(localized: "ORIGINAL TONES"), color: Instrument.manual); Spacer() }.padding(.top, 10)275                }276            }277            .frame(width: proxy.size.width, height: proxy.size.height)278        }279        .background(Color.black)280        .clipped()281    }282283    static func fit(_ image: CGSize, in container: CGSize, padding: CGFloat) -> CGRect {284        let available = CGSize(width: max(container.width - padding * 2, 1), height: max(container.height - padding * 2, 1))285        let scale = min(available.width / max(image.width, 1), available.height / max(image.height, 1))286        let size = CGSize(width: image.width * scale, height: image.height * scale)287        return CGRect(x: (container.width - size.width) / 2, y: (container.height - size.height) / 2, width: size.width, height: size.height)288    }289290    // MARK: Controls291292    private func slider(_ id: String, _ title: LocalizedStringKey, _ path: WritableKeyPath<EditRecipe, Double>, range: ClosedRange<Double> = -1...1,293                        format: ((Double) -> String)? = nil) -> some View {294        let binding = Binding(get: { session.recipe[keyPath: path] }, set: { session.recipe[keyPath: path] = $0 })295        return Group {296            if let format { EditSlider(id: id, title: title, value: binding, range: range, format: format) { session.commit() } } else {297                EditSlider(id: id, title: title, value: binding, range: range) { session.commit() }298            }299        }300    }301302    private var controls: some View {303        ScrollView {304            VStack(spacing: 6) {305                switch tab {306                case .presets: presetsPanel307                case .light:308                    slider("exposure", "Exposure", \.exposure, range: -3...3) { $0.formatted(.number.precision(.fractionLength(2)).sign(strategy: .always(includingZero: false))) + " EV" }309                    slider("contrast", "Contrast", \.contrast)310                    slider("highlights", "Highlights", \.highlights)311                    slider("shadows", "Shadows", \.shadows)312                    slider("vignette", "Vignette", \.vignette, range: 0...1)313                case .colour: colourPanel314                case .detail:315                    slider("sharpness", "Sharpening", \.sharpness, range: 0...1)316                    slider("noiseReduction", "Noise reduction", \.noiseReduction, range: 0...1)317                    Text("Judge sharpening and noise reduction at full size: the preview is downsized.")318                        .font(.caption2).foregroundStyle(Instrument.textFaint).frame(maxWidth: .infinity, alignment: .leading)319                case .curve:320                    CurveEditor(curve: Binding(get: { session.recipe.curve }, set: { session.recipe.curve = $0 })) { session.commit() }321                    Button("Reset Curve") { session.recipe.curve = EditRecipe.identityCurve; session.commit() }322                        .disabled(session.recipe.curve == EditRecipe.identityCurve).frame(minHeight: 44)323                case .crop: cropPanel324                case .raw: rawPanel325                }326            }327            .padding(.horizontal, 16).padding(.vertical, 10)328        }329    }330331    private var presetsPanel: some View {332        VStack(alignment: .leading, spacing: 8) {333            ScrollView(.horizontal, showsIndicators: false) {334                HStack(spacing: 10) {335                    ForEach(EditPreset.all) { preset in336                        let selected = preset.applied(to: session.recipe) == session.recipe337                        Button { session.apply(preset) } label: {338                            VStack(spacing: 5) {339                                Group {340                                    if let thumbnail = presetThumbnails[preset.id] {341                                        Image(decorative: thumbnail, scale: 1).resizable().scaledToFill()342                                    } else { Instrument.panelRaised }343                                }344                                .frame(width: 84, height: 84)345                                .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))346                                .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(selected ? Instrument.manual : .clear, lineWidth: 2))347                                Text(LocalizedStringKey(preset.title)).font(.caption2.weight(.semibold)).foregroundStyle(selected ? Instrument.manual : Instrument.textDim)348                            }349                        }350                        .buttonStyle(.plain)351                        .accessibilityIdentifier("editor.preset.\(preset.id)")352                        .accessibilityLabel(Text(LocalizedStringKey(preset.title)))353                        .accessibilityAddTraits(selected ? .isSelected : [])354                    }355                }356            }357            Text("A preset replaces the tone and colour adjustments. Crop and rotation are kept.")358                .font(.caption2).foregroundStyle(Instrument.textFaint)359        }360    }361362    @ViewBuilder private var colourPanel: some View {363        slider("temperature", "Temperature", \.temperature)364        slider("tint", "Tint", \.tint)365        slider("saturation", "Saturation", \.saturation)366        slider("vibrance", "Vibrance", \.vibrance)367        Toggle("Black and white", isOn: Binding(get: { session.recipe.monochrome }, set: { session.recipe.monochrome = $0; session.commit() }))368            .font(.subheadline.weight(.medium)).foregroundStyle(Instrument.text).tint(Instrument.manual).frame(minHeight: 44)369            .accessibilityIdentifier("editor.monochrome")370        VStack(alignment: .leading, spacing: 6) {371            Text("Look").font(.subheadline.weight(.medium)).foregroundStyle(Instrument.text)372            ScrollView(.horizontal, showsIndicators: false) {373                HStack(spacing: 6) {374                    PillButton(title: "None", isOn: session.recipe.lookID == nil, tint: Instrument.manual) { session.recipe.lookID = nil; session.commit() }375                    ForEach(ColorLUT.builtIn.dropFirst()) { look in376                        PillButton(title: LocalizedStringKey(look.title), isOn: session.recipe.lookID == look.id, tint: Instrument.manual) {377                            session.recipe.lookID = look.id; session.commit()378                        }379                        .accessibilityIdentifier("editor.look.\(look.id)")380                    }381                }382            }383        }384        if session.recipe.lookID != nil {385            slider("lookIntensity", "Look intensity", \.lookIntensity, range: 0...1) { $0.formatted(.percent.precision(.fractionLength(0))) }386        }387    }388389    @ViewBuilder private var cropPanel: some View {390        ScrollView(.horizontal, showsIndicators: false) {391            HStack(spacing: 6) {392                ForEach(CropAspect.allCases) { aspect in393                    PillButton(title: LocalizedStringKey(aspect.title), isOn: session.cropAspect == aspect, tint: Instrument.manual) { session.setAspect(aspect) }394                        .accessibilityIdentifier("editor.aspect.\(aspect.rawValue)")395                }396            }397        }398        HStack(spacing: 10) {399            geometryButton("rotate.right", "Rotate", id: "editor.rotate") { session.rotateClockwise() }400            geometryButton("arrow.left.and.right.righttriangle.left.righttriangle.right", "Flip", id: "editor.flip") { session.flipHorizontally() }401            geometryButton("arrow.counterclockwise", "Reset", id: "editor.resetGeometry") { session.resetGeometry() }402                .disabled(!session.recipe.hasGeometry)403        }404        slider("straighten", "Straighten", \.straighten, range: -45...45) { $0.formatted(.number.precision(.fractionLength(1)).sign(strategy: .always(includingZero: false))) + "°" }405        Text("Drag a corner to resize the crop, or inside it to move it. The full original stays on disk.")406            .font(.caption2).foregroundStyle(Instrument.textFaint).frame(maxWidth: .infinity, alignment: .leading)407    }408409    private func geometryButton(_ symbol: String, _ title: LocalizedStringKey, id: String, action: @escaping () -> Void) -> some View {410        Button(action: action) {411            Label(title, systemImage: symbol).font(.footnote.weight(.semibold)).foregroundStyle(Instrument.text)412                .frame(maxWidth: .infinity, minHeight: 44).background(Instrument.panelRaised, in: RoundedRectangle(cornerRadius: 10, style: .continuous))413        }414        .buttonStyle(.plain)415        .accessibilityIdentifier(id)416    }417418    @ViewBuilder private var rawPanel: some View {419        let raw = session.recipe.raw ?? RAWSettings()420        let asShotTemperature = rawInfo?.asShotTemperature ?? 5500, asShotTint = rawInfo?.asShotTint ?? 0421        EditSlider(id: "raw.exposure", title: "RAW exposure", value: Binding(get: { raw.exposure }, set: { v in session.updateRAW { $0.exposure = v } }), range: -3...3,422                   format: { $0.formatted(.number.precision(.fractionLength(2)).sign(strategy: .always(includingZero: false))) + " EV" }) { session.commit() }423        EditSlider(id: "raw.temperature", title: "White balance", value: Binding(get: { raw.temperature ?? asShotTemperature }, set: { v in session.updateRAW { $0.temperature = v } }),424                   range: 2000...12000, neutral: asShotTemperature, format: { "\(Int(($0 / 50).rounded()) * 50) K" }) {425            if abs((session.recipe.raw?.temperature ?? asShotTemperature) - asShotTemperature) < 1 { session.updateRAW { $0.temperature = nil } }426            session.commit()427        }428        EditSlider(id: "raw.tint", title: "White balance tint", value: Binding(get: { raw.tint ?? asShotTint }, set: { v in session.updateRAW { $0.tint = v } }),429                   range: -150...150, neutral: asShotTint, format: { $0.formatted(.number.precision(.fractionLength(0)).sign(strategy: .always(includingZero: false))) }) {430            if abs((session.recipe.raw?.tint ?? asShotTint) - asShotTint) < 0.5 { session.updateRAW { $0.tint = nil } }431            session.commit()432        }433        if rawInfo?.supportsLuminanceNoiseReduction != false {434            EditSlider(id: "raw.noise", title: "RAW noise reduction", value: Binding(get: { raw.luminanceNoiseReduction ?? 0 }, set: { v in session.updateRAW { $0.luminanceNoiseReduction = v; $0.colorNoiseReduction = v } }),435                       range: 0...1) { session.commit() }436        }437        if rawInfo?.supportsSharpness != false {438            EditSlider(id: "raw.sharpness", title: "RAW sharpness", value: Binding(get: { raw.sharpness ?? 0 }, set: { v in session.updateRAW { $0.sharpness = v } }), range: 0...1) { session.commit() }439        }440        Button("Back to As-Shot Development") { session.recipe.raw = nil; session.commit() }441            .disabled(session.recipe.raw == nil).frame(minHeight: 44).accessibilityIdentifier("editor.raw.reset")442        Text("These settings act on the sensor data before the other adjustments. The DNG file is never rewritten.")443            .font(.caption2).foregroundStyle(Instrument.textFaint).frame(maxWidth: .infinity, alignment: .leading)444    }445446    // MARK: Rendering (off the main thread)447448    private var previewSide: CGFloat { min(max(UIScreen.main.bounds.width, UIScreen.main.bounds.height) * UIScreen.main.scale, 2048) }449450    private func loadBase(raw: RAWSettings?, first: Bool) async {451        let url = source.url, isRAW = source.isRAW, side = previewSide452        let loaded = await Task.detached(priority: .userInitiated) { MediaRenderer.previewBase(url: url, isRAW: isRAW, raw: raw, maxDimension: side) }.value453        guard !Task.isCancelled else { return }454        guard let loaded else { if base == nil { loadFailed = true }; return }455        base = loaded; baseRAW = raw; before = nil456        session.sourceAspect = Double(loaded.width) / Double(max(loaded.height, 1))457        if first, isRAW { rawInfo = await Task.detached { RAWDeveloper.info(url: url) }.value }458        scheduleRender(immediately: true)459        if first || presetThumbnails.isEmpty { renderPresetThumbnails(loaded) }460    }461462    private func scheduleBase() {463        baseTask?.cancel()464        let raw = session.recipe.raw465        baseTask = Task {466            try? await Task.sleep(for: .milliseconds(140))467            if !Task.isCancelled { await loadBase(raw: raw, first: false) }468        }469    }470471    private func scheduleRender(immediately: Bool = false) {472        guard let base else { return }473        renderTask?.cancel()474        let recipe = tab == .crop ? session.recipeForCropping : session.recipe475        let side = previewSide476        renderTask = Task {477            if !immediately { try? await Task.sleep(for: .milliseconds(25)) }478            guard !Task.isCancelled else { return }479            let image = await Task.detached(priority: .userInitiated) { EditPipeline.render(recipe: recipe, source: CIImage(cgImage: base), maxDimension: side) }.value480            if !Task.isCancelled, let image { preview = image }481        }482    }483484    private func setComparing(_ on: Bool) {485        guard on != comparing else { return }486        if on, before == nil, let base {487            // Same geometry as the edit, none of the tone or colour: the two pictures stay registered.488            let recipe = tab == .crop ? session.recipeForCropping.geometryOnly : session.recipe.geometryOnly489            before = EditPipeline.render(recipe: recipe, source: CIImage(cgImage: base), maxDimension: previewSide)490        }491        if !on { before = nil }492        comparing = on493    }494495    private func renderPresetThumbnails(_ base: CGImage) {496        Task {497            let rendered: [String: CGImage] = await Task.detached(priority: .utility) {498                guard let small = EditPipeline.render(CIImage(cgImage: base), maxDimension: 220) else { return [:] }499                var out: [String: CGImage] = [:]500                for preset in EditPreset.all { out[preset.id] = EditPipeline.render(recipe: preset.recipe, source: CIImage(cgImage: small)) }501                return out502            }.value503            presetThumbnails = rendered504        }505    }506507    private func save() {508        library.setRecipe(session.recipe.isIdentity ? nil : session.recipe, for: item)509        dismiss()510    }511}512
Files main
Menu

Theme