Files
lichtkasten/Sources/Lichtkasten/Views/JerseySetupView.swift
T

290 lines
14 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SwiftUI
import LichtkastenCore
/// Teams of the current match: code team (from the code library), prefix and kit colors.
/// Tip: the color picker's magnifier can pick the shirt color directly from a photo on screen.
struct JerseySetupView: View {
@EnvironmentObject var state: AppState
@Environment(\.dismiss) private var dismiss
private var jersey: Binding<JerseySettings> { $state.settings.jersey }
/// Which color the next click in the photo sets: team + shirt/shorts
struct PickTarget: Equatable { var team: UUID; var shorts: Bool }
@State private var target: PickTarget?
@State private var photo: CGImage?
var body: some View {
HStack(alignment: .top, spacing: 16) {
settingsColumn.frame(width: 560)
photoColumn.frame(minWidth: 520, maxWidth: .infinity, maxHeight: .infinity)
}
.padding(18)
.frame(minWidth: 1140, minHeight: 640)
.task(id: state.cursorID) { await loadPhoto() }
.onAppear {
if target == nil, let first = state.settings.jersey.teams.first { target = PickTarget(team: first.id, shorts: false) }
}
}
// MARK: Photo → click on the shirt
private var photoColumn: some View {
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(targetText).font(.headline)
Spacer()
Button { state.moveCursor(by: -1) } label: { Image(systemName: "chevron.left") }
Text(state.cursorItem?.filename ?? "–").font(.caption).foregroundStyle(.secondary).lineLimit(1)
Button { state.moveCursor(by: 1) } label: { Image(systemName: "chevron.right") }
}
ImageColorPicker(image: photo) { color in
guard let t = target, let i = state.settings.jersey.teams.firstIndex(where: { $0.id == t.team }) else { return }
if t.shorts { state.settings.jersey.teams[i].shortsColor = color } else { state.settings.jersey.teams[i].shirtColor = color }
// next useful target: shirt → shorts? no – shirt of the next team
if !t.shorts, i + 1 < state.settings.jersey.teams.count {
target = PickTarget(team: state.settings.jersey.teams[i + 1].id, shorts: false)
}
}
.background(Color.black)
.clipShape(RoundedRectangle(cornerRadius: 6))
Text("Team und „Trikot“/„Hose“ links wählen, dann im Foto auf eine einfarbige Trikotfläche klicken (nicht auf die Nummer). Mit ‹ › ein passendes Bild suchen.")
.font(.caption).foregroundStyle(.secondary)
}
}
private var targetText: String {
guard let t = target, let team = state.settings.jersey.teams.first(where: { $0.id == t.team }) else {
return "Farbe aus dem Foto aufnehmen"
}
return "Klick setzt: \(team.name) – \(t.shorts ? "Hose" : "Trikot")"
}
private func loadPhoto() async {
guard let item = state.cursorItem else { photo = nil; return }
let url = state.previewURL(for: item)
photo = await Task.detached(priority: .userInitiated) { JerseyRecognizer.loadImage(url) }.value
}
// MARK: Settings
private var settingsColumn: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Trikot-Erkennung").font(.title3.bold())
Text("Pro Spiel die Teams wählen und die Trikotfarbe festlegen. Lichtkasten liest Nummern auf Trikot und Hose, bestimmt das Team über die Farbe und schlägt den Spieler aus deinen Code-Ersetzungen vor (Präfix + Nummer, z. B. w10).")
.font(.callout).foregroundStyle(.secondary)
Toggle("Matchday-Ansicht verwenden (Teamleiste, Spieler:innen-Liste, Teamfarben in den Kacheln)",
isOn: jersey.matchday)
ForEach(state.settings.jersey.teams) { t in teamRow(t.id) }
HStack {
Menu("Team hinzufügen") {
ForEach(state.codeLibrary.sets) { set in
Button(set.name) { add(set) }
}
if state.codeLibrary.sets.isEmpty { Text("Zuerst Teams in den Code-Ersetzungen anlegen (⌘⇧K)") }
}
.fixedSize()
Button("Teams tauschen (Heim ↔ Gast)") {
state.settings.jersey.teams.reverse()
}
.disabled(state.settings.jersey.teams.count < 2)
Spacer()
}
GroupBox("Optionen") {
VStack(alignment: .leading, spacing: 8) {
HStack {
Toggle("Nummern auf dem Trikot", isOn: jersey.useShirt)
Toggle("Nummern auf der Hose", isOn: jersey.useShorts)
}
HStack {
Text("Mindest-Sicherheit")
Slider(value: jersey.minConfidence, in: 0.1...0.9)
Text("\(Int(state.settings.jersey.minConfidence * 100)) %").monospacedDigit().frame(width: 44)
}
HStack {
Text("Mehrere Spieler trennen mit")
TextField("", text: jersey.separator).frame(width: 60).textFieldStyle(.roundedBorder)
}
Toggle("Nach dem Ingest automatisch erkennen", isOn: jersey.autoAfterIngest)
}
.padding(6)
}
HStack {
Spacer()
Button("Schließen") { dismiss() }.keyboardShortcut(.cancelAction)
Button("Jetzt erkennen") {
dismiss()
state.recognizeJerseys(state.selection.count > 1 ? state.selectedItems : nil, onlyNew: false)
}
.keyboardShortcut(.defaultAction)
.buttonStyle(.borderedProminent)
.disabled(state.settings.jersey.teams.isEmpty || state.folder == nil)
}
}
}
/// Binding by id – stays valid while a team is being removed (index-based bindings crashed here).
private func teamBinding(_ id: UUID) -> Binding<JerseyTeam> {
Binding(
get: { state.settings.jersey.teams.first { $0.id == id }
?? JerseyTeam(name: "", prefix: "", shirtColor: KitColor(r: 0, g: 0, b: 0)) },
set: { new in
if let i = state.settings.jersey.teams.firstIndex(where: { $0.id == id }) { state.settings.jersey.teams[i] = new }
})
}
private func remove(_ id: UUID) {
if target?.team == id { target = nil }
// after the current view update – removing inside it invalidates the row's bindings
DispatchQueue.main.async {
state.settings.jersey.teams.removeAll { $0.id == id }
if target == nil, let first = state.settings.jersey.teams.first { target = PickTarget(team: first.id, shorts: false) }
}
}
@ViewBuilder
private func teamRow(_ id: UUID) -> some View {
let team = teamBinding(id)
GroupBox {
HStack(spacing: 12) {
VStack(alignment: .leading, spacing: 6) {
TextField("Team", text: team.name).textFieldStyle(.roundedBorder).font(.headline)
HStack {
Text("Code-Präfix")
TextField("w", text: team.prefix).frame(width: 50).textFieldStyle(.roundedBorder)
Text(example(team.wrappedValue))
.font(.caption).foregroundStyle(.secondary).lineLimit(1)
}
}
Spacer()
swatchButton(team.wrappedValue, shorts: false)
Toggle("Hose", isOn: Binding(
get: { team.wrappedValue.shortsColor != nil },
set: { on in
team.wrappedValue.shortsColor = on ? team.wrappedValue.shirtColor : nil
if on { target = PickTarget(team: id, shorts: true) }
}))
.toggleStyle(.checkbox)
.help("Eigene Hosenfarbe (z. B. weißes Trikot, grüne Hose)")
if team.wrappedValue.shortsColor != nil { swatchButton(team.wrappedValue, shorts: true) }
ColorPicker("", selection: cgBinding(team.shirtColor), supportsOpacity: false)
.labelsHidden()
.help("Alternativ: Farbe manuell wählen")
Button(role: .destructive) { remove(id) } label: { Image(systemName: "trash") }
.buttonStyle(.borderless)
.help("Team entfernen")
}
.padding(4)
}
}
/// Color swatch; click = "next click in the photo sets this color".
private func swatchButton(_ team: JerseyTeam, shorts: Bool) -> some View {
let c = shorts ? (team.shortsColor ?? team.shirtColor) : team.shirtColor
let active = target == PickTarget(team: team.id, shorts: shorts)
return Button { target = PickTarget(team: team.id, shorts: shorts) } label: {
VStack(spacing: 2) {
RoundedRectangle(cornerRadius: 4)
.fill(Color(red: c.r, green: c.g, blue: c.b))
.frame(width: 34, height: 24)
.overlay(RoundedRectangle(cornerRadius: 4).stroke(active ? LK.amber : Color.secondary, lineWidth: active ? 3 : 1))
Text(shorts ? "Hose" : "Trikot").font(.caption2)
}
}
.buttonStyle(.plain)
.help("Auswählen und dann im Foto auf \(shorts ? "die Hose" : "das Trikot") klicken")
}
private func example(_ t: JerseyTeam) -> String {
guard let set = state.codeLibrary.sets.first(where: { $0.id == t.codeSetID }),
let e = set.entries.first(where: { $0.code.lowercased().hasPrefix(t.prefix.lowercased()) }) else { return "" }
return "z. B. \(e.code) → \(e.columns.first ?? "")"
}
private func add(_ set: CodeSet) {
let prefix = JerseyLogic.detectPrefix(codes: set.entries.map(\.code))
// first team light, second dark as a starting point – adjust with the picker
let defaults = [KitColor(r: 0.1, g: 0.45, b: 0.25), KitColor(r: 0.95, g: 0.95, b: 0.95), KitColor(r: 0.1, g: 0.2, b: 0.6)]
let color = defaults[min(state.settings.jersey.teams.count, defaults.count - 1)]
state.settings.jersey.teams.append(JerseyTeam(name: set.name, codeSetID: set.id, prefix: prefix, shirtColor: color))
}
private func cg(_ c: KitColor) -> CGColor { CGColor(srgbRed: c.r, green: c.g, blue: c.b, alpha: 1) }
private func rgb(_ c: CGColor) -> KitColor {
let conv = c.converted(to: CGColorSpace(name: CGColorSpace.sRGB)!, intent: .defaultIntent, options: nil) ?? c
let comps = conv.components ?? [0, 0, 0]
if comps.count >= 3 { return KitColor(r: Double(comps[0]), g: Double(comps[1]), b: Double(comps[2])) }
return KitColor(r: Double(comps[0]), g: Double(comps[0]), b: Double(comps[0])) // grayscale
}
private func cgBinding(_ b: Binding<KitColor>) -> Binding<CGColor> {
Binding(get: { cg(b.wrappedValue) }, set: { b.wrappedValue = rgb($0) })
}
}
/// Photo in which a click samples the kit color (k-means over a small patch, the same measure
/// the recognizer uses – numbers, folds and highlights drop out).
struct ImageColorPicker: View {
let image: CGImage?
let onPick: (KitColor) -> Void
@State private var marker: CGPoint?
@State private var lastColor: KitColor?
var body: some View {
GeometryReader { geo in
if let image {
let fit = Self.fitRect(CGSize(width: image.width, height: image.height), in: geo.size)
ZStack(alignment: .topLeading) {
Image(decorative: image, scale: 1)
.resizable()
.frame(width: fit.width, height: fit.height)
.offset(x: fit.minX, y: fit.minY)
if let m = marker {
Circle().stroke(Color.white, lineWidth: 2)
.background(Circle().fill(lastColor.map { Color(red: $0.r, green: $0.g, blue: $0.b) } ?? .clear))
.frame(width: 22, height: 22)
.shadow(radius: 2)
.offset(x: fit.minX + m.x * fit.width - 11, y: fit.minY + m.y * fit.height - 11)
}
}
.frame(width: geo.size.width, height: geo.size.height, alignment: .topLeading)
.contentShape(Rectangle())
.onTapGesture(coordinateSpace: .local) { loc in
guard fit.contains(loc) else { return }
let nx = (loc.x - fit.minX) / fit.width, ny = (loc.y - fit.minY) / fit.height
guard let color = Self.sample(image, nx: nx, ny: ny) else { return }
marker = CGPoint(x: nx, y: ny)
lastColor = color
onPick(color)
}
.onHover { inside in if inside { NSCursor.crosshair.push() } else { NSCursor.pop() } }
} else {
Text("Kein Bild ausgewählt").foregroundStyle(.secondary)
.frame(width: geo.size.width, height: geo.size.height)
}
}
.onChange(of: image.map { ObjectIdentifier($0) }) { _, _ in marker = nil }
}
static func fitRect(_ img: CGSize, in box: CGSize) -> CGRect {
guard img.width > 0, img.height > 0 else { return .zero }
let s = min(box.width / img.width, box.height / img.height)
let w = img.width * s, h = img.height * s
return CGRect(x: (box.width - w) / 2, y: (box.height - h) / 2, width: w, height: h)
}
/// Patch of ~1.5 % of the image width around the click.
static func sample(_ img: CGImage, nx: CGFloat, ny: CGFloat) -> KitColor? {
let W = CGFloat(img.width), H = CGFloat(img.height)
let r = max(8, W * 0.0075)
let rect = CGRect(x: nx * W - r, y: ny * H - r, width: 2 * r, height: 2 * r)
.intersection(CGRect(x: 0, y: 0, width: W, height: H)).integral
guard rect.width > 2, let crop = img.cropping(to: rect) else { return nil }
return JerseyRecognizer.dominantColor(crop, centerOnly: false)
}
}