Initial Commit
This commit is contained in:
@@ -0,0 +1,311 @@
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
archiveVersion = 1;
|
||||
classes = {
|
||||
};
|
||||
objectVersion = 56;
|
||||
objects = {
|
||||
AB0000000000000000000001 = {isa = PBXFileReference; lastKnownFileType = folder; path = Fixtures; sourceTree = "<group>";};
|
||||
AB0000000000000000000002 = {isa = PBXBuildFile; fileRef = AB0000000000000000000001;};
|
||||
AB0000000000000000000003 = {isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = (AB0000000000000000000002); runOnlyForDeploymentPostprocessing = 0;};
|
||||
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
000000000000000000000065 /* KJamsCloneApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000001 /* KJamsCloneApp.swift */; };
|
||||
000000000000000000000066 /* Library.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000002 /* Library.swift */; };
|
||||
000000000000000000000067 /* CDG.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000003 /* CDG.swift */; };
|
||||
000000000000000000000068 /* Importer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000004 /* Importer.swift */; };
|
||||
000000000000000000000069 /* Player.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000000000000000000000005 /* Player.swift */; };
|
||||
A00000000000000000000004 /* KJamsCloneTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A00000000000000000000003 /* KJamsCloneTests.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
D00000000000000000000003 /* PBXContainerItemProxy */ = {
|
||||
isa = PBXContainerItemProxy;
|
||||
containerPortal = F00000000000000000000001 /* Project object */;
|
||||
proxyType = 1;
|
||||
remoteGlobalIDString = D00000000000000000000001;
|
||||
remoteInfo = KJamsClone;
|
||||
};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
000000000000000000000001 /* KJamsCloneApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KJamsCloneApp.swift; sourceTree = "<group>"; };
|
||||
000000000000000000000002 /* Library.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Library.swift; sourceTree = "<group>"; };
|
||||
000000000000000000000003 /* CDG.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CDG.swift; sourceTree = "<group>"; };
|
||||
000000000000000000000004 /* Importer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Importer.swift; sourceTree = "<group>"; };
|
||||
000000000000000000000005 /* Player.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Player.swift; sourceTree = "<group>"; };
|
||||
A00000000000000000000001 /* KJamsClone.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; path = KJamsClone.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A00000000000000000000002 /* KJamsCloneTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; path = KJamsCloneTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
A00000000000000000000003 /* KJamsCloneTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KJamsCloneTests.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
B00000000000000000000001 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
AB0000000000000000000001 /* Fixtures */,
|
||||
B00000000000000000000002 /* KJamsClone */,
|
||||
B00000000000000000000003 /* KJamsCloneTests */,
|
||||
B00000000000000000000004 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
B00000000000000000000002 /* KJamsClone */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
000000000000000000000001 /* KJamsCloneApp.swift */,
|
||||
000000000000000000000002 /* Library.swift */,
|
||||
000000000000000000000003 /* CDG.swift */,
|
||||
000000000000000000000004 /* Importer.swift */,
|
||||
000000000000000000000005 /* Player.swift */,
|
||||
);
|
||||
path = KJamsClone;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
B00000000000000000000003 /* KJamsCloneTests */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A00000000000000000000003 /* KJamsCloneTests.swift */,
|
||||
);
|
||||
path = KJamsCloneTests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
B00000000000000000000004 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
A00000000000000000000001 /* KJamsClone.app */,
|
||||
A00000000000000000000002 /* KJamsCloneTests.xctest */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
D00000000000000000000001 /* KJamsClone */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = E00000000000000000000002 /* Build configuration list for PBXNativeTarget "KJamsClone" */;
|
||||
buildPhases = (
|
||||
C00000000000000000000001 /* Sources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = KJamsClone;
|
||||
productName = KJamsClone;
|
||||
productReference = A00000000000000000000001 /* KJamsClone.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
D00000000000000000000002 /* KJamsCloneTests */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = E00000000000000000000003 /* Build configuration list for PBXNativeTarget "KJamsCloneTests" */;
|
||||
buildPhases = (
|
||||
C00000000000000000000002 /* Sources */,
|
||||
AB0000000000000000000003 /* Resources */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
D00000000000000000000004 /* PBXTargetDependency */,
|
||||
);
|
||||
name = KJamsCloneTests;
|
||||
productName = KJamsCloneTests;
|
||||
productReference = A00000000000000000000002 /* KJamsCloneTests.xctest */;
|
||||
productType = "com.apple.product-type.bundle.unit-test";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
F00000000000000000000001 /* Project object */ = {
|
||||
isa = PBXProject;
|
||||
attributes = {
|
||||
LastUpgradeCheck = 1600;
|
||||
};
|
||||
buildConfigurationList = E00000000000000000000001 /* Build configuration list for PBXProject "KJamsClone" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
knownRegions = (
|
||||
en,
|
||||
Base,
|
||||
);
|
||||
mainGroup = B00000000000000000000001;
|
||||
productRefGroup = B00000000000000000000004 /* Products */;
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
D00000000000000000000001 /* KJamsClone */,
|
||||
D00000000000000000000002 /* KJamsCloneTests */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C00000000000000000000001 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
000000000000000000000065 /* KJamsCloneApp.swift in Sources */,
|
||||
000000000000000000000066 /* Library.swift in Sources */,
|
||||
000000000000000000000067 /* CDG.swift in Sources */,
|
||||
000000000000000000000068 /* Importer.swift in Sources */,
|
||||
000000000000000000000069 /* Player.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
C00000000000000000000002 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
A00000000000000000000004 /* KJamsCloneTests.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
D00000000000000000000004 /* PBXTargetDependency */ = {
|
||||
isa = PBXTargetDependency;
|
||||
target = D00000000000000000000001 /* KJamsClone */;
|
||||
targetProxy = D00000000000000000000003 /* PBXContainerItemProxy */;
|
||||
};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
F10000000000000000000000 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
F10000000000000000000001 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
F20000000000000000000000 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = 39R6U3437D;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
MARKETING_VERSION = 0.1.0;
|
||||
OTHER_LDFLAGS = "-lsqlite3";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.app;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
F20000000000000000000001 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1;
|
||||
DEVELOPMENT_TEAM = 39R6U3437D;
|
||||
ENABLE_APP_SANDBOX = NO;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
MARKETING_VERSION = 0.1.0;
|
||||
OTHER_LDFLAGS = "-lsqlite3";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.app;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
F30000000000000000000000 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
OTHER_LDFLAGS = "-lsqlite3";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.tests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/KJamsClone.app/Contents/MacOS/KJamsClone";
|
||||
};
|
||||
name = Debug;
|
||||
};
|
||||
F30000000000000000000001 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
BUNDLE_LOADER = "$(TEST_HOST)";
|
||||
CLANG_ENABLE_MODULES = YES;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
MACOSX_DEPLOYMENT_TARGET = 13.0;
|
||||
OTHER_LDFLAGS = "-lsqlite3";
|
||||
PRODUCT_BUNDLE_IDENTIFIER = com.kjamsclone.tests;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SDKROOT = macosx;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
SWIFT_VERSION = 5.0;
|
||||
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/KJamsClone.app/Contents/MacOS/KJamsClone";
|
||||
};
|
||||
name = Release;
|
||||
};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
E00000000000000000000001 /* Build configuration list for PBXProject "KJamsClone" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
F10000000000000000000000 /* Debug */,
|
||||
F10000000000000000000001 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
E00000000000000000000002 /* Build configuration list for PBXNativeTarget "KJamsClone" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
F20000000000000000000000 /* Debug */,
|
||||
F20000000000000000000001 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
E00000000000000000000003 /* Build configuration list for PBXNativeTarget "KJamsCloneTests" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
F30000000000000000000000 /* Debug */,
|
||||
F30000000000000000000001 /* Release */,
|
||||
);
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
/* End XCConfigurationList section */
|
||||
};
|
||||
rootObject = F00000000000000000000001 /* Project object */;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
import AVFoundation
|
||||
|
||||
struct Importer {
|
||||
let media: URL
|
||||
func run(_ urls: [URL], library: Library) throws {
|
||||
try FileManager.default.createDirectory(at: media, withIntermediateDirectories: true)
|
||||
var files = urls
|
||||
var temporary = [URL]()
|
||||
defer { for url in temporary { try? FileManager.default.removeItem(at: url) } }
|
||||
for zip in urls where zip.pathExtension.lowercased() == "zip" {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
|
||||
temporary.append(folder)
|
||||
// Validate names before extraction; reject path traversal and symlinks afterwards.
|
||||
let details = try process(["-Z", "-l", zip.path])
|
||||
guard !details.split(separator: "\n").contains(where: { $0.hasPrefix("l") }) else { throw LibraryError.message("ZIP symlinks are unsupported") }
|
||||
let list = try process(["-Z1", zip.path])
|
||||
let names = list.split(separator: "\n").map(String.init)
|
||||
guard !names.isEmpty, names.allSatisfy({ !$0.hasPrefix("/") && !$0.split(separator: "/").contains("..") && !$0.contains("\\") }) else { throw LibraryError.message("Unsafe or empty ZIP") }
|
||||
_ = try process(["-q", zip.path, "-d", folder.path])
|
||||
let extracted = FileManager.default.enumerator(at: folder, includingPropertiesForKeys: [.isSymbolicLinkKey,.isRegularFileKey])!
|
||||
for case let url as URL in extracted {
|
||||
let values = try url.resourceValues(forKeys: [.isSymbolicLinkKey,.isRegularFileKey])
|
||||
guard values.isSymbolicLink != true else { throw LibraryError.message("ZIP symlinks are unsupported") }
|
||||
if values.isRegularFile == true { files.append(url) }
|
||||
}
|
||||
}
|
||||
for audio in files where ["mp3","wav","m4a"].contains(audio.pathExtension.lowercased()) {
|
||||
let siblings = try FileManager.default.contentsOfDirectory(at: audio.deletingLastPathComponent(), includingPropertiesForKeys: nil)
|
||||
let cdg = siblings.first { $0.pathExtension.lowercased() == "cdg" && $0.deletingPathExtension().lastPathComponent.caseInsensitiveCompare(audio.deletingPathExtension().lastPathComponent) == .orderedSame }
|
||||
let hash = SHA256.hash(data: try Data(contentsOf: audio)).map { String(format: "%02x", $0) }.joined()
|
||||
let dest = media.appendingPathComponent(hash + "." + audio.pathExtension.lowercased())
|
||||
if !FileManager.default.fileExists(atPath: dest.path) { try FileManager.default.copyItem(at: audio, to: dest) }
|
||||
var graphics: String?
|
||||
if let cdg {
|
||||
let target = media.appendingPathComponent(hash + ".cdg")
|
||||
if !FileManager.default.fileExists(atPath: target.path) { try FileManager.default.copyItem(at: cdg, to: target) }
|
||||
graphics = target.path
|
||||
}
|
||||
let asset = AVURLAsset(url: audio)
|
||||
let metadata = asset.commonMetadata
|
||||
func tag(_ key: AVMetadataKey) -> String { metadata.first { $0.commonKey == key }?.stringValue ?? "" }
|
||||
let taggedTitle = tag(.commonKeyTitle)
|
||||
try library.add(title: taggedTitle.isEmpty ? audio.deletingPathExtension().lastPathComponent : taggedTitle,
|
||||
audio: dest.path, cdg: graphics, artist: tag(.commonKeyArtist), album: tag(.commonKeyAlbumName), label: tag(.commonKeyPublisher))
|
||||
}
|
||||
}
|
||||
private func process(_ arguments: [String]) throws -> String {
|
||||
let task = Process(); task.executableURL = URL(fileURLWithPath: "/usr/bin/unzip"); task.arguments = arguments
|
||||
let out = Pipe(); task.standardOutput = out
|
||||
let err = FileHandle.nullDevice; task.standardError = err
|
||||
try task.run()
|
||||
let bytes = out.fileHandleForReading.readDataToEndOfFile(); task.waitUntilExit()
|
||||
guard task.terminationStatus == 0 else { throw LibraryError.message("Cannot read ZIP archive") }
|
||||
return String(decoding: bytes, as: UTF8.self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,379 @@
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
enum EntityKind: String, Identifiable {
|
||||
case singer, venue
|
||||
var id: String { rawValue }
|
||||
var title: String { self == .singer ? "Singer" : "Venue" }
|
||||
var table: String { self == .singer ? "singers" : "venues" }
|
||||
}
|
||||
|
||||
@MainActor final class AppModel: ObservableObject {
|
||||
@Published var songs = [Song]()
|
||||
@Published var singers = [PersonPlace]()
|
||||
@Published var venues = [PersonPlace]()
|
||||
@Published var error: String?
|
||||
@Published var creating: EntityKind?
|
||||
let player = Player()
|
||||
private(set) var library: Library?
|
||||
let root: URL
|
||||
init(storageURL: URL? = nil) {
|
||||
root = storageURL ?? FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0].appendingPathComponent("KJamsClone")
|
||||
perform {
|
||||
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
||||
library = try Library(url: root.appendingPathComponent("Library.sqlite")); try refresh()
|
||||
}
|
||||
}
|
||||
func perform(_ work: () throws -> Void) { do { try work() } catch { self.error = error.localizedDescription } }
|
||||
func refresh() throws { guard let library else { return }; songs = try library.songs(); singers = try library.entities("singers"); venues = try library.entities("venues") }
|
||||
@discardableResult func createEntity(_ kind: EntityKind, name: String) throws -> Int64 {
|
||||
guard let library else { throw LibraryError.message("Library unavailable") }
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
try library.addEntity(kind.table, name: trimmed)
|
||||
try refresh()
|
||||
let entities = kind == .singer ? singers : venues
|
||||
guard let entity = entities.first(where: { $0.name == trimmed }) else {
|
||||
throw LibraryError.message("The new \(kind.title.lowercased()) could not be loaded")
|
||||
}
|
||||
return entity.id
|
||||
}
|
||||
func importFiles(_ urls: [URL]) { perform { guard let library else { throw LibraryError.message("Library unavailable") }; try Importer(media: root.appendingPathComponent("Media")).run(urls, library: library); try refresh() } }
|
||||
}
|
||||
@main struct KJamsCloneApp: App {
|
||||
@StateObject private var model = AppModel()
|
||||
var body: some Scene {
|
||||
Window("KJamsClone", id: "main") {
|
||||
LibraryView(model: model).frame(minWidth: 1060, minHeight: 680).preferredColorScheme(.dark)
|
||||
}.defaultSize(width: 1260, height: 840)
|
||||
.commands {
|
||||
CommandGroup(replacing: .newItem) {
|
||||
Button("New Singer…") { model.creating = .singer }.keyboardShortcut("n", modifiers: [.command, .shift])
|
||||
Button("New Venue…") { model.creating = .venue }.keyboardShortcut("n", modifiers: [.command, .option])
|
||||
}
|
||||
}
|
||||
Window("Video", id: "lyrics") {
|
||||
LyricsView(player: model.player).frame(minWidth: 480, minHeight: 320).preferredColorScheme(.dark)
|
||||
}.defaultSize(width: 600, height: 400)
|
||||
}
|
||||
}
|
||||
private enum Classic {
|
||||
static let frame = Color(red: 0.15, green: 0.15, blue: 0.15)
|
||||
static let navy = Color(red: 0.008, green: 0.065, blue: 0.16)
|
||||
static let blue = Color(red: 0.015, green: 0.17, blue: 0.42)
|
||||
static let header = Color(white: 0.115)
|
||||
static let line = Color(white: 0.42)
|
||||
}
|
||||
struct LyricsView: View {
|
||||
@ObservedObject var player: Player
|
||||
var body: some View {
|
||||
ZStack {
|
||||
Color.black
|
||||
if let image = player.image {
|
||||
Image(decorative: image, scale: 1).interpolation(.none).resizable().aspectRatio(1.5, contentMode: .fit)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct SilverSquareStyle: ButtonStyle {
|
||||
func makeBody(configuration: Configuration) -> some View {
|
||||
configuration.label.foregroundStyle(Color(white: 0.25)).padding(.horizontal, 6).padding(.vertical, 3)
|
||||
.background(LinearGradient(colors: [Color(white: 0.95), Color(white: 0.64)], startPoint: .top, endPoint: .bottom), in: RoundedRectangle(cornerRadius: 4))
|
||||
.overlay(RoundedRectangle(cornerRadius: 4).strokeBorder(Color(white: 0.45), lineWidth: 1.5))
|
||||
.overlay(RoundedRectangle(cornerRadius: 3).strokeBorder(.white.opacity(0.7)).padding(3))
|
||||
.opacity(configuration.isPressed ? 0.7 : 1)
|
||||
}
|
||||
}
|
||||
private struct SilverButton: View {
|
||||
let symbol: String
|
||||
let label: String
|
||||
var size: CGFloat = 40
|
||||
var active = false
|
||||
var enabled = true
|
||||
let action: () -> Void
|
||||
var body: some View {
|
||||
Button(action: action) {
|
||||
Image(systemName: symbol).font(.system(size: size * 0.41, weight: .semibold))
|
||||
.foregroundStyle(active ? Color.blue : Color(white: 0.24))
|
||||
.frame(width: size, height: size)
|
||||
.background(LinearGradient(colors: [.white, Color(white: 0.85), Color(white: 0.63)], startPoint: .top, endPoint: .bottom), in: Circle())
|
||||
.overlay(Circle().strokeBorder(Color(white: 0.45), lineWidth: 1.5))
|
||||
.overlay(Circle().strokeBorder(.white.opacity(0.65), lineWidth: 1).padding(3))
|
||||
.shadow(color: .black.opacity(0.7), radius: 1, y: 1)
|
||||
}.buttonStyle(.plain).disabled(!enabled).opacity(enabled ? 1 : 0.72)
|
||||
.help(label).accessibilityLabel(label)
|
||||
}
|
||||
}
|
||||
struct LibraryView: View {
|
||||
@ObservedObject var model: AppModel
|
||||
@State private var selected: Int64?
|
||||
@State private var singer: Int64?
|
||||
@State private var venue: Int64?
|
||||
@State private var search = ""
|
||||
@State private var name = ""
|
||||
@State private var importing = false
|
||||
@State private var source = "Library"
|
||||
@Environment(\.openWindow) private var openWindow
|
||||
private var visibleSongs: [Song] { model.songs.filter { search.isEmpty || $0.title.localizedCaseInsensitiveContains(search) } }
|
||||
private var selectedSong: Song? { model.songs.first { $0.id == selected } }
|
||||
var body: some View {
|
||||
VStack(spacing: 0) {
|
||||
TransportView(player: model.player, search: $search, hasSelection: selectedSong != nil,
|
||||
play: playSelected, next: playNext, display: { openWindow(id: "lyrics") })
|
||||
.padding(.horizontal, 18).padding(.top, 18).padding(.bottom, 22)
|
||||
HSplitView {
|
||||
sidebar.frame(minWidth: 190, idealWidth: 220, maxWidth: 240)
|
||||
VStack(spacing: 12) {
|
||||
if source == "Library" { songTable } else { directory }
|
||||
detailPanel.frame(height: 84)
|
||||
}.padding(.leading, 12).frame(minWidth: 780)
|
||||
}.padding(.horizontal, 18)
|
||||
footer.padding(.horizontal, 18).padding(.vertical, 12)
|
||||
}
|
||||
.background(Classic.frame)
|
||||
.sheet(item: $model.creating) { kind in
|
||||
AddEntitySheet(model: model, kind: kind) { id in
|
||||
if kind == .singer { singer = id } else { venue = id }
|
||||
}
|
||||
}
|
||||
.fileImporter(isPresented: $importing, allowedContentTypes: [.audio, .zip, UTType(filenameExtension: "cdg") ?? .data], allowsMultipleSelection: true) { result in
|
||||
switch result {
|
||||
case .success(let urls): model.importFiles(urls)
|
||||
case .failure(let error): model.error = error.localizedDescription
|
||||
}
|
||||
}
|
||||
.alert("KJamsClone", isPresented: Binding(get: { model.error != nil }, set: { if !$0 { model.error = nil } })) {
|
||||
Button("OK") { model.error = nil }
|
||||
} message: { Text(model.error ?? "") }
|
||||
}
|
||||
private var sidebar: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
Text("Source").font(.system(size: 15, weight: .semibold)).padding(.horizontal, 10).frame(height: 31)
|
||||
.frame(maxWidth: .infinity, alignment: .leading).background(Classic.header)
|
||||
ForEach([("Library", "music.note.house.fill", Color.yellow), ("Singers", "person.2.fill", Color.green), ("Venues", "building.2.fill", Color.cyan)], id: \.0) { item in
|
||||
Button { source = item.0 } label: {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: item.1).foregroundStyle(item.2).frame(width: 22)
|
||||
Text(item.0).font(.system(size: 16, weight: .medium))
|
||||
Spacer()
|
||||
Text("\(item.0 == "Library" ? model.songs.count : item.0 == "Singers" ? model.singers.count : model.venues.count)")
|
||||
.font(.system(size: 11)).foregroundStyle(.white.opacity(0.6))
|
||||
}.padding(.horizontal, 12).frame(height: 34).contentShape(Rectangle())
|
||||
.background(source == item.0 ? Color(red: 0, green: 0.36, blue: 1) : .clear)
|
||||
}.buttonStyle(.plain)
|
||||
}
|
||||
Spacer()
|
||||
}.foregroundStyle(.white).background(Classic.navy).overlay(Rectangle().stroke(Classic.line, lineWidth: 1))
|
||||
}
|
||||
private var songTable: some View {
|
||||
GeometryReader { geometry in
|
||||
ScrollView(.horizontal) {
|
||||
VStack(spacing: 0) {
|
||||
tableHeader(width: max(geometry.size.width, 790))
|
||||
ScrollView(.vertical) {
|
||||
LazyVStack(spacing: 0) {
|
||||
ForEach(visibleSongs) { song in songRow(song, width: max(geometry.size.width, 790)) }
|
||||
}.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
}
|
||||
}.frame(width: max(geometry.size.width, 790), height: geometry.size.height)
|
||||
}
|
||||
}.background(Classic.navy).overlay(Rectangle().stroke(Classic.line, lineWidth: 1))
|
||||
}
|
||||
private func widths(_ total: CGFloat) -> [CGFloat] {
|
||||
[42, max(200, total - 598), 100, 100, 76, 86, 72, 122]
|
||||
}
|
||||
private func tableHeader(width: CGFloat) -> some View {
|
||||
let sizes = widths(width)
|
||||
return HStack(spacing: 0) {
|
||||
ForEach(Array(["PLI", "Song Name", "Artist", "Album", "Label", "Key Adjust", "Tempo", "Rating"].enumerated()), id: \.offset) { index, title in
|
||||
Text(title).font(.system(size: 13, weight: .medium)).lineLimit(1)
|
||||
.padding(.leading, 7).frame(width: sizes[index], height: 30, alignment: .leading)
|
||||
.overlay(alignment: .trailing) { Rectangle().fill(Classic.line).frame(width: 1).padding(.vertical, 4) }
|
||||
}
|
||||
}.foregroundStyle(.white).background(Classic.header)
|
||||
.overlay(alignment: .bottom) { Rectangle().fill(Color(white: 0.65)).frame(height: 1) }
|
||||
}
|
||||
private func songRow(_ song: Song, width: CGFloat) -> some View {
|
||||
let sizes = widths(width)
|
||||
return HStack(spacing: 0) {
|
||||
Image(systemName: song.cdg == nil ? "music.note" : "music.note.tv")
|
||||
.foregroundStyle(.white.opacity(0.75)).frame(width: sizes[0])
|
||||
Text(song.title).lineLimit(1).padding(.leading, 7).frame(width: sizes[1], alignment: .leading)
|
||||
ForEach(2..<7) { index in
|
||||
Text(index == 4 ? (song.cdg == nil ? "Audio" : "MP3+G") : "—")
|
||||
.foregroundStyle(.white.opacity(0.5)).padding(.leading, 7).frame(width: sizes[index], alignment: .leading)
|
||||
}
|
||||
Menu {
|
||||
ForEach(0..<6) { value in
|
||||
Button(value == 0 ? "Unrated" : String(repeating: "★", count: value)) {
|
||||
model.perform { try model.library?.rate(song.id, value); try model.refresh() }
|
||||
}
|
||||
}
|
||||
} label: {
|
||||
Text(song.rating == 0 ? "☆☆☆☆☆" : String(repeating: "★", count: song.rating) + String(repeating: "☆", count: 5 - song.rating))
|
||||
.font(.system(size: 13)).foregroundStyle(song.rating == 0 ? Color.gray : Color.yellow)
|
||||
}.menuStyle(.borderlessButton).frame(width: sizes[7] - 14).padding(.horizontal, 7).help("Set song rating")
|
||||
}.font(.system(size: 13)).foregroundStyle(.white).frame(height: 30)
|
||||
.background(selected == song.id ? Color(red: 0, green: 0.28, blue: 0.72) : .clear)
|
||||
.contentShape(Rectangle()).onTapGesture(count: 2) { selected = song.id; playSelected() }
|
||||
.onTapGesture { selected = song.id }
|
||||
}
|
||||
private var directory: some View {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
HStack {
|
||||
Text(source).font(.system(size: 14, weight: .semibold))
|
||||
Spacer()
|
||||
Button(source == "Singers" ? "New Singer…" : "New Venue…") { model.creating = source == "Singers" ? .singer : .venue }
|
||||
}.padding(.horizontal, 12).frame(height: 36).background(Classic.header)
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 0) {
|
||||
ForEach(source == "Singers" ? model.singers : model.venues) { entity in
|
||||
Button {
|
||||
if source == "Singers" { singer = entity.id } else { venue = entity.id }
|
||||
} label: {
|
||||
HStack { Image(systemName: source == "Singers" ? "person.fill" : "building.2.fill"); Text(entity.name); Spacer()
|
||||
if entity.id == (source == "Singers" ? singer : venue) { Image(systemName: "checkmark") }
|
||||
}.padding(12).contentShape(Rectangle())
|
||||
}.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
}
|
||||
HStack {
|
||||
TextField(source == "Singers" ? "Singer name" : "Venue name", text: $name).textFieldStyle(.roundedBorder).onSubmit(addEntity)
|
||||
Button("Add \(source == "Singers" ? "Singer" : "Venue")", action: addEntity).disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}.padding(12)
|
||||
}.foregroundStyle(.white).background(Classic.navy).overlay(Rectangle().stroke(Classic.line, lineWidth: 1))
|
||||
}
|
||||
private var detailPanel: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack(spacing: 16) {
|
||||
Picker("Singer", selection: $singer) { Text("None").tag(nil as Int64?); ForEach(model.singers) { Text($0.name).tag(Optional($0.id)) } }
|
||||
Button { model.creating = .singer } label: { Image(systemName: "plus.circle.fill") }
|
||||
.buttonStyle(.plain).help("Add singer").accessibilityLabel("Add singer")
|
||||
Picker("Venue", selection: $venue) { Text("None").tag(nil as Int64?); ForEach(model.venues) { Text($0.name).tag(Optional($0.id)) } }
|
||||
Button { model.creating = .venue } label: { Image(systemName: "plus.circle.fill") }
|
||||
.buttonStyle(.plain).help("Add venue").accessibilityLabel("Add venue")
|
||||
Text(selectedSong.map { "\($0.plays) plays" } ?? "No song selected").foregroundStyle(.white.opacity(0.55)).font(.system(size: 11))
|
||||
}
|
||||
SeekBar(player: model.player)
|
||||
}.padding(12).frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.background(Classic.navy).overlay(Rectangle().stroke(Classic.line, lineWidth: 1))
|
||||
}
|
||||
private var footer: some View {
|
||||
HStack {
|
||||
Button { importing = true } label: { Image(systemName: "plus").font(.system(size: 20, weight: .bold)).frame(width: 32, height: 24) }
|
||||
.help("Import audio, MP3+G or ZIP").accessibilityLabel("Import songs")
|
||||
RepeatButton(player: model.player).padding(.leading, 12)
|
||||
Spacer()
|
||||
Text("\(visibleSongs.count) \(visibleSongs.count == 1 ? "Song" : "Songs")").font(.system(size: 14, weight: .medium))
|
||||
Spacer()
|
||||
Button { openWindow(id: "lyrics") } label: { Image(systemName: "rectangle.on.rectangle").frame(width: 32, height: 24) }
|
||||
.help("Open video window").accessibilityLabel("Open video window")
|
||||
}.buttonStyle(SilverSquareStyle())
|
||||
}
|
||||
private func playSelected() {
|
||||
guard let song = selectedSong else { return }
|
||||
model.perform { try model.player.load(song); try model.library?.record(song.id, singer: singer, venue: venue); try model.refresh() }
|
||||
}
|
||||
private func playNext() {
|
||||
guard !visibleSongs.isEmpty else { return }
|
||||
let index = visibleSongs.firstIndex { $0.id == selected } ?? -1
|
||||
selected = visibleSongs[(index + 1) % visibleSongs.count].id; playSelected()
|
||||
}
|
||||
private func addEntity() {
|
||||
model.perform {
|
||||
let kind: EntityKind = source == "Singers" ? .singer : .venue
|
||||
let id = try model.createEntity(kind, name: name)
|
||||
if kind == .singer { singer = id } else { venue = id }
|
||||
name = ""
|
||||
}
|
||||
}
|
||||
}
|
||||
private struct AddEntitySheet: View {
|
||||
@ObservedObject var model: AppModel
|
||||
let kind: EntityKind
|
||||
let saved: (Int64) -> Void
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
@State private var name = ""
|
||||
@State private var error: String?
|
||||
@FocusState private var focused: Bool
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 16) {
|
||||
Text("New \(kind.title)").font(.title2.bold())
|
||||
TextField("\(kind.title) name", text: $name).textFieldStyle(.roundedBorder)
|
||||
.focused($focused).onSubmit(save)
|
||||
if let error { Text(error).foregroundStyle(.red).font(.callout) }
|
||||
HStack {
|
||||
Spacer()
|
||||
Button("Cancel") { dismiss() }.keyboardShortcut(.cancelAction)
|
||||
Button("Add \(kind.title)", action: save).keyboardShortcut(.defaultAction)
|
||||
.disabled(name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
|
||||
}
|
||||
}.padding(24).frame(width: 360).onAppear { focused = true }
|
||||
}
|
||||
private func save() {
|
||||
do { let id = try model.createEntity(kind, name: name); saved(id); dismiss() }
|
||||
catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
private struct TransportView: View {
|
||||
@ObservedObject var player: Player
|
||||
@Binding var search: String
|
||||
let hasSelection: Bool
|
||||
let play: () -> Void
|
||||
let next: () -> Void
|
||||
let display: () -> Void
|
||||
var body: some View {
|
||||
HStack(alignment: .top, spacing: 28) {
|
||||
VStack(spacing: 15) {
|
||||
HStack(spacing: 7) {
|
||||
SilverButton(symbol: "backward.fill", label: "Back 10 seconds", size: 35, enabled: player.duration > 0) { player.seek(player.time - 10) }
|
||||
SilverButton(symbol: player.playing ? "pause.fill" : "play.fill", label: player.playing ? "Pause" : "Play", size: 49, enabled: hasSelection || player.duration > 0) {
|
||||
if player.duration > 0 { player.toggle() } else { play() }
|
||||
}
|
||||
SilverButton(symbol: "stop", label: "Stop", size: 46, enabled: player.duration > 0) { player.stop() }
|
||||
SilverButton(symbol: "forward.fill", label: "Forward 10 seconds", size: 35, enabled: player.duration > 0) { player.seek(player.time + 10) }
|
||||
SilverButton(symbol: "forward.end.fill", label: "Play next song", size: 26, enabled: hasSelection, action: next)
|
||||
}
|
||||
HStack(spacing: 9) {
|
||||
Image(systemName: "speaker.fill").font(.system(size: 11))
|
||||
Slider(value: $player.volume, in: 0...1).controlSize(.small).tint(.gray).accessibilityLabel("Volume")
|
||||
Image(systemName: "speaker.wave.3.fill").font(.system(size: 12))
|
||||
}.frame(width: 180)
|
||||
}.frame(width: 220)
|
||||
VStack(spacing: 0) {
|
||||
Text(player.duration == 0 ? "Ready!" : player.title).font(.system(size: 15, weight: .medium)).lineLimit(1).padding(.horizontal, 20)
|
||||
if player.duration > 0 { Text(player.playing ? "Playing" : "Paused").font(.system(size: 10)).foregroundStyle(.white.opacity(0.65)).padding(.top, 4) }
|
||||
}.frame(maxWidth: .infinity).frame(height: 64)
|
||||
.background(LinearGradient(colors: [Color(red: 0, green: 0.10, blue: 0.30), Classic.blue], startPoint: .top, endPoint: .bottom), in: Capsule())
|
||||
.overlay(Capsule().strokeBorder(LinearGradient(colors: [.black, .white], startPoint: .top, endPoint: .bottom), lineWidth: 1.5))
|
||||
.padding(.top, 14)
|
||||
HStack(spacing: 12) {
|
||||
TextField("Search", text: $search).textFieldStyle(.plain).font(.system(size: 16))
|
||||
.padding(.horizontal, 8).frame(width: 145, height: 28).background(Color(white: 0.07), in: RoundedRectangle(cornerRadius: 5))
|
||||
.overlay(RoundedRectangle(cornerRadius: 5).stroke(.white.opacity(0.1)))
|
||||
SilverButton(symbol: "eye", label: "Open video window", size: 48, action: display)
|
||||
}.padding(.top, 15)
|
||||
}.foregroundStyle(.white).frame(height: 96)
|
||||
}
|
||||
}
|
||||
private struct SeekBar: View {
|
||||
@ObservedObject var player: Player
|
||||
private func clock(_ seconds: Double) -> String { let n = Int(seconds); return String(format: "%d:%02d", n / 60, n % 60) }
|
||||
var body: some View {
|
||||
HStack(spacing: 10) {
|
||||
Text(clock(player.time))
|
||||
Slider(value: Binding(get: { player.time }, set: { player.seek($0) }), in: 0...max(1, player.duration))
|
||||
.controlSize(.mini).tint(.gray).disabled(player.duration == 0).accessibilityLabel("Playback position")
|
||||
Text(clock(player.duration))
|
||||
}.font(.system(size: 10, design: .monospaced)).foregroundStyle(.white.opacity(0.65))
|
||||
}
|
||||
}
|
||||
private struct RepeatButton: View {
|
||||
@ObservedObject var player: Player
|
||||
var body: some View {
|
||||
Button { player.repeating.toggle() } label: {
|
||||
Image(systemName: "repeat").font(.system(size: 18, weight: .semibold))
|
||||
.foregroundStyle(player.repeating ? Color.blue : Color(white: 0.25)).frame(width: 32, height: 24)
|
||||
}.help(player.repeating ? "Repeat song: on" : "Repeat song: off").accessibilityLabel("Repeat song").accessibilityValue(player.repeating ? "On" : "Off")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import Foundation
|
||||
import SQLite3
|
||||
|
||||
struct Song: Identifiable, Hashable {
|
||||
var id: Int64
|
||||
var title: String
|
||||
var audio: String
|
||||
var cdg: String?
|
||||
var rating: Int
|
||||
var plays: Int
|
||||
var artist: String = ""
|
||||
var album: String = ""
|
||||
var label: String = ""
|
||||
}
|
||||
struct PersonPlace: Identifiable, Hashable { var id: Int64; var name: String }
|
||||
struct SongPreference: Equatable {
|
||||
var pitch: Double = 0
|
||||
var tempo: Double = 1
|
||||
var rating: Int = 0
|
||||
}
|
||||
struct Performance: Identifiable {
|
||||
var id: Int64
|
||||
var song: String
|
||||
var singer: String
|
||||
var venue: String
|
||||
var date: String
|
||||
}
|
||||
struct QueueEntry: Identifiable {
|
||||
var id: Int64
|
||||
var songID: Int64
|
||||
var singerID: Int64?
|
||||
var title: String
|
||||
var singer: String
|
||||
}
|
||||
enum LibraryError: LocalizedError {
|
||||
case message(String)
|
||||
var errorDescription: String? { if case .message(let s) = self { return s }; return nil }
|
||||
}
|
||||
final class Library {
|
||||
private var db: OpaquePointer?
|
||||
init(url: URL) throws {
|
||||
guard sqlite3_open(url.path, &db) == SQLITE_OK else { throw LibraryError.message("Cannot open library") }
|
||||
try execute("PRAGMA foreign_keys=ON")
|
||||
try execute("CREATE TABLE IF NOT EXISTS songs(id INTEGER PRIMARY KEY,title TEXT NOT NULL,audio TEXT UNIQUE NOT NULL,cdg TEXT,rating INTEGER NOT NULL DEFAULT 0 CHECK(rating BETWEEN 0 AND 5),plays INTEGER NOT NULL DEFAULT 0)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS singers(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS venues(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS history(id INTEGER PRIMARY KEY,song INTEGER REFERENCES songs(id),singer INTEGER REFERENCES singers(id),venue INTEGER REFERENCES venues(id),played TEXT DEFAULT CURRENT_TIMESTAMP)")
|
||||
// Additive migration: preserve older libraries and infer existing memberships from history.
|
||||
for column in ["artist", "album", "label"] {
|
||||
if try !columns("songs").contains(column) { try execute("ALTER TABLE songs ADD COLUMN \(column) TEXT NOT NULL DEFAULT ''") }
|
||||
}
|
||||
try execute("CREATE TABLE IF NOT EXISTS venue_singers(venue INTEGER NOT NULL REFERENCES venues(id) ON DELETE CASCADE,singer INTEGER NOT NULL REFERENCES singers(id) ON DELETE CASCADE,PRIMARY KEY(venue,singer))")
|
||||
if try schemaVersion() < 3 { try execute("INSERT OR IGNORE INTO venue_singers SELECT DISTINCT venue,singer FROM history WHERE venue IS NOT NULL AND singer IS NOT NULL") }
|
||||
try execute("CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY,value TEXT)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS preferences(song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,singer INTEGER NOT NULL REFERENCES singers(id) ON DELETE CASCADE,pitch REAL NOT NULL DEFAULT 0 CHECK(pitch BETWEEN -12 AND 12),tempo REAL NOT NULL DEFAULT 1 CHECK(tempo BETWEEN 0.5 AND 1.5),rating INTEGER NOT NULL DEFAULT 0 CHECK(rating BETWEEN 0 AND 5),PRIMARY KEY(song,singer))")
|
||||
try execute("CREATE TABLE IF NOT EXISTS queue(id INTEGER PRIMARY KEY,venue INTEGER REFERENCES venues(id) ON DELETE CASCADE,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,singer INTEGER REFERENCES singers(id) ON DELETE CASCADE,position INTEGER NOT NULL)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS playlists(id INTEGER PRIMARY KEY,name TEXT UNIQUE NOT NULL)")
|
||||
try execute("CREATE TABLE IF NOT EXISTS playlist_songs(playlist INTEGER NOT NULL REFERENCES playlists(id) ON DELETE CASCADE,song INTEGER NOT NULL REFERENCES songs(id) ON DELETE CASCADE,position INTEGER NOT NULL,PRIMARY KEY(playlist,song))")
|
||||
try execute("PRAGMA user_version=3")
|
||||
}
|
||||
deinit { sqlite3_close(db) }
|
||||
private func statement(_ sql: String, _ values: [String?]) throws -> OpaquePointer {
|
||||
var s: OpaquePointer?
|
||||
guard sqlite3_prepare_v2(db, sql, -1, &s, nil) == SQLITE_OK, let s else { throw error() }
|
||||
for (i,v) in values.enumerated() {
|
||||
let code = v.map { sqlite3_bind_text(s, Int32(i + 1), $0, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) } ?? sqlite3_bind_null(s, Int32(i + 1))
|
||||
if code != SQLITE_OK { sqlite3_finalize(s); throw error() }
|
||||
}
|
||||
return s
|
||||
}
|
||||
private func error() -> LibraryError { .message(String(cString: sqlite3_errmsg(db))) }
|
||||
func execute(_ sql: String, _ values: [String?] = []) throws {
|
||||
let s = try statement(sql, values); defer { sqlite3_finalize(s) }
|
||||
guard sqlite3_step(s) == SQLITE_DONE else { throw error() }
|
||||
}
|
||||
func songs() throws -> [Song] {
|
||||
let s = try statement("SELECT id,title,audio,cdg,rating,plays,artist,album,label FROM songs ORDER BY title COLLATE NOCASE", []); defer { sqlite3_finalize(s) }
|
||||
var result = [Song]()
|
||||
while true {
|
||||
let code = sqlite3_step(s); if code == SQLITE_DONE { break }; guard code == SQLITE_ROW else { throw error() }
|
||||
result.append(Song(id: sqlite3_column_int64(s,0), title: String(cString: sqlite3_column_text(s,1)), audio: String(cString: sqlite3_column_text(s,2)), cdg: sqlite3_column_text(s,3).map { String(cString:$0) }, rating: Int(sqlite3_column_int(s,4)), plays: Int(sqlite3_column_int(s,5)), artist: text(s,6), album: text(s,7), label: text(s,8)))
|
||||
}
|
||||
return result
|
||||
}
|
||||
func add(title: String, audio: String, cdg: String?, artist: String = "", album: String = "", label: String = "") throws {
|
||||
try execute("INSERT INTO songs(title,audio,cdg,artist,album,label) VALUES(?,?,?,?,?,?) ON CONFLICT(audio) DO UPDATE SET cdg=COALESCE(excluded.cdg,songs.cdg),artist=CASE WHEN excluded.artist!='' THEN excluded.artist ELSE songs.artist END,album=CASE WHEN excluded.album!='' THEN excluded.album ELSE songs.album END,label=CASE WHEN excluded.label!='' THEN excluded.label ELSE songs.label END", [title,audio,cdg,artist,album,label])
|
||||
}
|
||||
func rate(_ id: Int64, _ rating: Int) throws { try execute("UPDATE songs SET rating=? WHERE id=?", [String(rating),String(id)]) }
|
||||
func entities(_ table: String) throws -> [PersonPlace] {
|
||||
precondition(["singers","venues","playlists"].contains(table))
|
||||
let s = try statement("SELECT id,name FROM \(table) ORDER BY name", []); defer { sqlite3_finalize(s) }
|
||||
var rows = [PersonPlace]()
|
||||
while sqlite3_step(s) == SQLITE_ROW { rows.append(.init(id: sqlite3_column_int64(s,0), name: String(cString: sqlite3_column_text(s,1)))) }
|
||||
return rows
|
||||
}
|
||||
func addEntity(_ table: String, name: String) throws {
|
||||
precondition(["singers","venues","playlists"].contains(table))
|
||||
let name = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
guard !name.isEmpty else { throw LibraryError.message("Enter a name") }
|
||||
try execute("INSERT OR IGNORE INTO \(table)(name) VALUES(?)", [name])
|
||||
}
|
||||
func record(_ song: Int64, singer: Int64?, venue: Int64?) throws {
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
do {
|
||||
try execute("INSERT INTO history(song,singer,venue) VALUES(?,?,?)", [String(song),singer.map(String.init),venue.map(String.init)])
|
||||
try execute("UPDATE songs SET plays=plays+1 WHERE id=?", [String(song)])
|
||||
try execute("COMMIT")
|
||||
} catch { try? execute("ROLLBACK"); throw error }
|
||||
}
|
||||
|
||||
private func text(_ s: OpaquePointer, _ index: Int32) -> String { sqlite3_column_text(s,index).map { String(cString:$0) } ?? "" }
|
||||
private func schemaVersion() throws -> Int {
|
||||
let s = try statement("PRAGMA user_version",[]); defer { sqlite3_finalize(s) }
|
||||
return sqlite3_step(s) == SQLITE_ROW ? Int(sqlite3_column_int(s,0)) : 0
|
||||
}
|
||||
private func columns(_ table: String) throws -> Set<String> {
|
||||
let s = try statement("PRAGMA table_info(\(table))", []); defer { sqlite3_finalize(s) }
|
||||
var result = Set<String>(); while sqlite3_step(s) == SQLITE_ROW { result.insert(text(s,1)) }; return result
|
||||
}
|
||||
func members(of venue: Int64) throws -> [PersonPlace] {
|
||||
let s = try statement("SELECT singers.id,singers.name FROM singers JOIN venue_singers ON singers.id=venue_singers.singer WHERE venue=? ORDER BY name", [String(venue)]); defer { sqlite3_finalize(s) }
|
||||
var result = [PersonPlace](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),name:text(s,1))) }; return result
|
||||
}
|
||||
func setMembership(singer: Int64, venue: Int64, included: Bool) throws {
|
||||
try execute(included ? "INSERT OR IGNORE INTO venue_singers(venue,singer) VALUES(?,?)" : "DELETE FROM venue_singers WHERE venue=? AND singer=?", [String(venue),String(singer)])
|
||||
if !included { try execute("DELETE FROM queue WHERE venue=? AND singer=?",[String(venue),String(singer)]) }
|
||||
}
|
||||
func currentVenue() throws -> Int64? {
|
||||
let s = try statement("SELECT venues.id FROM venues JOIN settings ON CAST(settings.value AS INTEGER)=venues.id WHERE settings.key='currentVenue'", []); defer { sqlite3_finalize(s) }
|
||||
return sqlite3_step(s) == SQLITE_ROW ? sqlite3_column_int64(s,0) : nil
|
||||
}
|
||||
func selectVenue(_ id: Int64?) throws {
|
||||
if let id {
|
||||
guard try entities("venues").contains(where: { $0.id == id }) else { throw LibraryError.message("Venue no longer exists") }
|
||||
}
|
||||
try execute("INSERT INTO settings(key,value) VALUES('currentVenue',?) ON CONFLICT(key) DO UPDATE SET value=excluded.value",[id.map(String.init)])
|
||||
}
|
||||
func rename(_ table: String, id: Int64, name: String) throws {
|
||||
precondition(["singers","venues","playlists"].contains(table))
|
||||
let name = name.trimmingCharacters(in:.whitespacesAndNewlines)
|
||||
guard !name.isEmpty else { throw LibraryError.message("Enter a name") }
|
||||
try execute("UPDATE \(table) SET name=? WHERE id=?",[name,String(id)])
|
||||
}
|
||||
func deleteEntity(_ table: String, id: Int64) throws {
|
||||
precondition(["singers","venues","playlists"].contains(table))
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
do {
|
||||
if table == "singers" { try execute("UPDATE history SET singer=NULL WHERE singer=?",[String(id)]) }
|
||||
if table == "venues" {
|
||||
try execute("UPDATE history SET venue=NULL WHERE venue=?",[String(id)])
|
||||
try execute("DELETE FROM settings WHERE key='currentVenue' AND value=?",[String(id)])
|
||||
}
|
||||
try execute("DELETE FROM \(table) WHERE id=?",[String(id)])
|
||||
try execute("COMMIT")
|
||||
} catch { try? execute("ROLLBACK"); throw error }
|
||||
}
|
||||
func preference(song: Int64, singer: Int64) throws -> SongPreference {
|
||||
let s = try statement("SELECT pitch,tempo,rating FROM preferences WHERE song=? AND singer=?",[String(song),String(singer)]); defer { sqlite3_finalize(s) }
|
||||
guard sqlite3_step(s) == SQLITE_ROW else { return .init() }
|
||||
return .init(pitch:sqlite3_column_double(s,0),tempo:sqlite3_column_double(s,1),rating:Int(sqlite3_column_int(s,2)))
|
||||
}
|
||||
func savePreference(song: Int64, singer: Int64, value: SongPreference) throws {
|
||||
try execute("INSERT INTO preferences(song,singer,pitch,tempo,rating) VALUES(?,?,?,?,?) ON CONFLICT(song,singer) DO UPDATE SET pitch=excluded.pitch,tempo=excluded.tempo,rating=excluded.rating",[String(song),String(singer),String(value.pitch),String(value.tempo),String(value.rating)])
|
||||
}
|
||||
func history(venue: Int64?, singer: Int64? = nil) throws -> [Performance] {
|
||||
let s = try statement("SELECT history.id,COALESCE(songs.title,'Deleted song'),COALESCE(singers.name,'—'),COALESCE(venues.name,'—'),played FROM history LEFT JOIN songs ON songs.id=history.song LEFT JOIN singers ON singers.id=history.singer LEFT JOIN venues ON venues.id=history.venue WHERE (? IS NULL OR history.venue=?) AND (? IS NULL OR history.singer=?) ORDER BY history.id DESC",[venue.map(String.init),venue.map(String.init),singer.map(String.init),singer.map(String.init)]); defer { sqlite3_finalize(s) }
|
||||
var result = [Performance](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),song:text(s,1),singer:text(s,2),venue:text(s,3),date:text(s,4))) }; return result
|
||||
}
|
||||
func enqueue(song: Int64, singer: Int64?, venue: Int64?) throws {
|
||||
guard let venue else { throw LibraryError.message("Select a current venue before adding to its queue") }
|
||||
if let singer, try !members(of:venue).contains(where: { $0.id == singer }) { throw LibraryError.message("Add this singer to the current venue first") }
|
||||
try execute("INSERT INTO queue(venue,song,singer,position) VALUES(?,?,?,(SELECT COALESCE(MAX(position),0)+1 FROM queue WHERE venue=?))",[String(venue),String(song),singer.map(String.init),String(venue)])
|
||||
}
|
||||
func queue(venue: Int64?) throws -> [QueueEntry] {
|
||||
guard let venue else { return [] }
|
||||
let s = try statement("SELECT queue.id,queue.song,queue.singer,songs.title,COALESCE(singers.name,'No singer') FROM queue JOIN songs ON songs.id=queue.song LEFT JOIN singers ON singers.id=queue.singer WHERE queue.venue=? ORDER BY position,id",[String(venue)]); defer { sqlite3_finalize(s) }
|
||||
var result = [QueueEntry](); while sqlite3_step(s) == SQLITE_ROW { result.append(.init(id:sqlite3_column_int64(s,0),songID:sqlite3_column_int64(s,1),singerID:sqlite3_column_type(s,2) == SQLITE_NULL ? nil : sqlite3_column_int64(s,2),title:text(s,3),singer:text(s,4))) }; return result
|
||||
}
|
||||
func removeQueue(_ id: Int64) throws { try execute("DELETE FROM queue WHERE id=?",[String(id)]) }
|
||||
func moveQueue(_ id: Int64, venue: Int64, by offset: Int) throws {
|
||||
var rows = try queue(venue:venue)
|
||||
guard let index = rows.firstIndex(where: { $0.id == id }), rows.indices.contains(index+offset) else { return }
|
||||
rows.swapAt(index,index+offset)
|
||||
try execute("BEGIN IMMEDIATE")
|
||||
do { for (i,row) in rows.enumerated() { try execute("UPDATE queue SET position=? WHERE id=?",[String(i),String(row.id)]) }; try execute("COMMIT") }
|
||||
catch { try? execute("ROLLBACK"); throw error }
|
||||
}
|
||||
func addToPlaylist(_ playlist: Int64, song: Int64) throws {
|
||||
try execute("INSERT OR IGNORE INTO playlist_songs(playlist,song,position) VALUES(?,?,(SELECT COALESCE(MAX(position),0)+1 FROM playlist_songs WHERE playlist=?))",[String(playlist),String(song),String(playlist)])
|
||||
}
|
||||
func playlistSongIDs(_ playlist: Int64) throws -> [Int64] {
|
||||
let s = try statement("SELECT song FROM playlist_songs WHERE playlist=? ORDER BY position",[String(playlist)]); defer { sqlite3_finalize(s) }
|
||||
var ids = [Int64](); while sqlite3_step(s) == SQLITE_ROW { ids.append(sqlite3_column_int64(s,0)) }; return ids
|
||||
}
|
||||
func removeFromPlaylist(_ playlist: Int64, song: Int64) throws { try execute("DELETE FROM playlist_songs WHERE playlist=? AND song=?",[String(playlist),String(song)]) }
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import SwiftUI
|
||||
import AVFoundation
|
||||
|
||||
/// Audio source-frame time drives CDG, including when the time-pitch unit changes tempo.
|
||||
@MainActor final class Player: ObservableObject {
|
||||
@Published var image: CGImage?
|
||||
@Published var playing = false
|
||||
@Published var time: Double = 0
|
||||
@Published var duration: Double = 0
|
||||
@Published var title = "Select a song"
|
||||
@Published var volume: Double = 0.8 { didSet { engine.mainMixerNode.outputVolume = Float(volume) } }
|
||||
@Published var repeating = false
|
||||
@Published var pitch: Double = 0 { didSet { effect.pitch = Float(pitch * 100) } }
|
||||
@Published var tempo: Double = 1 { didSet { effect.rate = Float(tempo) } }
|
||||
@Published var graphicsOffset: Double = 0
|
||||
private(set) var currentSongID: Int64?
|
||||
var onFinished: (() -> Void)?
|
||||
private let engine = AVAudioEngine()
|
||||
private let node = AVAudioPlayerNode()
|
||||
private let effect = AVAudioUnitTimePitch()
|
||||
private var file: AVAudioFile?
|
||||
private var anchor: Double = 0
|
||||
private var generation = UUID()
|
||||
private var cdg = Data()
|
||||
private var decoder = CDGDecoder()
|
||||
private var timer: Timer?
|
||||
init() { engine.attach(node); engine.attach(effect) }
|
||||
func load(_ song: Song, preference: SongPreference = .init()) throws {
|
||||
stop()
|
||||
do {
|
||||
let loaded = try AVAudioFile(forReading: URL(fileURLWithPath:song.audio))
|
||||
let graphics = try song.cdg.map { try Data(contentsOf:URL(fileURLWithPath:$0)) } ?? Data()
|
||||
guard loaded.length > 0 else { throw LibraryError.message("Audio file is empty") }
|
||||
engine.connect(node,to:effect,format:loaded.processingFormat)
|
||||
engine.connect(effect,to:engine.mainMixerNode,format:loaded.processingFormat)
|
||||
file = loaded; cdg = graphics; decoder = CDGDecoder()
|
||||
duration = Double(loaded.length) / loaded.processingFormat.sampleRate
|
||||
title = song.title; currentSongID = song.id
|
||||
pitch = preference.pitch; tempo = preference.tempo
|
||||
engine.mainMixerNode.outputVolume = Float(volume)
|
||||
engine.prepare(); try engine.start()
|
||||
schedule(at:0, play:true); startTimer(); tick()
|
||||
} catch { stop(); throw error }
|
||||
}
|
||||
private func schedule(at seconds: Double, play: Bool) {
|
||||
guard let file else { return }
|
||||
generation = UUID(); let token = generation
|
||||
node.stop()
|
||||
let rate = file.processingFormat.sampleRate
|
||||
let start = min(file.length, max(0, AVAudioFramePosition(seconds * rate)))
|
||||
anchor = Double(start) / rate; time = anchor
|
||||
guard start < file.length else { playing = false; render(); return }
|
||||
node.scheduleSegment(file, startingFrame:start, frameCount:AVAudioFrameCount(min(file.length-start,Int64(UInt32.max))), at:nil, completionCallbackType:.dataPlayedBack) { [weak self] _ in
|
||||
Task { @MainActor in
|
||||
guard let self, self.generation == token else { return }
|
||||
if self.repeating { self.schedule(at:0,play:true) }
|
||||
else {
|
||||
self.playing = false; self.time = self.duration; self.render()
|
||||
self.timer?.invalidate(); self.timer = nil; self.onFinished?()
|
||||
}
|
||||
}
|
||||
}
|
||||
if play { node.play() }; playing = play; render()
|
||||
}
|
||||
private func startTimer() {
|
||||
timer?.invalidate()
|
||||
timer = Timer.scheduledTimer(withTimeInterval:1.0/30,repeats:true) { [weak self] _ in Task { @MainActor in self?.tick() } }
|
||||
}
|
||||
func toggle() {
|
||||
guard file != nil else { return }
|
||||
if playing { tick(); node.pause(); playing = false }
|
||||
else if time >= duration { schedule(at:0,play:true); startTimer() }
|
||||
else { node.play(); playing = true; startTimer() }
|
||||
}
|
||||
func stop() {
|
||||
generation = UUID(); timer?.invalidate(); timer = nil; node.stop(); engine.stop()
|
||||
engine.disconnectNodeOutput(node); engine.disconnectNodeOutput(effect)
|
||||
file = nil; playing = false; time = 0; anchor = 0; duration = 0; image = nil; currentSongID = nil; title = "Select a song"
|
||||
}
|
||||
func seek(_ value: Double) {
|
||||
guard file != nil, value.isFinite else { return }
|
||||
schedule(at:min(max(value,0),duration), play:playing)
|
||||
startTimer()
|
||||
}
|
||||
private func render() { decoder.render(cdg,at:max(0,time+graphicsOffset)); image = cdg.isEmpty ? nil : decoder.image() }
|
||||
private func tick() {
|
||||
if playing, let file, let renderTime = node.lastRenderTime, let playerTime = node.playerTime(forNodeTime:renderTime) {
|
||||
time = min(duration,anchor + Double(playerTime.sampleTime) / file.processingFormat.sampleRate)
|
||||
}
|
||||
render()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import XCTest
|
||||
@testable import KJamsClone
|
||||
|
||||
final class KJamsCloneTests: XCTestCase {
|
||||
func packet(_ instruction: UInt8, _ data: [UInt8]) -> [UInt8] { [9,instruction,0,0] + Array((data + Array(repeating: 0,count:16)).prefix(16)) + [0,0,0,0] }
|
||||
func testPresetTileXORAndInvalidCoordinates() {
|
||||
var d = CDGDecoder()
|
||||
d.apply(packet(1,[3,0])); XCTAssertEqual(d.pixels[0],3)
|
||||
d.apply(packet(6,[0,5,1,1] + Array(repeating:63,count:12)))
|
||||
XCTAssertEqual(d.pixels[12*300+6],5)
|
||||
d.apply(packet(38,[0,5,1,1] + Array(repeating:63,count:12)))
|
||||
XCTAssertEqual(d.pixels[12*300+6],0)
|
||||
let old = d.pixels; d.apply(packet(6,[1,2,31,63])); XCTAssertEqual(d.pixels,old)
|
||||
}
|
||||
func testSeekAndTruncatedPacket() {
|
||||
var d = CDGDecoder()
|
||||
let data = Data(packet(1,[2,0]) + packet(1,[7,0]) + [9])
|
||||
d.render(data,at:1); XCTAssertEqual(d.pixels[0],7); XCTAssertEqual(d.packetIndex,2)
|
||||
d.render(data,at:1.0/300); XCTAssertEqual(d.pixels[0],2)
|
||||
d.render(data,at:0); XCTAssertEqual(d.pixels[0],0)
|
||||
}
|
||||
func testPaletteBorderScrollAndImage() {
|
||||
var d = CDGDecoder()
|
||||
d.apply(packet(30,[63,63])); XCTAssertEqual(d.palette[0],0xFFFFFFFF)
|
||||
d.apply(packet(2,[4])); XCTAssertEqual(d.pixels[0],4); XCTAssertEqual(d.pixels[12*300+6],0)
|
||||
d.apply(packet(20,[3,16,0])); XCTAssertEqual(d.pixels[100*300],3)
|
||||
d.apply(packet(24,[0,32,0])); XCTAssertEqual(d.pixels[100*300+294],3)
|
||||
XCTAssertEqual(d.image()?.width,288)
|
||||
}
|
||||
func testSQLitePersistenceDedupRatingsAndHistory() throws {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: folder,withIntermediateDirectories:true)
|
||||
defer { try? FileManager.default.removeItem(at:folder) }
|
||||
let url = folder.appendingPathComponent("test.sqlite")
|
||||
do {
|
||||
let db = try Library(url:url)
|
||||
try db.add(title:"Singer's Song",audio:"/test.mp3",cdg:nil)
|
||||
try db.add(title:"Duplicate",audio:"/test.mp3",cdg:"/test.cdg")
|
||||
let song = try XCTUnwrap(db.songs().first)
|
||||
try db.rate(song.id,5); XCTAssertThrowsError(try db.rate(song.id,6))
|
||||
try db.addEntity("singers",name:"O'Neil"); try db.addEntity("venues",name:"Hall")
|
||||
try db.record(song.id,singer:db.entities("singers").first?.id,venue:db.entities("venues").first?.id)
|
||||
}
|
||||
let reopened = try Library(url:url); let songs = try reopened.songs()
|
||||
XCTAssertEqual(songs.count,1); XCTAssertEqual(songs[0].rating,5); XCTAssertEqual(songs[0].plays,1); XCTAssertEqual(songs[0].cdg,"/test.cdg")
|
||||
XCTAssertEqual(try reopened.entities("singers").first?.name,"O'Neil")
|
||||
}
|
||||
func testPairedImportAndContentDedup() throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at:root,withIntermediateDirectories:true)
|
||||
defer { try? FileManager.default.removeItem(at:root) }
|
||||
let audio = root.appendingPathComponent("Test.mp3"), cdg = root.appendingPathComponent("Test.CDG")
|
||||
try Data([1,2,3]).write(to:audio); try Data(packet(1,[2,0])).write(to:cdg)
|
||||
let db = try Library(url:root.appendingPathComponent("test.sqlite"))
|
||||
let importer = Importer(media:root.appendingPathComponent("Media"))
|
||||
try importer.run([audio],library:db); try importer.run([audio],library:db)
|
||||
XCTAssertEqual(try db.songs().count,1)
|
||||
XCTAssertNotNil(try db.songs().first?.cdg)
|
||||
}
|
||||
|
||||
func testZippedMP3GImportAndUnsafeArchiveRejection() throws {
|
||||
let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at:folder,withIntermediateDirectories:true)
|
||||
defer { try? FileManager.default.removeItem(at:folder) }
|
||||
let fixtures = try XCTUnwrap(Bundle(for:Self.self).resourceURL?.appendingPathComponent("Fixtures"))
|
||||
let db = try Library(url:folder.appendingPathComponent("db.sqlite"))
|
||||
let importer = Importer(media:folder.appendingPathComponent("Media"))
|
||||
try importer.run([fixtures.appendingPathComponent("Demo.zip")],library:db)
|
||||
let song = try XCTUnwrap(db.songs().first)
|
||||
XCTAssertEqual(song.title,"Demo"); XCTAssertNotNil(song.cdg)
|
||||
XCTAssertTrue(FileManager.default.fileExists(atPath:song.audio))
|
||||
XCTAssertThrowsError(try importer.run([fixtures.appendingPathComponent("Unsafe.zip")],library:db))
|
||||
}
|
||||
@MainActor func testMP3PlaybackPauseAndSeek() throws {
|
||||
let fixtures = try XCTUnwrap(Bundle(for:Self.self).resourceURL?.appendingPathComponent("Fixtures"))
|
||||
let player = Player()
|
||||
defer { player.stop() }
|
||||
try player.load(Song(id:1,title:"Demo",audio:fixtures.appendingPathComponent("Demo.mp3").path,cdg:fixtures.appendingPathComponent("Demo.cdg").path,rating:0,plays:0))
|
||||
XCTAssertGreaterThan(player.duration,3.9); XCTAssertTrue(player.playing)
|
||||
player.toggle(); XCTAssertFalse(player.playing)
|
||||
player.seek(2); XCTAssertEqual(player.time,2,accuracy:0.05); XCTAssertNotNil(player.image)
|
||||
player.seek(0.1); XCTAssertEqual(player.time,0.1,accuracy:0.05)
|
||||
}
|
||||
@MainActor func testCreateSingerAndVenueThroughAppModel() throws {
|
||||
let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: root) }
|
||||
let model = AppModel(storageURL: root)
|
||||
XCTAssertNil(model.error)
|
||||
let singer = try model.createEntity(.singer, name: " Alex ")
|
||||
let venue = try model.createEntity(.venue, name: "Town Hall")
|
||||
XCTAssertEqual(model.singers.first?.name, "Alex")
|
||||
XCTAssertEqual(model.venues.first?.name, "Town Hall")
|
||||
XCTAssertEqual(try model.createEntity(.singer, name: "Alex"), singer)
|
||||
XCTAssertEqual(model.singers.count, 1)
|
||||
XCTAssertThrowsError(try model.createEntity(.venue, name: " "))
|
||||
let reopened = AppModel(storageURL: root)
|
||||
XCTAssertEqual(reopened.singers.first?.id, singer)
|
||||
XCTAssertEqual(reopened.venues.first?.id, venue)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
# KJamsClone — initial macOS implementation, v0.1.0
|
||||
|
||||
This is a real Xcode application project, not a Swift Package renamed as one.
|
||||
Open **KJamsClone.xcodeproj**. Its required project file is
|
||||
**KJamsClone.xcodeproj/project.pbxproj**. No version-control restoration,
|
||||
project generator, third-party packages, or network downloads are needed.
|
||||
|
||||
## Start
|
||||
|
||||
1. Extract the whole source ZIP to a writable folder. Do not open the project from inside the archive.
|
||||
2. Open `KJamsClone/KJamsClone.xcodeproj` in Xcode, select the **KJamsClone** scheme and **My Mac**, then Run.
|
||||
3. Click the **+ import button** and select `Fixtures/Demo.zip` for an original four-second tone and animated tile demonstration. This is a decoder demonstration, not a song with lyrics.
|
||||
4. Double-click the imported song. Use the **eye button** to open the Video window, then move it onto another monitor or use macOS's window fullscreen control.
|
||||
5. Double-click a library row to play it; the large Play/Pause button resumes or pauses the current track. The smaller transport buttons seek back/forward ten seconds and play the next song. The volume slider and repeat button control actual playback. Use the + button to import and the eye button to open the Video window.
|
||||
6. Import your own `.mp3` and matching `.cdg` files, or a ZIP containing those files. Names must match, ignoring case, in the same folder. Select the audio file; its sibling CDG is found automatically. Audio-only MP3/WAV/M4A and WAV+G are also accepted.
|
||||
|
||||
App deployment target: macOS 13+. Verified here with Xcode 27.2 on Apple Silicon macOS 27.2; older systems and Intel execution have not been tested. The build produces arm64 and x86_64 slices. XCTest execution with this Xcode may require macOS 14+.
|
||||
|
||||
## Implemented
|
||||
|
||||
| Feature | Scope |
|
||||
| --- | --- |
|
||||
| macOS app | Screenshot-inspired charcoal/silver controls, navy source sidebar and library grid, blue status capsule, library/search, rating menu, separate Video window |
|
||||
| MP3+G | AVAudioPlayer master clock; CDG packets decoded at 300 packets/sec; play, pause, resume, stop, seek, volume and repeat |
|
||||
| CDG | Memory/border preset, normal/XOR tiles, low/high palette, scroll preset/copy with fine offsets, transparent color; 288×192 cropped graphics |
|
||||
| ZIP import | Automatic extraction and pairing, nested folders, traversal/symlink rejection; system `/usr/bin/unzip` |
|
||||
| Library | SQLite persistence, copied media, SHA-256 audio-content deduplication for the same extension, search by filename title |
|
||||
| Ratings | Persistent per-song 0–5 stars |
|
||||
| Singers / venues | Create, list, select; persistent SQLite records |
|
||||
| Play history | Song/singer/venue/timestamp stored on each new song start; play counts shown |
|
||||
| Tests | Eight XCTest cases covering decoder behavior, backward seeking, SQLite reopening, ratings, play counts, pair/dedup import, ZIP import/rejection, real MP3 loading/pause/seeking |
|
||||
| Scripts | Debug build, tests, unsigned Release app ZIP |
|
||||
|
||||
Library and copied media are stored under `~/Library/Application Support/KJamsClone/`.
|
||||
Imported source files remain untouched. Back up that entire folder together; paths are absolute.
|
||||
No music catalogue or copyrighted songs are included. Demo tone/graphics are original and may be used freely.
|
||||
|
||||
## Incomplete / unverified
|
||||
|
||||
This is **not a complete kJams replacement or production-qualified release**.
|
||||
There is no singer rotation queue, playlist management, history browser, singer/venue editing or deletion, per-singer ratings/preferences, pitch/tempo adjustment, crossfade, key detection, metadata tag parsing, physical CD ripping, or standalone CDG-only playback. Titles come from filenames. The rating is global per song. Play counts count playback starts, not completed performances.
|
||||
|
||||
Synthetic fixtures and automated MP3 checks passed; real commercial karaoke collections, long performances, audible output quality, visual lyric accuracy, external monitors, and full UI interactions have not been manually validated. The decoder ignores parity/error correction, unsupported instructions and channel selection; all tile channels are combined. CDG has no adjustable synchronization offset. Backward seeking rebuilds graphics from packet zero on the main thread. Large imports also run on the main thread, without progress/cancel controls or archive expansion limits; use trusted, reasonably sized archives. Importing multiple files is not one database/filesystem transaction. A failed import may leave copied media to clean up. The app is intentionally not sandboxed, signed for distribution, or notarized. It has the default macOS application icon.
|
||||
|
||||
## Build, test, release
|
||||
|
||||
Run from this extracted project folder:
|
||||
|
||||
```sh
|
||||
./scripts/build.sh
|
||||
./scripts/test.sh
|
||||
./scripts/release.sh
|
||||
```
|
||||
|
||||
Scripts work from any working directory and stop on failure. Build products go under `build/` and `build-release/`; release output is `dist/KJamsClone-unsigned-macOS.zip`. Release builds disable signing. Developer ID signing and Apple notarization must be added before distributing the app to other users. The source ZIP contains neither personal media nor your library database.
|
||||
|
||||
`VERIFICATION.md` records the checks performed on this delivery. `verification/` contains the corresponding build/test excerpts.
|
||||
|
||||
## Implementation reference
|
||||
|
||||
CDG packet layout and commands were implemented using Jim Bumgardner's [CD+G Revealed](https://jbum.com/cdg_revealed.html) as a format reference. The implementation is original Swift code; no third-party player source is bundled.
|
||||
|
||||
## Screenshot-inspired interface
|
||||
|
||||
The interface follows the supplied reference: charcoal frame, silver transport controls, blue status capsule, navy panes, compact column headings, source selection and bottom song count. Library, Singers and Venues are functional sources. Third-party music stores and playlists from the reference are not implemented. Artist, Album, Key Adjust and Tempo columns show dashes because those features are not available; the Label column identifies the imported format. Rating menus persist changes. The separate Video window remains black when no graphics are loaded.
|
||||
|
||||
## Single main window and adding people / places
|
||||
|
||||
The app uses a single main library window; the File menu has no New Window command. The optional Video display remains separate for karaoke output.
|
||||
|
||||
Choose **File → New Singer…** or **File → New Venue…**, enter a name, then click Add. You can also use **New Singer… / New Venue…** at the top of the matching source pane, or the + button beside the singer/venue selector. New entries save to SQLite, appear immediately, and become selected for subsequent playback. Empty names are rejected, and adding an existing name selects its existing record.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 222 KiB |
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user