SPB Git

Repository Public License

EditorControls.swift 13.9 KB 302 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/EditorControls.swift10// Description      : Editor building blocks: the adjustment slider row, the11//                    five-point tone-curve editor and the crop overlay.12// Module           : Features13// Repository       : https://git.spboucher.ai/orix-camera14// Project Website  : https://www.orixlab.dev15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import ORIXDesign92import ORIXImaging93import SwiftUI9495/// A labelled slider. The value changes live; `commit` is called once when the gesture ends (one undo step).96struct EditSlider: View {97    let id: String98    let title: LocalizedStringKey99    @Binding var value: Double100    var range: ClosedRange<Double> = -1...1101    var neutral: Double = 0102    var format: (Double) -> String = { ($0 * 100).formatted(.number.precision(.fractionLength(0)).sign(strategy: .always(includingZero: false))) }103    let commit: () -> Void104    @State private var settle: Task<Void, Never>?105106    var body: some View {107        VStack(spacing: 2) {108            HStack {109                Text(title).font(.subheadline.weight(.medium)).foregroundStyle(Instrument.text)110                Spacer()111                Button {112                    value = neutral; commit()113                } label: {114                    Text(format(value)).font(Instrument.readout(.subheadline))115                        .foregroundStyle(abs(value - neutral) > 1e-6 ? Instrument.manual : Instrument.textDim)116                        .frame(minWidth: 52, minHeight: 30, alignment: .trailing)117                }118                .buttonStyle(.plain)119                .accessibilityLabel(Text("Reset"))120                .accessibilityHint(Text("Sets this adjustment back to neutral"))121            }122            Slider(value: $value, in: range) { editing in if !editing { commit() } }123                // The end-of-drag callback is not delivered for every input method (VoiceOver, Switch Control, keyboards), so124                // a change is also committed once the value has rested for a moment. Committing an unchanged state is a no-op.125                .onChange(of: value) {126                    settle?.cancel()127                    settle = Task {128                        try? await Task.sleep(for: .milliseconds(350))129                        if !Task.isCancelled { commit() }130                    }131                }132                .tint(abs(value - neutral) > 1e-6 ? Instrument.manual : Instrument.textFaint)133                .accessibilityLabel(Text(title))134                .accessibilityValue(Text(format(value)))135                .accessibilityIdentifier("editor.slider.\(id)")136        }137        .frame(minHeight: 58)138    }139}140141/// Five control points at inputs 0, ¼, ½, ¾, 1. Points move vertically and cannot cross their neighbours' levels.142struct CurveEditor: View {143    @Binding var curve: [Double]144    let commit: () -> Void145    @State private var active: Int?146147    var body: some View {148        GeometryReader { proxy in149            let size = proxy.size150            ZStack {151                Canvas { context, canvas in152                    for i in 1..<4 {153                        var grid = Path()154                        let x = canvas.width * CGFloat(i) / 4, y = canvas.height * CGFloat(i) / 4155                        grid.move(to: CGPoint(x: x, y: 0)); grid.addLine(to: CGPoint(x: x, y: canvas.height))156                        grid.move(to: CGPoint(x: 0, y: y)); grid.addLine(to: CGPoint(x: canvas.width, y: y))157                        context.stroke(grid, with: .color(.white.opacity(0.1)), lineWidth: 1)158                    }159                    var diagonal = Path()160                    diagonal.move(to: CGPoint(x: 0, y: canvas.height)); diagonal.addLine(to: CGPoint(x: canvas.width, y: 0))161                    context.stroke(diagonal, with: .color(.white.opacity(0.18)), style: StrokeStyle(lineWidth: 1, dash: [4, 4]))162                    let table = ToneCurve.table(ys: curve.count == 5 ? curve : EditRecipe.identityCurve, count: 128)163                    var path = Path()164                    for (i, v) in table.enumerated() {165                        let p = CGPoint(x: canvas.width * CGFloat(i) / 127, y: canvas.height * (1 - CGFloat(v)))166                        if i == 0 { path.move(to: p) } else { path.addLine(to: p) }167                    }168                    context.stroke(path, with: .color(Instrument.manual), lineWidth: 2)169                }170                ForEach(0..<5, id: \.self) { index in171                    let y = curve.count == 5 ? curve[index] : EditRecipe.identityCurve[index]172                    Circle()173                        .fill(active == index ? Instrument.manual : .white)174                        .frame(width: 14, height: 14)175                        .overlay(Circle().stroke(.black.opacity(0.5), lineWidth: 1))176                        .frame(width: 44, height: 44)177                        .contentShape(Rectangle())178                        .position(x: size.width * CGFloat(index) / 4, y: size.height * (1 - CGFloat(y)))179                        .gesture(DragGesture(minimumDistance: 0)180                            .onChanged { value in181                                active = index182                                set(index, to: 1 - Double(value.location.y / max(size.height, 1)))183                            }184                            .onEnded { _ in active = nil; commit() })185                        .accessibilityElement()186                        .accessibilityLabel(Text(Self.name(index)))187                        .accessibilityValue(Text(y.formatted(.percent.precision(.fractionLength(0)))))188                        .accessibilityIdentifier("editor.curve.\(index)")189                        .accessibilityAdjustableAction { direction in190                            set(index, to: y + (direction == .increment ? 0.02 : -0.02)); commit()191                        }192                }193            }194        }195        .aspectRatio(1.6, contentMode: .fit)196        .padding(12)197        .background(Instrument.panelRaised, in: RoundedRectangle(cornerRadius: 12, style: .continuous))198    }199200    static func name(_ index: Int) -> LocalizedStringResource {201        switch index {202        case 0: "Black point"203        case 1: "Shadows"204        case 2: "Midtones"205        case 3: "Highlights"206        default: "White point"207        }208    }209210    private func set(_ index: Int, to value: Double) {211        var points = curve.count == 5 ? curve : EditRecipe.identityCurve212        let lower = index > 0 ? points[index - 1] : 0, upper = index < 4 ? points[index + 1] : 1213        points[index] = min(max(value, lower), upper)214        curve = points215    }216}217218/// The crop rectangle over the full (uncropped) picture: drag a corner to resize, drag inside to move.219struct CropOverlay: View {220    let rect: CGRect221    let ratio: Double?222    let imageAspect: Double223    let change: (CGRect) -> Void224    let commit: () -> Void225    @State private var start: CGRect?226227    var body: some View {228        GeometryReader { proxy in229            let size = proxy.size230            let frame = CGRect(x: rect.minX * size.width, y: rect.minY * size.height, width: rect.width * size.width, height: rect.height * size.height)231            ZStack(alignment: .topLeading) {232                Path { p in p.addRect(CGRect(origin: .zero, size: size)); p.addRect(frame) }233                    .fill(.black.opacity(0.6), style: FillStyle(eoFill: true))234                    .allowsHitTesting(false)235                Path { p in236                    p.addRect(frame)237                    for i in 1..<3 {238                        let x = frame.minX + frame.width * CGFloat(i) / 3, y = frame.minY + frame.height * CGFloat(i) / 3239                        p.move(to: CGPoint(x: x, y: frame.minY)); p.addLine(to: CGPoint(x: x, y: frame.maxY))240                        p.move(to: CGPoint(x: frame.minX, y: y)); p.addLine(to: CGPoint(x: frame.maxX, y: y))241                    }242                }243                .stroke(.white.opacity(0.85), lineWidth: 1)244                .allowsHitTesting(false)245                Color.clear.contentShape(Rectangle())246                    .frame(width: max(frame.width - 44, 1), height: max(frame.height - 44, 1))247                    .position(x: frame.midX, y: frame.midY)248                    .gesture(drag(.move, size))249                ForEach(Array([CropMath.Handle.topLeft, .topRight, .bottomLeft, .bottomRight].enumerated()), id: \.offset) { index, handle in250                    let left = handle == .topLeft || handle == .bottomLeft, top = handle == .topLeft || handle == .topRight251                    CornerMark(left: left, top: top)252                        .frame(width: 48, height: 48)253                        .contentShape(Rectangle())254                        .position(x: left ? frame.minX : frame.maxX, y: top ? frame.minY : frame.maxY)255                        .gesture(drag(handle, size))256                        .accessibilityElement()257                        .accessibilityLabel(Text(Self.name(index)))258                        .accessibilityHint(Text("Drag to resize the crop"))259                        .accessibilityIdentifier("editor.crop.handle.\(index)")260                }261            }262        }263        .accessibilityElement(children: .contain)264        .accessibilityLabel(Text("Crop area"))265        .accessibilityValue(Text("\(Double(rect.width).formatted(.percent.precision(.fractionLength(0)))) wide, \(Double(rect.height).formatted(.percent.precision(.fractionLength(0)))) high"))266    }267268    static func name(_ index: Int) -> LocalizedStringResource {269        switch index {270        case 0: "Top left corner"271        case 1: "Top right corner"272        case 2: "Bottom left corner"273        default: "Bottom right corner"274        }275    }276277    private func drag(_ handle: CropMath.Handle, _ size: CGSize) -> some Gesture {278        DragGesture(minimumDistance: 1)279            .onChanged { value in280                if start == nil { start = rect }281                let delta = CGSize(width: value.translation.width / max(size.width, 1), height: value.translation.height / max(size.height, 1))282                change(CropMath.drag(start ?? rect, handle: handle, delta: delta, ratio: ratio, imageAspect: imageAspect))283            }284            .onEnded { _ in start = nil; commit() }285    }286}287288private struct CornerMark: View {289    let left: Bool290    let top: Bool291    var body: some View {292        Path { p in293            let c = CGPoint(x: 24, y: 24), l: CGFloat = 16294            p.move(to: CGPoint(x: c.x + (left ? l : -l), y: c.y))295            p.addLine(to: c)296            p.addLine(to: CGPoint(x: c.x, y: c.y + (top ? l : -l)))297        }298        .stroke(.white, style: StrokeStyle(lineWidth: 3.5, lineCap: .round, lineJoin: .round))299        .shadow(color: .black.opacity(0.5), radius: 1)300    }301}302
Files main
Menu

Theme