Code-Ersetzung mit Teams (TXT-Import, nur neue Spieler nachladen, Auto-Reload), Codes ohne Trennzeichen, Cursor bleibt stehen; Auswerfen per diskutil mit Wiederholung direkt nach dem Kopieren
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
This commit is contained in:
1 parent
d39db536a0
commit
25729ebfe3
10 files changed
+602
-121
No files matched your search
@@ -72,7 +72,15 @@ final class AppState: ObservableObject {
|
|||||||
@Published var alert: AppAlert?
|
@Published var alert: AppAlert?
|
||||||
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
|
@Published var templates: [IPTCTemplate] = [] { didSet { Storage.save(templates, to: Storage.templatesURL) } }
|
||||||
@Published var settings: AppSettings { didSet { Storage.save(settings, to: Storage.settingsURL) } }
|
@Published var settings: AppSettings { didSet { Storage.save(settings, to: Storage.settingsURL) } }
|
||||||
@Published var codes: CodeReplacements { didSet { Storage.save(codes, to: Storage.codesURL) } }
|
/// Teams with player codes (PM: list of code replacement files).
|
||||||
|
@Published var codeLibrary: CodeLibrary {
|
||||||
|
didSet {
|
||||||
|
Storage.save(codeLibrary, to: Storage.codeLibraryURL)
|
||||||
|
codes = codeLibrary.replacements
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Flat lookup of all enabled teams (used for expansion).
|
||||||
|
@Published private(set) var codes: CodeReplacements
|
||||||
@Published var gridColumns = 5
|
@Published var gridColumns = 5
|
||||||
|
|
||||||
// Sheets
|
// Sheets
|
||||||
@@ -96,16 +104,29 @@ final class AppState: ObservableObject {
|
|||||||
private var indexByID: [String: Int] = [:]
|
private var indexByID: [String: Int] = [:]
|
||||||
private var exiftoolInstance: ExifTool?
|
private var exiftoolInstance: ExifTool?
|
||||||
private var lrPollTimer: Timer?
|
private var lrPollTimer: Timer?
|
||||||
|
private var codeReloadTimer: Timer?
|
||||||
private var pendingLRJobs: [String: LightroomJob] = [:]
|
private var pendingLRJobs: [String: LightroomJob] = [:]
|
||||||
@Published var lrPendingCount = 0
|
@Published var lrPendingCount = 0
|
||||||
|
|
||||||
init() {
|
init() {
|
||||||
settings = Storage.load(AppSettings.self, from: Storage.settingsURL) ?? AppSettings()
|
settings = Storage.load(AppSettings.self, from: Storage.settingsURL) ?? AppSettings()
|
||||||
templates = Storage.load([IPTCTemplate].self, from: Storage.templatesURL) ?? []
|
templates = Storage.load([IPTCTemplate].self, from: Storage.templatesURL) ?? []
|
||||||
codes = Storage.load(CodeReplacements.self, from: Storage.codesURL) ?? CodeReplacements()
|
let library = Storage.load(CodeLibrary.self, from: Storage.codeLibraryURL)
|
||||||
|
?? CodeLibrary.migrate(Storage.load(CodeReplacements.self, from: Storage.codesURL) ?? CodeReplacements())
|
||||||
|
codeLibrary = library
|
||||||
|
codes = library.replacements
|
||||||
uploads.state = self
|
uploads.state = self
|
||||||
seedDefaultsIfNeeded()
|
seedDefaultsIfNeeded()
|
||||||
startLightroomPolling()
|
startLightroomPolling()
|
||||||
|
// PM "Automatically reload code replacement files when they change"
|
||||||
|
codeReloadTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
|
||||||
|
Task { @MainActor in
|
||||||
|
guard let self, self.codeLibrary.autoReload else { return }
|
||||||
|
var lib = self.codeLibrary
|
||||||
|
let n = lib.reloadAll(onlyChanged: true)
|
||||||
|
if n > 0 { self.codeLibrary = lib; self.statusText = "Codes: \(n) neue Einträge nachgeladen" }
|
||||||
|
}
|
||||||
|
}
|
||||||
cardMonitor.start { [weak self] dcim in
|
cardMonitor.start { [weak self] dcim in
|
||||||
guard let self, self.settings.autoIngestOnCardMount, self.ingestTask == nil else { return }
|
guard let self, self.settings.autoIngestOnCardMount, self.ingestTask == nil else { return }
|
||||||
self.pendingIngestSources = [dcim]
|
self.pendingIngestSources = [dcim]
|
||||||
@@ -334,6 +355,14 @@ final class AppState: ObservableObject {
|
|||||||
|
|
||||||
// MARK: Ingest (background)
|
// MARK: Ingest (background)
|
||||||
|
|
||||||
|
/// Closes everything of ours that could keep the card busy (open tab on the card, folder watcher).
|
||||||
|
private func ejectReleaseCardHandles(_ volumes: [URL]) {
|
||||||
|
for v in volumes {
|
||||||
|
for tab in tabs where tab.path.hasPrefix(v.path) { closeTab(tab) }
|
||||||
|
if let f = folder, f.path.hasPrefix(v.path) { folderWatcher.watch(nil) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
var ingestRunning: Bool { ingestTask != nil }
|
var ingestRunning: Bool { ingestTask != nil }
|
||||||
|
|
||||||
func startIngest(sources: [URL], fromCards: Bool = true) {
|
func startIngest(sources: [URL], fromCards: Bool = true) {
|
||||||
@@ -341,11 +370,11 @@ final class AppState: ObservableObject {
|
|||||||
let settings = self.settings.ingest
|
let settings = self.settings.ingest
|
||||||
let template = settings.applyTemplate ? templates.first { $0.id == settings.templateID } : nil
|
let template = settings.applyTemplate ? templates.first { $0.id == settings.templateID } : nil
|
||||||
// Only real memory cards are ejected – never the system disk or a drive you ingested a folder from.
|
// Only real memory cards are ejected – never the system disk or a drive you ingested a folder from.
|
||||||
|
// (Some built-in SD readers don't report "ejectable" – any non-system volume under /Volumes counts.)
|
||||||
let volumes: [URL] = fromCards ? Array(Set(sources.compactMap { src -> URL? in
|
let volumes: [URL] = fromCards ? Array(Set(sources.compactMap { src -> URL? in
|
||||||
let keys: Set<URLResourceKey> = [.volumeURLKey, .volumeIsEjectableKey, .volumeIsRemovableKey, .volumeIsRootFileSystemKey]
|
let keys: Set<URLResourceKey> = [.volumeURLKey, .volumeIsRootFileSystemKey]
|
||||||
guard let v = try? src.resourceValues(forKeys: keys), let vol = v.volume,
|
guard let v = try? src.resourceValues(forKeys: keys), let vol = v.volume,
|
||||||
v.volumeIsRootFileSystem != true,
|
v.volumeIsRootFileSystem != true, vol.path.hasPrefix("/Volumes/") else { return nil }
|
||||||
v.volumeIsEjectable == true || v.volumeIsRemovable == true else { return nil }
|
|
||||||
return vol
|
return vol
|
||||||
})) : []
|
})) : []
|
||||||
let taskID = tasks.start(.ingest, title: "Ingest von \(sources.map { $0.deletingLastPathComponent().lastPathComponent }.joined(separator: ", "))") { [weak self] in
|
let taskID = tasks.start(.ingest, title: "Ingest von \(sources.map { $0.deletingLastPathComponent().lastPathComponent }.joined(separator: ", "))") { [weak self] in
|
||||||
@@ -379,6 +408,24 @@ final class AppState: ObservableObject {
|
|||||||
// PM: the sequence continues with the next number next time.
|
// PM: the sequence continues with the next number next time.
|
||||||
if settings.sequenceEnabled { self.settings.ingest.startSequence = result.nextSequence }
|
if settings.sequenceEnabled { self.settings.ingest.startSequence = result.nextSequence }
|
||||||
|
|
||||||
|
// Eject right after copying – everything after this works on the copies only.
|
||||||
|
var ejectNote = ""
|
||||||
|
if settings.unmountAfter && !volumes.isEmpty {
|
||||||
|
self.tasks.update(taskID, detail: "Werfe Karte aus …")
|
||||||
|
self.ejectReleaseCardHandles(volumes)
|
||||||
|
var failed: [String] = []
|
||||||
|
for v in volumes {
|
||||||
|
if let err = await IngestService.eject(volume: v) { failed.append("\(v.lastPathComponent): \(err)") }
|
||||||
|
}
|
||||||
|
if failed.isEmpty {
|
||||||
|
ejectNote = " · Karte ausgeworfen"
|
||||||
|
} else {
|
||||||
|
ejectNote = " · Auswerfen fehlgeschlagen"
|
||||||
|
self.alert = AppAlert(title: "Karte konnte nicht ausgeworfen werden",
|
||||||
|
message: failed.joined(separator: "\n") + "\n\nDie Fotos sind vollständig kopiert. Bitte im Finder auswerfen.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Protected-in-camera photos → PM tag
|
// Protected-in-camera photos → PM tag
|
||||||
if settings.tagLockedPhotos, !result.lockedCopies.isEmpty, let w = self.writer {
|
if settings.tagLockedPhotos, !result.lockedCopies.isEmpty, let w = self.writer {
|
||||||
self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …")
|
self.tasks.update(taskID, detail: "Tagge \(result.lockedCopies.count) gesperrte Fotos …")
|
||||||
@@ -404,24 +451,7 @@ final class AppState: ObservableObject {
|
|||||||
var detail = "\(result.copied.count) Fotos kopiert"
|
var detail = "\(result.copied.count) Fotos kopiert"
|
||||||
if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" }
|
if result.skipped > 0 { detail += ", \(result.skipped) bereits importiert übersprungen" }
|
||||||
if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") }
|
if !result.lockedCopies.isEmpty { detail += ", \(result.lockedCopies.count) gesperrt" + (settings.tagLockedPhotos ? " → getaggt" : "") }
|
||||||
if settings.unmountAfter && !volumes.isEmpty {
|
self.tasks.finish(taskID, detail: detail + ejectNote)
|
||||||
self.tasks.update(taskID, detail: "Werfe Karte aus …")
|
|
||||||
// Let exiftool/QuickLook release the card's files first.
|
|
||||||
try? await Task.sleep(nanoseconds: 800_000_000)
|
|
||||||
var failed: [String] = []
|
|
||||||
for v in volumes {
|
|
||||||
do { try NSWorkspace.shared.unmountAndEjectDevice(at: v) }
|
|
||||||
catch { failed.append("\(v.lastPathComponent): \(error.localizedDescription)") }
|
|
||||||
}
|
|
||||||
if failed.isEmpty {
|
|
||||||
detail += " · Karte ausgeworfen"
|
|
||||||
} else {
|
|
||||||
detail += " · Auswerfen fehlgeschlagen"
|
|
||||||
self.alert = AppAlert(title: "Karte konnte nicht ausgeworfen werden",
|
|
||||||
message: failed.joined(separator: "\n") + "\n\nDie Fotos sind vollständig kopiert. Bitte im Finder auswerfen.")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.tasks.finish(taskID, detail: detail)
|
|
||||||
if let current = self.folder, result.folders.contains(current) {
|
if let current = self.folder, result.folders.contains(current) {
|
||||||
self.metadataCache = nil
|
self.metadataCache = nil
|
||||||
self.refreshFolder()
|
self.refreshFolder()
|
||||||
@@ -746,20 +776,29 @@ final class AppState: ObservableObject {
|
|||||||
do { try XMPTemplateIO.export(t).write(to: url, atomically: true, encoding: .utf8) } catch { report(error) }
|
do { try XMPTemplateIO.export(t).write(to: url, atomically: true, encoding: .utf8) } catch { report(error) }
|
||||||
}
|
}
|
||||||
|
|
||||||
func importCodeReplacements() {
|
/// PM "Add…": each TXT becomes a team – or, if the team exists already, only new players are added.
|
||||||
|
func importCodeFiles(into setID: UUID? = nil) {
|
||||||
let panel = NSOpenPanel()
|
let panel = NSOpenPanel()
|
||||||
panel.allowsMultipleSelection = false
|
panel.allowsMultipleSelection = setID == nil
|
||||||
panel.message = "Code-Ersetzungsdatei (Tab-getrennt, wie in Photo Mechanic)"
|
panel.message = setID == nil ? "Code-Dateien (TXT, Tab-getrennt wie in PM) – jede Datei wird ein Team"
|
||||||
guard panel.runModal() == .OK, let url = panel.url else { return }
|
: "TXT mit neuen Spielern – vorhandene Codes bleiben unverändert"
|
||||||
|
guard panel.runModal() == .OK else { return }
|
||||||
|
var lines: [String] = []
|
||||||
|
for url in panel.urls {
|
||||||
do {
|
do {
|
||||||
let data = try Data(contentsOf: url)
|
let r = try codeLibrary.importFile(url, into: setID)
|
||||||
let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .macOSRoman) ?? ""
|
lines.append("\(r.team): \(r.added) neu" + (r.existing > 0 ? ", \(r.existing) schon vorhanden" : ""))
|
||||||
let delimiter = codes.delimiter
|
|
||||||
codes = CodeReplacements.load(tabDelimited: text)
|
|
||||||
codes.delimiter = delimiter
|
|
||||||
statusText = "\(codes.table.count) Codes geladen"
|
|
||||||
} catch { report(error) }
|
} catch { report(error) }
|
||||||
}
|
}
|
||||||
|
statusText = lines.joined(separator: " · ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func reloadAllCodes() {
|
||||||
|
let n = codeLibrary.reloadAll()
|
||||||
|
statusText = n == 0 ? "Codes: keine neuen Einträge" : "Codes: \(n) neue Einträge"
|
||||||
|
}
|
||||||
|
|
||||||
|
func importCodeReplacements() { importCodeFiles() }
|
||||||
|
|
||||||
// MARK: Lightroom
|
// MARK: Lightroom
|
||||||
|
|
||||||
|
|||||||
@@ -118,6 +118,7 @@ enum Storage {
|
|||||||
static var settingsURL: URL { appSupport.appendingPathComponent("settings.json") }
|
static var settingsURL: URL { appSupport.appendingPathComponent("settings.json") }
|
||||||
static var templatesURL: URL { appSupport.appendingPathComponent("templates.json") }
|
static var templatesURL: URL { appSupport.appendingPathComponent("templates.json") }
|
||||||
static var codesURL: URL { appSupport.appendingPathComponent("codes.json") }
|
static var codesURL: URL { appSupport.appendingPathComponent("codes.json") }
|
||||||
|
static var codeLibraryURL: URL { appSupport.appendingPathComponent("codelibrary.json") }
|
||||||
|
|
||||||
static func load<T: Decodable>(_ type: T.Type, from url: URL) -> T? {
|
static func load<T: Decodable>(_ type: T.Type, from url: URL) -> T? {
|
||||||
guard let d = try? Data(contentsOf: url) else { return nil }
|
guard let d = try? Data(contentsOf: url) else { return nil }
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import AppKit
|
||||||
|
import SwiftUI
|
||||||
|
import LichtkastenCore
|
||||||
|
|
||||||
|
/// Replaces a code right before the cursor (PM-style live code replacement) and keeps the cursor in place.
|
||||||
|
/// Returns true if something was replaced. Undo (⌘Z) restores the code.
|
||||||
|
@MainActor
|
||||||
|
func applyCodeExpansion(_ tv: NSTextView, codes: CodeReplacements?) -> Bool {
|
||||||
|
guard let codes else { return false }
|
||||||
|
let sel = tv.selectedRange()
|
||||||
|
guard sel.length == 0, let (range, rep) = codes.pendingExpansion(in: tv.string, cursor: sel.location) else { return false }
|
||||||
|
let afterReplaced = sel.location - (range.location + range.length) // e.g. the typed space after "w10"
|
||||||
|
tv.insertText(rep, replacementRange: range)
|
||||||
|
let newCursor = range.location + (rep as NSString).length + afterReplaced
|
||||||
|
tv.setSelectedRange(NSRange(location: min(newCursor, (tv.string as NSString).length), length: 0))
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multi-line field (caption, keywords …) with live code replacement.
|
||||||
|
struct CodeTextView: NSViewRepresentable {
|
||||||
|
@Binding var text: String
|
||||||
|
var codes: CodeReplacements?
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> NSScrollView {
|
||||||
|
let sv = NSTextView.scrollableTextView()
|
||||||
|
sv.borderType = .bezelBorder
|
||||||
|
sv.hasVerticalScroller = true
|
||||||
|
guard let tv = sv.documentView as? NSTextView else { return sv }
|
||||||
|
tv.delegate = context.coordinator
|
||||||
|
tv.isRichText = false
|
||||||
|
tv.importsGraphics = false
|
||||||
|
tv.allowsUndo = true
|
||||||
|
tv.font = .systemFont(ofSize: 13)
|
||||||
|
tv.isAutomaticQuoteSubstitutionEnabled = false
|
||||||
|
tv.isAutomaticDashSubstitutionEnabled = false
|
||||||
|
tv.isAutomaticTextReplacementEnabled = false
|
||||||
|
tv.isContinuousSpellCheckingEnabled = true
|
||||||
|
tv.textContainerInset = NSSize(width: 3, height: 4)
|
||||||
|
tv.string = text
|
||||||
|
return sv
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ sv: NSScrollView, context: Context) {
|
||||||
|
context.coordinator.parent = self
|
||||||
|
guard let tv = sv.documentView as? NSTextView, tv.string != text, !context.coordinator.editing else { return }
|
||||||
|
tv.string = text
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||||
|
var parent: CodeTextView
|
||||||
|
var expanding = false
|
||||||
|
var editing = false
|
||||||
|
init(_ p: CodeTextView) { parent = p }
|
||||||
|
|
||||||
|
func textDidChange(_ notification: Notification) {
|
||||||
|
guard let tv = notification.object as? NSTextView else { return }
|
||||||
|
if !expanding {
|
||||||
|
expanding = true
|
||||||
|
MainActor.assumeIsolated { _ = applyCodeExpansion(tv, codes: parent.codes) }
|
||||||
|
expanding = false
|
||||||
|
}
|
||||||
|
editing = true
|
||||||
|
parent.text = tv.string
|
||||||
|
DispatchQueue.main.async { self.editing = false }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Single-line field with live code replacement (event, city, test field …).
|
||||||
|
struct CodeTextField: NSViewRepresentable {
|
||||||
|
@Binding var text: String
|
||||||
|
var codes: CodeReplacements?
|
||||||
|
var placeholder: String = ""
|
||||||
|
|
||||||
|
func makeCoordinator() -> Coordinator { Coordinator(self) }
|
||||||
|
|
||||||
|
func makeNSView(context: Context) -> NSTextField {
|
||||||
|
let f = NSTextField(string: text)
|
||||||
|
f.delegate = context.coordinator
|
||||||
|
f.placeholderString = placeholder
|
||||||
|
f.bezelStyle = .roundedBezel
|
||||||
|
f.lineBreakMode = .byTruncatingTail
|
||||||
|
f.cell?.isScrollable = true
|
||||||
|
f.font = .systemFont(ofSize: 13)
|
||||||
|
return f
|
||||||
|
}
|
||||||
|
|
||||||
|
func updateNSView(_ f: NSTextField, context: Context) {
|
||||||
|
context.coordinator.parent = self
|
||||||
|
f.placeholderString = placeholder
|
||||||
|
if f.stringValue != text, f.currentEditor() == nil { f.stringValue = text }
|
||||||
|
}
|
||||||
|
|
||||||
|
final class Coordinator: NSObject, NSTextFieldDelegate {
|
||||||
|
var parent: CodeTextField
|
||||||
|
var expanding = false
|
||||||
|
init(_ p: CodeTextField) { parent = p }
|
||||||
|
|
||||||
|
func controlTextDidChange(_ obj: Notification) {
|
||||||
|
guard let f = obj.object as? NSTextField else { return }
|
||||||
|
if !expanding, let editor = f.currentEditor() as? NSTextView {
|
||||||
|
expanding = true
|
||||||
|
MainActor.assumeIsolated { _ = applyCodeExpansion(editor, codes: parent.codes) }
|
||||||
|
expanding = false
|
||||||
|
}
|
||||||
|
parent.text = f.stringValue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,93 +1,190 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import UniformTypeIdentifiers
|
|
||||||
import LichtkastenCore
|
import LichtkastenCore
|
||||||
|
|
||||||
/// PM "Code Replacements": table editor, import/export of PM's tab-delimited file, live test.
|
/// PM "Code Replacement" – but with teams stored in the app:
|
||||||
|
/// left the teams (enable checkbox like PM's file list), right the players of the selected team.
|
||||||
struct CodesWindow: View {
|
struct CodesWindow: View {
|
||||||
@EnvironmentObject var state: AppState
|
@EnvironmentObject var state: AppState
|
||||||
@State private var rows: [Row] = []
|
@State private var selectedTeam: UUID?
|
||||||
@State private var selection: Set<Row.ID> = []
|
@State private var selectedRows: Set<UUID> = []
|
||||||
@State private var test = "\\vfl\\ gegen \\tsg\\"
|
@State private var newCode = ""
|
||||||
|
@State private var newText = ""
|
||||||
|
@State private var test = "w10 trifft gegen h10, "
|
||||||
|
@State private var search = ""
|
||||||
|
|
||||||
struct Row: Identifiable, Hashable {
|
private var teamIndex: Int? { state.codeLibrary.sets.firstIndex { $0.id == selectedTeam } }
|
||||||
let id = UUID()
|
|
||||||
var code: String
|
|
||||||
var columns: String // replacement columns separated by " | "
|
|
||||||
}
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
VStack(alignment: .leading, spacing: 10) {
|
VStack(alignment: .leading, spacing: 10) {
|
||||||
HStack {
|
Text("Diese Teams werden für Code-Ersetzungen verwendet. Bei doppelten Codes gewinnt das obere Team.")
|
||||||
Text("Code-Ersetzungen").font(.title3.bold())
|
.font(.callout).foregroundStyle(.secondary)
|
||||||
Spacer()
|
HSplitView {
|
||||||
Text("Trennzeichen:")
|
teamList.frame(minWidth: 300, idealWidth: 360)
|
||||||
TextField("", text: Binding(get: { String(state.codes.delimiter) },
|
playerTable.frame(minWidth: 420)
|
||||||
set: { if let c = $0.last { state.codes.delimiter = c } }))
|
|
||||||
.frame(width: 30)
|
|
||||||
}
|
}
|
||||||
Text("Tippe im IPTC-Feld \\code\\ – sobald das schließende Trennzeichen getippt wird, ersetzt Lichtkasten den Code (wie PM). \\code#2\\ nimmt Spalte 2.")
|
.frame(minHeight: 320)
|
||||||
.font(.caption).foregroundStyle(.secondary)
|
optionsRow
|
||||||
|
testRow
|
||||||
|
}
|
||||||
|
.padding(16)
|
||||||
|
.onAppear { if selectedTeam == nil { selectedTeam = state.codeLibrary.sets.first?.id } }
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Teams (PM file list)
|
||||||
|
|
||||||
|
private var teamList: some View {
|
||||||
|
VStack(spacing: 6) {
|
||||||
|
List(selection: $selectedTeam) {
|
||||||
|
ForEach($state.codeLibrary.sets) { $set in
|
||||||
HStack {
|
HStack {
|
||||||
Text("Code").frame(width: 140, alignment: .leading)
|
Toggle("", isOn: $set.enabled).toggleStyle(.checkbox).labelsHidden()
|
||||||
|
.help("Aktiv (PM: Enable)")
|
||||||
|
VStack(alignment: .leading, spacing: 1) {
|
||||||
|
Text(set.name).lineLimit(1)
|
||||||
|
Text(set.sourcePath.map { URL(fileURLWithPath: $0).lastPathComponent } ?? "manuell")
|
||||||
|
.font(.caption2).foregroundStyle(.secondary).lineLimit(1)
|
||||||
|
}
|
||||||
|
Spacer()
|
||||||
|
Text("\(set.entries.count)").font(.caption.monospacedDigit()).foregroundStyle(.secondary)
|
||||||
|
}
|
||||||
|
.tag(set.id)
|
||||||
|
.contextMenu {
|
||||||
|
Button("Neue Spieler aus TXT nachladen …") { state.importCodeFiles(into: set.id) }
|
||||||
|
Button("Im Finder zeigen") {
|
||||||
|
if let p = set.sourcePath { NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: p)]) }
|
||||||
|
}.disabled(set.sourcePath == nil)
|
||||||
|
Button("Löschen", role: .destructive) { remove(set.id) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.onMove { state.codeLibrary.sets.move(fromOffsets: $0, toOffset: $1) }
|
||||||
|
}
|
||||||
|
HStack(spacing: 6) {
|
||||||
|
Button("Hinzufügen …") { state.importCodeFiles() }
|
||||||
|
.help("TXT-Dateien als Teams importieren (wie PM „Add…“)")
|
||||||
|
Button("Neues Team") {
|
||||||
|
let s = CodeSet(name: "Neues Team")
|
||||||
|
state.codeLibrary.sets.append(s)
|
||||||
|
selectedTeam = s.id
|
||||||
|
}
|
||||||
|
Button("Entfernen") { if let id = selectedTeam { remove(id) } }.disabled(selectedTeam == nil)
|
||||||
|
Spacer()
|
||||||
|
Button("Alle neu laden") { state.reloadAllCodes() }
|
||||||
|
.help("Liest die TXT-Dateien erneut – nur neue Spieler kommen hinzu")
|
||||||
|
}
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Players of the selected team
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
|
private var playerTable: some View {
|
||||||
|
if let i = teamIndex {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
HStack {
|
||||||
|
TextField("Teamname", text: $state.codeLibrary.sets[i].name).font(.headline).textFieldStyle(.roundedBorder)
|
||||||
|
Button("TXT nachladen …") { state.importCodeFiles(into: state.codeLibrary.sets[i].id) }
|
||||||
|
.help("Neue Spieler aus einer TXT hinzufügen – vorhandene bleiben unverändert")
|
||||||
|
}
|
||||||
|
TextField("Suchen", text: $search).textFieldStyle(.roundedBorder)
|
||||||
|
HStack {
|
||||||
|
Text("Code").frame(width: 90, alignment: .leading)
|
||||||
Text("Ersetzung (weitere Spalten mit „ | “ trennen)")
|
Text("Ersetzung (weitere Spalten mit „ | “ trennen)")
|
||||||
}
|
}
|
||||||
.font(.caption.bold())
|
.font(.caption.bold())
|
||||||
List(selection: $selection) {
|
List(selection: $selectedRows) {
|
||||||
ForEach($rows) { $r in
|
ForEach($state.codeLibrary.sets[i].entries) { $e in
|
||||||
|
if search.isEmpty || e.code.localizedCaseInsensitiveContains(search)
|
||||||
|
|| e.columns.joined().localizedCaseInsensitiveContains(search) {
|
||||||
HStack {
|
HStack {
|
||||||
TextField("", text: $r.code).frame(width: 140)
|
TextField("", text: $e.code).frame(width: 90)
|
||||||
TextField("", text: $r.columns)
|
TextField("", text: Binding(get: { e.columns.joined(separator: " | ") },
|
||||||
|
set: { e.columns = $0.components(separatedBy: " | ") }))
|
||||||
}
|
}
|
||||||
.tag(r.id)
|
.tag(e.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.onChange(of: rows) { _, _ in commit() }
|
}
|
||||||
|
// Quick add (e.g. a new player during the game)
|
||||||
|
HStack {
|
||||||
|
TextField("w23", text: $newCode).frame(width: 90).textFieldStyle(.roundedBorder)
|
||||||
|
TextField("Vorname Nachname (VfL Wolfsburg, 23)", text: $newText).textFieldStyle(.roundedBorder)
|
||||||
|
.onSubmit(addPlayer)
|
||||||
|
Button("Hinzufügen", action: addPlayer).disabled(newCode.isEmpty || newText.isEmpty)
|
||||||
|
Button {
|
||||||
|
state.codeLibrary.sets[i].entries.removeAll { selectedRows.contains($0.id) }
|
||||||
|
selectedRows = []
|
||||||
|
} label: { Image(systemName: "minus") }
|
||||||
|
.disabled(selectedRows.isEmpty)
|
||||||
|
.help("Ausgewählte Spieler löschen")
|
||||||
|
}
|
||||||
HStack {
|
HStack {
|
||||||
Button { rows.append(Row(code: "", columns: "")) } label: { Image(systemName: "plus") }
|
|
||||||
Button { rows.removeAll { selection.contains($0.id) }; commit() } label: { Image(systemName: "minus") }
|
|
||||||
.disabled(selection.isEmpty)
|
|
||||||
Spacer()
|
Spacer()
|
||||||
Button("Datei laden (PM-Format) …") { state.importCodeReplacements(); load() }
|
Button("Als TXT exportieren …") { export(state.codeLibrary.sets[i]) }.controlSize(.small)
|
||||||
Button("Exportieren …") { export() }
|
|
||||||
}
|
}
|
||||||
Divider()
|
}
|
||||||
|
.padding(.leading, 8)
|
||||||
|
} else {
|
||||||
|
Text("Team auswählen oder hinzufügen").foregroundStyle(.secondary)
|
||||||
|
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Options (PM bottom row)
|
||||||
|
|
||||||
|
private var optionsRow: some View {
|
||||||
|
HStack(spacing: 16) {
|
||||||
|
Toggle("TXT-Dateien automatisch neu laden, wenn sie sich ändern", isOn: $state.codeLibrary.autoReload)
|
||||||
|
Spacer()
|
||||||
|
Toggle("Codes ohne Trennzeichen (w10 + Leertaste)", isOn: $state.codeLibrary.bareCodes)
|
||||||
|
HStack(spacing: 4) {
|
||||||
|
Text("Trennzeichen:")
|
||||||
|
TextField("", text: Binding(get: { state.codeLibrary.delimiter },
|
||||||
|
set: { if let c = $0.last { state.codeLibrary.delimiter = String(c) } }))
|
||||||
|
.frame(width: 28)
|
||||||
|
.textFieldStyle(.roundedBorder)
|
||||||
|
}
|
||||||
|
HStack(spacing: 4) {
|
||||||
|
Text("Standard-Ersetzung:")
|
||||||
|
TextField("", text: $state.codeLibrary.defaultReplacement).frame(width: 140).textFieldStyle(.roundedBorder)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.font(.callout)
|
||||||
|
}
|
||||||
|
|
||||||
|
private var testRow: some View {
|
||||||
HStack {
|
HStack {
|
||||||
TextField("Test", text: $test).textFieldStyle(.roundedBorder)
|
Text("Test:").foregroundStyle(.secondary)
|
||||||
Image(systemName: "arrow.right")
|
CodeTextField(text: $test, codes: state.codes)
|
||||||
Text(state.codes.expand(test)).textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)
|
.frame(height: 24)
|
||||||
|
Text("Tippe z. B. „w10“ + Leertaste oder „\(state.codeLibrary.delimiter)w10\(state.codeLibrary.delimiter)“")
|
||||||
|
.font(.caption).foregroundStyle(.secondary)
|
||||||
}
|
}
|
||||||
Divider()
|
|
||||||
DisclosureGroup("Variablen") {
|
|
||||||
LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], alignment: .leading) {
|
|
||||||
ForEach(VariableExpander.documented, id: \.0) { v in
|
|
||||||
HStack { Text(v.0).font(.system(.caption, design: .monospaced)).textSelection(.enabled); Text(v.1).font(.caption).foregroundStyle(.secondary) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.padding(16)
|
|
||||||
.onAppear(perform: load)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func load() {
|
// MARK: Actions
|
||||||
rows = state.codes.table.sorted { $0.key < $1.key }.map { Row(code: $0.key, columns: $0.value.joined(separator: " | ")) }
|
|
||||||
|
private func addPlayer() {
|
||||||
|
guard let i = teamIndex, !newCode.isEmpty, !newText.isEmpty else { return }
|
||||||
|
let r = state.codeLibrary.sets[i].merge([CodeEntry(code: newCode.trimmingCharacters(in: .whitespaces),
|
||||||
|
columns: newText.components(separatedBy: " | "))])
|
||||||
|
if r.added == 0 {
|
||||||
|
state.alert = AppAlert(title: "Code existiert schon", message: "„\(newCode)“ ist in diesem Team bereits vergeben.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newCode = ""; newText = ""
|
||||||
}
|
}
|
||||||
|
|
||||||
private func commit() {
|
private func remove(_ id: UUID) {
|
||||||
var table: [String: [String]] = [:]
|
state.codeLibrary.sets.removeAll { $0.id == id }
|
||||||
for r in rows where !r.code.trimmingCharacters(in: .whitespaces).isEmpty {
|
if selectedTeam == id { selectedTeam = state.codeLibrary.sets.first?.id }
|
||||||
table[r.code.trimmingCharacters(in: .whitespaces).lowercased()] =
|
|
||||||
r.columns.components(separatedBy: " | ").map { $0.trimmingCharacters(in: .whitespaces) }
|
|
||||||
}
|
|
||||||
if table != state.codes.table { state.codes.table = table }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private func export() {
|
private func export(_ set: CodeSet) {
|
||||||
let p = NSSavePanel()
|
let p = NSSavePanel()
|
||||||
p.nameFieldStringValue = "Codes.txt"
|
p.nameFieldStringValue = set.name + ".txt"
|
||||||
guard p.runModal() == .OK, let url = p.url else { return }
|
guard p.runModal() == .OK, let url = p.url else { return }
|
||||||
let text = state.codes.table.sorted { $0.key < $1.key }
|
let text = set.entries.map { ([$0.code] + $0.columns).joined(separator: "\t") }.joined(separator: "\n") + "\n"
|
||||||
.map { ([$0.key] + $0.value).joined(separator: "\t") }.joined(separator: "\n") + "\n"
|
|
||||||
try? text.write(to: url, atomically: true, encoding: .utf8)
|
try? text.write(to: url, atomically: true, encoding: .utf8)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -72,7 +72,7 @@ struct PMMetadataForm: View {
|
|||||||
VStack(alignment: .leading, spacing: 6) {
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
PMSectionHeader(title: section.rawValue)
|
PMSectionHeader(title: section.rawValue)
|
||||||
ForEach(IPTCField.all.filter { $0.section == section }) { field in
|
ForEach(IPTCField.all.filter { $0.section == section }) { field in
|
||||||
PMFieldRow(field: field, text: binding(field),
|
PMFieldRow(field: field, text: binding(field), codes: codes,
|
||||||
isMixed: mixed.contains(field.id) && !dirty.contains(field.id),
|
isMixed: mixed.contains(field.id) && !dirty.contains(field.id),
|
||||||
isDirty: dirty.contains(field.id),
|
isDirty: dirty.contains(field.id),
|
||||||
applied: appliedBinding(field))
|
applied: appliedBinding(field))
|
||||||
@@ -89,12 +89,8 @@ struct PMMetadataForm: View {
|
|||||||
|
|
||||||
private func binding(_ f: IPTCField) -> Binding<String> {
|
private func binding(_ f: IPTCField) -> Binding<String> {
|
||||||
Binding(get: { texts[f.id] ?? "" },
|
Binding(get: { texts[f.id] ?? "" },
|
||||||
set: { new in
|
set: { value in
|
||||||
var value = new
|
// Code replacement happens inside the text views (cursor stays in place).
|
||||||
// PM code replacement while typing: "\bvb\" expands as soon as the closing delimiter is typed.
|
|
||||||
if let codes, !codes.table.isEmpty, new.last == codes.delimiter, new.count > (texts[f.id]?.count ?? 0) {
|
|
||||||
value = codes.expand(new)
|
|
||||||
}
|
|
||||||
texts[f.id] = value
|
texts[f.id] = value
|
||||||
// Editing a field ticks its checkbox (PM behaviour).
|
// Editing a field ticks its checkbox (PM behaviour).
|
||||||
applied?.wrappedValue.insert(f.id)
|
applied?.wrappedValue.insert(f.id)
|
||||||
@@ -106,6 +102,7 @@ struct PMMetadataForm: View {
|
|||||||
struct PMFieldRow: View {
|
struct PMFieldRow: View {
|
||||||
let field: IPTCField
|
let field: IPTCField
|
||||||
@Binding var text: String
|
@Binding var text: String
|
||||||
|
var codes: CodeReplacements?
|
||||||
let isMixed: Bool
|
let isMixed: Bool
|
||||||
let isDirty: Bool
|
let isDirty: Bool
|
||||||
let applied: Binding<Bool>?
|
let applied: Binding<Bool>?
|
||||||
@@ -141,21 +138,16 @@ struct PMFieldRow: View {
|
|||||||
if field.id == "dateCreated" {
|
if field.id == "dateCreated" {
|
||||||
DateFieldEditor(text: $text)
|
DateFieldEditor(text: $text)
|
||||||
} else if let h = height {
|
} else if let h = height {
|
||||||
TextEditor(text: $text)
|
CodeTextView(text: $text, codes: codes)
|
||||||
.font(.system(size: 13))
|
|
||||||
.scrollContentBackground(.hidden)
|
|
||||||
.padding(4)
|
|
||||||
.background(Color(nsColor: .textBackgroundColor))
|
|
||||||
.overlay(alignment: .topLeading) {
|
.overlay(alignment: .topLeading) {
|
||||||
if isMixed && text.isEmpty {
|
if isMixed && text.isEmpty {
|
||||||
Text("‹mehrere Werte›").foregroundStyle(.tertiary).padding(8).allowsHitTesting(false)
|
Text("‹mehrere Werte›").foregroundStyle(.tertiary).padding(8).allowsHitTesting(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.overlay(RoundedRectangle(cornerRadius: 3).stroke(Color.secondary.opacity(0.4)))
|
|
||||||
.frame(height: h)
|
.frame(height: h)
|
||||||
} else {
|
} else {
|
||||||
TextField(isMixed ? "‹mehrere Werte›" : "", text: $text)
|
CodeTextField(text: $text, codes: codes, placeholder: isMixed ? "‹mehrere Werte›" : "")
|
||||||
.textFieldStyle(.roundedBorder)
|
.frame(height: 22)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxWidth: .infinity)
|
.frame(maxWidth: .infinity)
|
||||||
|
|||||||
@@ -273,21 +273,12 @@ struct LightroomSettingsView: View {
|
|||||||
|
|
||||||
struct CodesSettings: View {
|
struct CodesSettings: View {
|
||||||
@EnvironmentObject var state: AppState
|
@EnvironmentObject var state: AppState
|
||||||
@State private var testInput = "\\bvb\\ gegen \\s04\\"
|
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
Form {
|
Form {
|
||||||
Section("Code-Ersetzung (wie Photo Mechanic)") {
|
Section("Code-Ersetzung") {
|
||||||
HStack {
|
Text("\(state.codeLibrary.sets.filter(\.enabled).count) von \(state.codeLibrary.sets.count) Teams aktiv · \(state.codes.table.count) Codes")
|
||||||
Text("\(state.codes.table.count) Codes geladen")
|
Button("Code-Ersetzungen öffnen … (⌘⇧K)") { state.openWindow("codes") }
|
||||||
Spacer()
|
|
||||||
Button("Datei laden …") { state.importCodeReplacements() }
|
|
||||||
Button("Leeren") { state.codes = CodeReplacements() }
|
|
||||||
}
|
|
||||||
Text("Tab-getrennte Textdatei: Code ⇥ Ersetzung ⇥ weitere Spalten. Im Text: \\code\\ oder \\code#2\\ für Spalte 2.")
|
|
||||||
.font(.caption).foregroundStyle(.secondary)
|
|
||||||
TextField("Test", text: $testInput)
|
|
||||||
Text(state.codes.expand(testInput)).font(.callout).textSelection(.enabled)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.formStyle(.grouped)
|
.formStyle(.grouped)
|
||||||
|
|||||||
@@ -254,6 +254,22 @@ public enum IngestService {
|
|||||||
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
|
lockedCopies: lockedCopies, nextSequence: seq, skipped: skipped)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Ejects a memory card via `diskutil eject` (more reliable than NSWorkspace, reports who blocks it).
|
||||||
|
/// Retries a few times – right after an ingest Spotlight (mds) or QuickLook often still hold the card.
|
||||||
|
/// Returns nil on success, otherwise the error text.
|
||||||
|
public static func eject(volume: URL, attempts: Int = 4) async -> String? {
|
||||||
|
var last = ""
|
||||||
|
for attempt in 0..<attempts {
|
||||||
|
if attempt > 0 { try? await Task.sleep(nanoseconds: 2_000_000_000) }
|
||||||
|
if let r = try? await FTPUploader.run("/usr/sbin/diskutil", ["eject", volume.path], stdin: nil) {
|
||||||
|
if r.status == 0 { return nil }
|
||||||
|
last = (r.stderr + r.stdout).trimmingCharacters(in: .whitespacesAndNewlines)
|
||||||
|
}
|
||||||
|
if !FileManager.default.fileExists(atPath: volume.path) { return nil } // already gone
|
||||||
|
}
|
||||||
|
return last.isEmpty ? "diskutil eject fehlgeschlagen" : last
|
||||||
|
}
|
||||||
|
|
||||||
static func sameSize(_ a: URL, _ b: URL) -> Bool {
|
static func sameSize(_ a: URL, _ b: URL) -> Bool {
|
||||||
func size(_ u: URL) -> Int64? {
|
func size(_ u: URL) -> Int64? {
|
||||||
guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil }
|
guard let attrs = try? FileManager.default.attributesOfItem(atPath: u.path) else { return nil }
|
||||||
|
|||||||
@@ -0,0 +1,142 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// One code line: "w10 ⇥ Svenja Huth (VfL Wolfsburg, 10) ⇥ …"
|
||||||
|
public struct CodeEntry: Codable, Hashable, Identifiable, Sendable {
|
||||||
|
public var id = UUID()
|
||||||
|
public var code: String
|
||||||
|
public var columns: [String]
|
||||||
|
|
||||||
|
public init(code: String, columns: [String]) { self.code = code; self.columns = columns }
|
||||||
|
|
||||||
|
enum CodingKeys: String, CodingKey { case code, columns }
|
||||||
|
public init(from decoder: Decoder) throws {
|
||||||
|
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
code = try c.decode(String.self, forKey: .code)
|
||||||
|
columns = try c.decodeIfPresent([String].self, forKey: .columns) ?? []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A team (or any group of codes) – like one enabled file in PM's Code Replacement list,
|
||||||
|
/// but stored in the app so players can be added by hand and merged from new TXT files.
|
||||||
|
public struct CodeSet: Codable, Hashable, Identifiable, Sendable {
|
||||||
|
public var id = UUID()
|
||||||
|
public var name: String
|
||||||
|
public var enabled = true
|
||||||
|
public var entries: [CodeEntry] = []
|
||||||
|
/// TXT file the team was imported from (for "Reload" / auto reload).
|
||||||
|
public var sourcePath: String?
|
||||||
|
public var sourceModified: Date?
|
||||||
|
|
||||||
|
public init(name: String, entries: [CodeEntry] = [], sourcePath: String? = nil) {
|
||||||
|
self.name = name; self.entries = entries; self.sourcePath = sourcePath
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adds only codes that are not in the team yet (existing players stay untouched).
|
||||||
|
@discardableResult
|
||||||
|
public mutating func merge(_ new: [CodeEntry]) -> (added: Int, existing: Int) {
|
||||||
|
var known = Set(entries.map { $0.code.lowercased() })
|
||||||
|
var added = 0, existing = 0
|
||||||
|
for e in new {
|
||||||
|
let k = e.code.lowercased()
|
||||||
|
if known.contains(k) { existing += 1; continue }
|
||||||
|
entries.append(e)
|
||||||
|
known.insert(k)
|
||||||
|
added += 1
|
||||||
|
}
|
||||||
|
return (added, existing)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct CodeLibrary: Codable, Sendable {
|
||||||
|
public var sets: [CodeSet] = []
|
||||||
|
public var delimiter: String = "\\"
|
||||||
|
public var defaultReplacement = ""
|
||||||
|
public var bareCodes = true
|
||||||
|
public var autoReload = false
|
||||||
|
|
||||||
|
public init() {}
|
||||||
|
|
||||||
|
/// Flat lookup table for the enabled teams – first team in the list wins on duplicate codes.
|
||||||
|
public var replacements: CodeReplacements {
|
||||||
|
var table: [String: [String]] = [:]
|
||||||
|
for set in sets where set.enabled {
|
||||||
|
for e in set.entries where table[e.code.lowercased()] == nil { table[e.code.lowercased()] = e.columns }
|
||||||
|
}
|
||||||
|
var r = CodeReplacements(table: table)
|
||||||
|
r.delimiter = delimiter.first ?? "\\"
|
||||||
|
r.defaultReplacement = defaultReplacement
|
||||||
|
r.bareCodes = bareCodes
|
||||||
|
return r
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses PM's tab-delimited code file (code ⇥ replacement ⇥ more columns). '#' lines are comments.
|
||||||
|
public static func parse(_ text: String) -> [CodeEntry] {
|
||||||
|
var out: [CodeEntry] = []
|
||||||
|
for line in text.components(separatedBy: .newlines) {
|
||||||
|
let trimmed = line.trimmingCharacters(in: .whitespaces)
|
||||||
|
if trimmed.isEmpty || trimmed.hasPrefix("#") { continue }
|
||||||
|
let cols = line.components(separatedBy: "\t")
|
||||||
|
guard cols.count >= 2 else { continue }
|
||||||
|
let code = cols[0].trimmingCharacters(in: .whitespaces)
|
||||||
|
guard !code.isEmpty else { continue }
|
||||||
|
out.append(CodeEntry(code: code, columns: cols.dropFirst().map { $0.trimmingCharacters(in: .whitespaces) }))
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads a code file in UTF-8, UTF-16 (PM sometimes saves that), Windows-1252 or Mac Roman.
|
||||||
|
public static func readText(_ url: URL) throws -> String {
|
||||||
|
let data = try Data(contentsOf: url)
|
||||||
|
for enc in [String.Encoding.utf8, .utf16, .windowsCP1252, .macOSRoman] {
|
||||||
|
if let s = String(data: data, encoding: enc) { return s }
|
||||||
|
}
|
||||||
|
return String(decoding: data, as: UTF8.self)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Imports a TXT: merges into the team with the same source file (or name), otherwise creates a new team.
|
||||||
|
@discardableResult
|
||||||
|
public mutating func importFile(_ url: URL, into setID: UUID? = nil) throws -> (team: String, added: Int, existing: Int) {
|
||||||
|
let entries = CodeLibrary.parse(try CodeLibrary.readText(url))
|
||||||
|
let mod = (try? FileManager.default.attributesOfItem(atPath: url.path)[.modificationDate]) as? Date
|
||||||
|
let name = url.deletingPathExtension().lastPathComponent.replacingOccurrences(of: "_", with: " ")
|
||||||
|
let idx = setID.flatMap { id in sets.firstIndex { $0.id == id } }
|
||||||
|
?? sets.firstIndex { $0.sourcePath == url.path }
|
||||||
|
?? sets.firstIndex { $0.name.caseInsensitiveCompare(name) == .orderedSame }
|
||||||
|
if let i = idx {
|
||||||
|
let r = sets[i].merge(entries)
|
||||||
|
if sets[i].sourcePath == nil || setID == nil { sets[i].sourcePath = url.path }
|
||||||
|
sets[i].sourceModified = mod
|
||||||
|
return (sets[i].name, r.added, r.existing)
|
||||||
|
}
|
||||||
|
var set = CodeSet(name: name, sourcePath: url.path)
|
||||||
|
let r = set.merge(entries)
|
||||||
|
set.sourceModified = mod
|
||||||
|
sets.append(set)
|
||||||
|
return (name, r.added, r.existing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Re-reads all source files (PM "Reload All" / auto reload) – only new codes are added.
|
||||||
|
@discardableResult
|
||||||
|
public mutating func reloadAll(onlyChanged: Bool = false) -> Int {
|
||||||
|
var added = 0
|
||||||
|
for i in sets.indices {
|
||||||
|
guard let path = sets[i].sourcePath, FileManager.default.fileExists(atPath: path) else { continue }
|
||||||
|
let mod = (try? FileManager.default.attributesOfItem(atPath: path)[.modificationDate]) as? Date
|
||||||
|
if onlyChanged, let m = mod, let known = sets[i].sourceModified, m <= known { continue }
|
||||||
|
guard let text = try? CodeLibrary.readText(URL(fileURLWithPath: path)) else { continue }
|
||||||
|
added += sets[i].merge(CodeLibrary.parse(text)).added
|
||||||
|
sets[i].sourceModified = mod
|
||||||
|
}
|
||||||
|
return added
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Migration from the old flat code table.
|
||||||
|
public static func migrate(_ old: CodeReplacements) -> CodeLibrary {
|
||||||
|
var lib = CodeLibrary()
|
||||||
|
lib.delimiter = String(old.delimiter)
|
||||||
|
if !old.table.isEmpty {
|
||||||
|
lib.sets = [CodeSet(name: "Importiert", entries: old.table.sorted { $0.key < $1.key }.map { CodeEntry(code: $0.key, columns: $0.value) })]
|
||||||
|
}
|
||||||
|
return lib
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -88,8 +88,12 @@ public struct CodeReplacements: Codable, Sendable {
|
|||||||
public var delimiter: Character = "\\"
|
public var delimiter: Character = "\\"
|
||||||
public var table: [String: [String]] = [:]
|
public var table: [String: [String]] = [:]
|
||||||
public var caseSensitive = false
|
public var caseSensitive = false
|
||||||
|
/// PM "Default replacement": used when a \code\ is not found (empty = leave the code as typed).
|
||||||
|
public var defaultReplacement = ""
|
||||||
|
/// Codes without delimiter: "w10" + space/comma/… expands (only while typing).
|
||||||
|
public var bareCodes = true
|
||||||
|
|
||||||
enum CodingKeys: String, CodingKey { case delimiter, table, caseSensitive }
|
enum CodingKeys: String, CodingKey { case delimiter, table, caseSensitive, defaultReplacement, bareCodes }
|
||||||
|
|
||||||
public init(table: [String: [String]] = [:]) { self.table = table }
|
public init(table: [String: [String]] = [:]) { self.table = table }
|
||||||
|
|
||||||
@@ -99,6 +103,8 @@ public struct CodeReplacements: Codable, Sendable {
|
|||||||
delimiter = d.first ?? "\\"
|
delimiter = d.first ?? "\\"
|
||||||
table = try c.decodeIfPresent([String: [String]].self, forKey: .table) ?? [:]
|
table = try c.decodeIfPresent([String: [String]].self, forKey: .table) ?? [:]
|
||||||
caseSensitive = try c.decodeIfPresent(Bool.self, forKey: .caseSensitive) ?? false
|
caseSensitive = try c.decodeIfPresent(Bool.self, forKey: .caseSensitive) ?? false
|
||||||
|
defaultReplacement = try c.decodeIfPresent(String.self, forKey: .defaultReplacement) ?? ""
|
||||||
|
bareCodes = try c.decodeIfPresent(Bool.self, forKey: .bareCodes) ?? true
|
||||||
}
|
}
|
||||||
|
|
||||||
public func encode(to encoder: Encoder) throws {
|
public func encode(to encoder: Encoder) throws {
|
||||||
@@ -106,6 +112,8 @@ public struct CodeReplacements: Codable, Sendable {
|
|||||||
try c.encode(String(delimiter), forKey: .delimiter)
|
try c.encode(String(delimiter), forKey: .delimiter)
|
||||||
try c.encode(table, forKey: .table)
|
try c.encode(table, forKey: .table)
|
||||||
try c.encode(caseSensitive, forKey: .caseSensitive)
|
try c.encode(caseSensitive, forKey: .caseSensitive)
|
||||||
|
try c.encode(defaultReplacement, forKey: .defaultReplacement)
|
||||||
|
try c.encode(bareCodes, forKey: .bareCodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a tab-delimited PM code replacement file. Lines starting with '#' are ignored.
|
/// Loads a tab-delimited PM code replacement file. Lines starting with '#' are ignored.
|
||||||
@@ -123,7 +131,7 @@ public struct CodeReplacements: Codable, Sendable {
|
|||||||
return CodeReplacements(table: table)
|
return CodeReplacements(table: table)
|
||||||
}
|
}
|
||||||
|
|
||||||
func lookup(_ code: String) -> String? {
|
public func lookup(_ code: String) -> String? {
|
||||||
var name = code
|
var name = code
|
||||||
var column = 1
|
var column = 1
|
||||||
if let hash = code.lastIndex(of: "#"), let n = Int(code[code.index(after: hash)...]) {
|
if let hash = code.lastIndex(of: "#"), let n = Int(code[code.index(after: hash)...]) {
|
||||||
@@ -136,6 +144,48 @@ public struct CodeReplacements: Codable, Sendable {
|
|||||||
return row[column - 1]
|
return row[column - 1]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static let terminators: Set<Character> = [" ", "\t", "\n", "\r", ",", ";", ":", ")", "!", "?", ".", "/"]
|
||||||
|
|
||||||
|
static func isTokenChar(_ c: Character) -> Bool { c.isLetter || c.isNumber || c == "_" || c == "-" || c == "#" }
|
||||||
|
|
||||||
|
/// Live expansion while typing (PM behaviour): looks at the text just before the cursor and returns the
|
||||||
|
/// range (UTF-16, for NSTextView) to replace plus the replacement, or nil.
|
||||||
|
/// – "\\w10\\" (delimiter mode, as soon as the closing delimiter is typed)
|
||||||
|
/// – "w10" followed by space/comma/… (bare codes, the terminator itself is kept)
|
||||||
|
public func pendingExpansion(in text: String, cursor: Int) -> (range: NSRange, replacement: String)? {
|
||||||
|
guard !table.isEmpty else { return nil }
|
||||||
|
let ns = text as NSString
|
||||||
|
guard cursor > 0, cursor <= ns.length else { return nil }
|
||||||
|
let before = ns.substring(to: cursor)
|
||||||
|
guard let last = before.last else { return nil }
|
||||||
|
|
||||||
|
if last == delimiter {
|
||||||
|
let body = before.dropLast()
|
||||||
|
if let open = body.lastIndex(of: delimiter) {
|
||||||
|
let code = String(body[body.index(after: open)...])
|
||||||
|
if !code.isEmpty, !code.contains(where: { $0.isWhitespace }) {
|
||||||
|
let rep = lookup(code) ?? (defaultReplacement.isEmpty ? nil : defaultReplacement)
|
||||||
|
if let rep {
|
||||||
|
let start = (String(body[..<open]) as NSString).length
|
||||||
|
return (NSRange(location: start, length: cursor - start), rep)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if bareCodes, CodeReplacements.terminators.contains(last) {
|
||||||
|
let body = before.dropLast()
|
||||||
|
var start = body.endIndex
|
||||||
|
while start > body.startIndex, CodeReplacements.isTokenChar(body[body.index(before: start)]) {
|
||||||
|
start = body.index(before: start)
|
||||||
|
}
|
||||||
|
let token = String(body[start...])
|
||||||
|
guard !token.isEmpty, let rep = lookup(token) else { return nil }
|
||||||
|
let loc = (String(body[..<start]) as NSString).length
|
||||||
|
return (NSRange(location: loc, length: (token as NSString).length), rep)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
public func expand(_ text: String) -> String {
|
public func expand(_ text: String) -> String {
|
||||||
guard !table.isEmpty, text.contains(delimiter) else { return text }
|
guard !table.isEmpty, text.contains(delimiter) else { return text }
|
||||||
var out = ""
|
var out = ""
|
||||||
|
|||||||
@@ -154,3 +154,45 @@ final class PMPrefsTests: XCTestCase {
|
|||||||
XCTAssertEqual(item.pmPrefsString, "1:1:0:-00001")
|
XCTAssertEqual(item.pmPrefsString, "1:1:0:-00001")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
final class CodeLibraryTests: XCTestCase {
|
||||||
|
func lib() -> CodeLibrary {
|
||||||
|
var l = CodeLibrary()
|
||||||
|
l.sets = [CodeSet(name: "VfL", entries: CodeLibrary.parse("w10\tSvenja Huth (VfL Wolfsburg, 10)\tHuth\n")),
|
||||||
|
CodeSet(name: "TSG", entries: CodeLibrary.parse("h10\tSarai Linder (TSG Hoffenheim, 10)\n"))]
|
||||||
|
l.delimiter = "."
|
||||||
|
return l
|
||||||
|
}
|
||||||
|
|
||||||
|
func testBareCodeExpandsOnSpace() {
|
||||||
|
let codes = lib().replacements
|
||||||
|
let text = "w10 "
|
||||||
|
let r = codes.pendingExpansion(in: text, cursor: 4)
|
||||||
|
XCTAssertEqual(r?.range, NSRange(location: 0, length: 3))
|
||||||
|
XCTAssertEqual(r?.replacement, "Svenja Huth (VfL Wolfsburg, 10)")
|
||||||
|
XCTAssertNil(codes.pendingExpansion(in: "Ball ", cursor: 5))
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDelimiterCodeAndColumn() {
|
||||||
|
let codes = lib().replacements
|
||||||
|
let text = "Tor .w10#2."
|
||||||
|
let r = codes.pendingExpansion(in: text, cursor: (text as NSString).length)
|
||||||
|
XCTAssertEqual(r?.replacement, "Huth")
|
||||||
|
XCTAssertEqual(r?.range.location, 4)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testMergeAddsOnlyNewPlayers() {
|
||||||
|
var set = CodeSet(name: "VfL", entries: CodeLibrary.parse("w10\tSvenja Huth\n"))
|
||||||
|
let r = set.merge(CodeLibrary.parse("w10\tANDERS\nw23\tNeue Spielerin\n"))
|
||||||
|
XCTAssertEqual(r.added, 1)
|
||||||
|
XCTAssertEqual(r.existing, 1)
|
||||||
|
XCTAssertEqual(set.entries.first?.columns.first, "Svenja Huth")
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDisabledTeamIsIgnored() {
|
||||||
|
var l = lib()
|
||||||
|
l.sets[1].enabled = false
|
||||||
|
XCTAssertNil(l.replacements.lookup("h10"))
|
||||||
|
XCTAssertNotNil(l.replacements.lookup("W10"))
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user