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
+615
-134
No files matched your search
@@ -254,6 +254,22 @@ public enum IngestService {
|
||||
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 {
|
||||
func size(_ u: URL) -> Int64? {
|
||||
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 table: [String: [String]] = [:]
|
||||
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 }
|
||||
|
||||
@@ -99,6 +103,8 @@ public struct CodeReplacements: Codable, Sendable {
|
||||
delimiter = d.first ?? "\\"
|
||||
table = try c.decodeIfPresent([String: [String]].self, forKey: .table) ?? [:]
|
||||
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 {
|
||||
@@ -106,6 +112,8 @@ public struct CodeReplacements: Codable, Sendable {
|
||||
try c.encode(String(delimiter), forKey: .delimiter)
|
||||
try c.encode(table, forKey: .table)
|
||||
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.
|
||||
@@ -123,7 +131,7 @@ public struct CodeReplacements: Codable, Sendable {
|
||||
return CodeReplacements(table: table)
|
||||
}
|
||||
|
||||
func lookup(_ code: String) -> String? {
|
||||
public func lookup(_ code: String) -> String? {
|
||||
var name = code
|
||||
var column = 1
|
||||
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]
|
||||
}
|
||||
|
||||
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 {
|
||||
guard !table.isEmpty, text.contains(delimiter) else { return text }
|
||||
var out = ""
|
||||
|
||||
Reference in new issue
Block a user