// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later #import "SizzleSession+Files.h" #import "SizzleSession+Internal.h" #import "SizzleSession+Setup.h" #include #include #include #include "io/MidiMapIo.hpp" #include "io/Zip.hpp" #include "sizzle/Specs.hpp" using namespace sizzle; namespace zip = sizzle::io::zip; // Defined in SizzleSession.mm (Documents/samples/.wav). @interface SizzleSession (FilesPrivate) - (NSURL *)sampleURL:(const std::string &)id; @end namespace { NSError *filesError(NSString *msg) { return [NSError errorWithDomain:@"Sizzle" code:3 userInfo:@{NSLocalizedDescriptionKey: msg}]; } NSURL *documents() { return [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; } std::vector bytesOf(NSData *d) { const uint8_t *b = (const uint8_t *)d.bytes; return std::vector(b, b + d.length); } NSData *dataOf(const std::vector &v) { return [NSData dataWithBytes:v.data() length:v.size()]; } // Backup areas under Documents (Android: songs, themes, presets, datastore; the // iOS app keeps its samples as files too, and settings as settings.txt). NSArray *const kAreas = @[@"songs", @"themes", @"presets", @"samples"]; NSString *const kAutosave = @"autosave.szg"; NSString *const kSettings = @"settings.txt"; } // namespace @implementation SizzleSession (Files) + (BOOL)isZipData:(NSData *)data { return data.length >= 4 && !memcmp(data.bytes, "PK\x03\x04", 4); } #pragma mark - bundles /// ProjectBundleIo.collectSampleIds: per slot, a Sampler's pads, else the /// SF2/XI, Grain Cloud or Wavetable sample; each id once, in that order. - (std::vector)files_sampleIds { std::vector ids; auto add = [&](NSString *v) { if (!v.length) return; std::string id = v.UTF8String; for (auto &x : ids) if (x == id) return; ids.push_back(id); }; for (NSInteger s = 0; s < 16; ++s) { NSString *type = [self typeOfSlot:s]; if ([type isEqualToString:@"SAMPLER"]) { for (int p = 0; p < 16; ++p) add([self valueOfSlot:s key:[NSString stringWithFormat:@"pad%d", p]]); } else if ([@[@"SOUNDFONT", @"GRAIN_CLOUD", @"WAVETABLE"] containsObject:type]) { add([self valueOfSlot:s key:@"sfSample"]); } } return ids; } - (nullable NSData *)projectBundleData { std::vector entries; NSData *text = [[self projectText] dataUsingEncoding:NSUTF8StringEncoding]; entries.push_back({"project.szg", bytesOf(text)}); std::string manifest; int i = 0; for (const std::string &id : [self files_sampleIds]) { NSData *wav = [NSData dataWithContentsOfURL:[self sampleURL:id]]; std::vector bytes; if (wav) bytes = bytesOf(wav); else if (auto s = [self sampleStore].get(id.c_str())) bytes = sampler::SampleStore::encodeWav(*s); if (!bytes.empty()) { entries.push_back({"samples/" + std::to_string(i) + ".wav", std::move(bytes)}); manifest += std::to_string(i) + "\t" + id + "\n"; } ++i; } entries.push_back({"samples/manifest.txt", std::vector(manifest.begin(), manifest.end())}); return dataOf(zip::write(entries)); } - (BOOL)importProjectBundleData:(NSData *)data error:(NSError **)error { std::vector entries; // ZipLimits.forBundle: 64 MB. if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 64ull << 20)) { if (error) *error = filesError(@"Couldn't read this bundle: it isn't a ZIP, is damaged, or is larger than 64 MB."); return NO; } NSString *text = nil; std::map manifest; // index -> original id std::map *> wavs; for (const auto &e : entries) { if (!zip::safeName(e.name)) continue; if (e.name == "project.szg") text = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding]; else if (e.name == "samples/manifest.txt") { std::string m(e.data.begin(), e.data.end()); size_t start = 0; while (start < m.size()) { size_t end = m.find('\n', start); if (end == std::string::npos) end = m.size(); std::string line = m.substr(start, end - start); if (!line.empty() && line.back() == '\r') line.pop_back(); const size_t tab = line.find('\t'); if (tab != std::string::npos && tab > 0) manifest[line.substr(0, tab)] = line.substr(tab + 1); start = end + 1; } } else if (e.name.rfind("samples/", 0) == 0 && e.name.size() > 12 && e.name.compare(e.name.size() - 4, 4, ".wav") == 0) { wavs[e.name.substr(8, e.name.size() - 12)] = &e.data; } } if (!text || ![SizzleSession looksLikeProjectText:text]) { if (error) *error = filesError(@"This archive holds no Sizzle project."); return NO; } // Store each sample under its original id, where the song looks for it. for (const auto &[idx, id] : manifest) { auto w = wavs.find(idx); if (w == wavs.end() || id.empty()) continue; [self sampleStore].remove(id.c_str()); // a stale copy under the same id must not win [dataOf(*w->second) writeToURL:[self sampleURL:id] atomically:YES]; } [self stop]; return [self importProjectText:text error:error]; } #pragma mark - MIDI mappings - (nullable NSString *)midiMapTextOfSlot:(NSInteger)slot { if (slot < 0 || slot >= 16) return nil; __block std::string text; [self read:^(const model::Project &p, const engine::Engine &) { const auto &s = p.toolbox[(size_t)slot]; if (!s.isEmpty()) text = io::MidiMapIo::save(io::MidiMapIo::fromSlot(s)); }]; return text.empty() ? nil : @(text.c_str()); } - (BOOL)importMidiMapText:(NSString *)text intoSlot:(NSInteger)slot error:(NSError **)error { const auto map = io::MidiMapIo::parse(text.UTF8String ?: ""); if (!map) { if (error) *error = filesError(@"This doesn't look like a Sizzle MIDI mapping (.szm)."); return NO; } __block int applied = -1; [self edit:^(model::Project &p, engine::Engine &) { applied = io::MidiMapIo::apply(p, (int)slot, *map); }]; if (applied < 0 && error) { const DeviceSpec *want = findDevice(map->type.c_str()); const DeviceSpec *have = findDevice([self typeOfSlot:slot].UTF8String); *error = filesError([NSString stringWithFormat:@"This mapping is for a %s, not a %s.", want ? want->displayName : map->type.c_str(), have ? have->displayName : "empty slot"]); } return applied >= 0; } - (void)removeValueOfSlot:(NSInteger)slot key:(NSString *)key { if (slot < 0 || slot >= 16) return; std::string k = key.UTF8String ?: ""; [self edit:^(model::Project &p, engine::Engine &) { p.toolbox[(size_t)slot].values.remove(k.c_str()); ++p.toolbox[(size_t)slot].version; }]; } #pragma mark - backups - (nullable NSData *)backupDataWithSettings:(NSString *)settings { [self autosave]; NSFileManager *fm = NSFileManager.defaultManager; NSURL *docs = documents(); std::vector entries; for (NSString *area in kAreas) { NSURL *dir = [docs URLByAppendingPathComponent:area]; NSDirectoryEnumerator *walk = [fm enumeratorAtURL:dir includingPropertiesForKeys:@[NSURLIsRegularFileKey] options:0 errorHandler:nil]; for (NSURL *f in walk) { NSNumber *regular = nil; [f getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil]; if (!regular.boolValue) continue; NSString *rel = [f.path substringFromIndex:dir.path.length]; if ([rel hasPrefix:@"/"]) rel = [rel substringFromIndex:1]; if ([rel hasPrefix:@"."] || [rel containsString:@"/."]) continue; // export scratch NSData *d = [NSData dataWithContentsOfURL:f]; if (d) entries.push_back({std::string(area.UTF8String) + "/" + rel.UTF8String, bytesOf(d)}); } } if (NSData *a = [NSData dataWithContentsOfURL:[docs URLByAppendingPathComponent:kAutosave]]) entries.push_back({kAutosave.UTF8String, bytesOf(a)}); NSData *s = [settings dataUsingEncoding:NSUTF8StringEncoding]; entries.push_back({kSettings.UTF8String, bytesOf(s)}); return dataOf(zip::write(entries)); } - (nullable NSString *)restoreBackupData:(NSData *)data error:(NSError **)error { std::vector entries; // ZipLimits.forBackup: 512 MB. if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 512ull << 20)) { if (error) *error = filesError(@"Couldn't read this backup: it isn't a ZIP, is damaged, or is too large."); return nil; } NSFileManager *fm = NSFileManager.defaultManager; NSURL *docs = documents(); NSURL *staging = [docs URLByAppendingPathComponent:@".restore_tmp"]; [fm removeItemAtURL:staging error:nil]; [fm createDirectoryAtURL:staging withIntermediateDirectories:YES attributes:nil error:nil]; BOOL looksValid = NO; NSString *settings = @""; for (const auto &e : entries) { if (!zip::safeName(e.name)) continue; NSString *name = @(e.name.c_str()); if ([name isEqualToString:kSettings]) { settings = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding] ?: @""; continue; } NSString *top = name.pathComponents.firstObject; const BOOL area = [kAreas containsObject:top] && name.pathComponents.count > 1; if (!area && ![name isEqualToString:kAutosave]) continue; // not ours (Android's datastore, …) NSURL *target = [staging URLByAppendingPathComponent:name]; [fm createDirectoryAtURL:target.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:nil]; if ([dataOf(e.data) writeToURL:target atomically:NO]) looksValid = YES; } if (!looksValid) { [fm removeItemAtURL:staging error:nil]; if (error) *error = filesError(@"This file doesn't look like a Sizzle backup."); return nil; } [self stop]; for (NSString *area in kAreas) { NSURL *src = [staging URLByAppendingPathComponent:area]; if (![fm fileExistsAtPath:src.path]) continue; NSURL *dst = [docs URLByAppendingPathComponent:area]; [fm removeItemAtURL:dst error:nil]; [fm moveItemAtURL:src toURL:dst error:nil]; } NSURL *autoSrc = [staging URLByAppendingPathComponent:kAutosave]; if ([fm fileExistsAtPath:autoSrc.path]) { NSURL *dst = [docs URLByAppendingPathComponent:kAutosave]; [fm removeItemAtURL:dst error:nil]; [fm moveItemAtURL:autoSrc toURL:dst error:nil]; NSString *text = [NSString stringWithContentsOfURL:dst encoding:NSUTF8StringEncoding error:nil]; if (text) [self loadProjectText:text error:nil]; } [fm removeItemAtURL:staging error:nil]; [fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"songs"] withIntermediateDirectories:YES attributes:nil error:nil]; [fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"samples"] withIntermediateDirectories:YES attributes:nil error:nil]; [self rehydrateSamples]; [[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil]; return settings; } @end