// Imported pets live on the device: a zip's `pack.json` and sprite sheets are // unpacked under the app's documents, and only this client reads them. There // is no built-in pet; nothing shows until the person imports one. import 'dart:convert'; import 'dart:io'; import 'dart:ui' as ui; import 'package:archive/archive.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../l10n.dart'; import 'pet_pack.dart'; class PetImportException implements Exception { final String message; const PetImportException(this.message); @override String toString() => message; } class PetLibrary extends ChangeNotifier { PetLibrary._(); static final PetLibrary instance = PetLibrary._(); static const _activeKey = 'pet.active.v1'; static const _enabledKey = 'pet.enabled.v1'; static const _sizeKey = 'pet.size.v1'; static const _positionKey = 'pet.x.v1'; /// The canvas width a pet is drawn at; the list offers these. static const sizes = [40, 52, 64]; PetPack? pack; bool enabled = false; double size = 52; /// Where the pet stands along its edge, 0 = left end, 1 = right end. double position = 0.5; String? _packDir; bool _loaded = false; // One decoded sheet at a time: a full sheet can be several megabytes, and // only the current mood is on screen. String? _imagePath; ui.Image? _image; Future? _loading; bool get hasPet => pack != null; bool get ready => pack != null && enabled; Future ensureLoaded() async { if (_loaded) return; _loaded = true; try { final prefs = await SharedPreferences.getInstance(); enabled = prefs.getBool(_enabledKey) ?? false; size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80); position = (prefs.getDouble(_positionKey) ?? 0.5).clamp(0.0, 1.0); final active = prefs.getString(_activeKey); if (active != null && active.isNotEmpty) { final root = await _petsRoot(); final dir = Directory('${root.path}/$active'); final manifest = File('${dir.path}/pack.json'); if (await manifest.exists()) { final json = jsonDecode(await manifest.readAsString()); if (json is Map) { final parsed = PetPack.fromJson(json); if (parsed.isValid) { pack = parsed; _packDir = dir.path; } } } } } catch (_) { // A corrupt or half-written pet must not keep the app from starting. } notifyListeners(); } Future setEnabled(bool value) async { enabled = value; notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setBool(_enabledKey, value); } catch (_) {} } Future setSize(double value) async { size = value.clamp(32, 80); notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(_sizeKey, size); } catch (_) {} } Future setPosition(double value) async { position = value.clamp(0.0, 1.0); notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.setDouble(_positionKey, position); } catch (_) {} } /// Unpacks and activates a pet package. [root] is for tests; the app uses /// the documents directory. Future importZip(List bytes, {Directory? root}) async { if (bytes.isEmpty) throw PetImportException(tr('File is empty')); if (bytes.length > 40 * 1024 * 1024) { throw PetImportException(tr('Pet pack cannot exceed 40 MB')); } final Archive archive; try { archive = ZipDecoder().decodeBytes(bytes, verify: true); } catch (_) { throw PetImportException(tr('Not a valid zip file')); } ArchiveFile? manifest; for (final file in archive.files) { if (!file.isFile) continue; final name = file.name.replaceAll('\\', '/'); if (name == 'pack.json' || name.endsWith('/pack.json')) { if (manifest == null || name.length < manifest.name.length) { manifest = file; } } } if (manifest == null) { throw PetImportException(tr('The archive has no pack.json')); } final manifestName = manifest.name.replaceAll('\\', '/'); final base = manifestName == 'pack.json' ? '' : manifestName.substring(0, manifestName.length - '/pack.json'.length); final PetPack parsed; try { final text = utf8.decode(_content(manifest)); final json = jsonDecode(text); if (json is! Map) throw const FormatException(); parsed = PetPack.fromJson(json); } catch (_) { throw PetImportException(tr('pack.json is not a valid pet pack')); } if (!parsed.isValid) { throw PetImportException(tr('pack.json is missing animations or states')); } final id = _safeId(parsed.id.isNotEmpty ? parsed.id : parsed.name); final rootDir = root ?? await _petsRoot(); await rootDir.create(recursive: true); final staging = Directory('${rootDir.path}/.$id.importing'); if (await staging.exists()) await staging.delete(recursive: true); await staging.create(recursive: true); try { var extracted = 0; for (final file in archive.files) { if (!file.isFile) continue; final name = file.name.replaceAll('\\', '/'); if (base.isNotEmpty && !name.startsWith('$base/')) continue; final rel = base.isEmpty ? name : name.substring(base.length + 1); if (rel.isEmpty || rel.startsWith('/')) continue; final segments = rel.split('/'); if (segments.any((s) => s.isEmpty || s == '..' || s == '.')) continue; final content = _content(file); extracted += content.length; if (extracted > 60 * 1024 * 1024) { throw PetImportException(tr('Extracted size exceeds 60 MB')); } final target = File('${staging.path}/$rel'); await target.parent.create(recursive: true); await target.writeAsBytes(content, flush: true); } for (final animation in parsed.animations.values) { if (animation.sheet.isEmpty) { throw PetImportException(trArgs('Animation {0} has no sprite sheet', [animation.name])); } final sheet = File('${staging.path}/${animation.sheet}'); if (!await sheet.exists()) { throw PetImportException(trArgs('Missing sprite sheet {0}', [animation.sheet])); } } final destination = Directory('${rootDir.path}/$id'); if (await destination.exists()) await destination.delete(recursive: true); await staging.rename(destination.path); _clearImages(); pack = parsed; _packDir = destination.path; enabled = true; try { final prefs = await SharedPreferences.getInstance(); await prefs.setString(_activeKey, id); await prefs.setBool(_enabledKey, true); } catch (_) {} notifyListeners(); return parsed; } catch (_) { if (await staging.exists()) { try { await staging.delete(recursive: true); } catch (_) {} } rethrow; } } Future remove() async { final dir = _packDir; pack = null; _packDir = null; enabled = false; _clearImages(); notifyListeners(); try { final prefs = await SharedPreferences.getInstance(); await prefs.remove(_activeKey); await prefs.setBool(_enabledKey, false); } catch (_) {} if (dir != null) { try { await Directory(dir).delete(recursive: true); } catch (_) {} } } /// The decoded sheet for [animation], held one at a time. Future imageFor(PetAnimation animation) { final dir = _packDir; if (dir == null || animation.sheet.isEmpty) return Future.value(null); final path = '$dir/${animation.sheet}'; if (_imagePath == path) { if (_image != null) return Future.value(_image); if (_loading != null) return _loading!; } _imagePath = path; _image?.dispose(); _image = null; final loading = _decode(path); _loading = loading; return loading; } Future _decode(String path) async { try { final bytes = await File(path).readAsBytes(); final codec = await ui.instantiateImageCodec(bytes); final frame = await codec.getNextFrame(); final image = frame.image; if (_imagePath != path) { image.dispose(); return null; } _image = image; return image; } catch (_) { return null; } finally { if (_imagePath == path) _loading = null; } } void _clearImages() { _image?.dispose(); _image = null; _imagePath = null; _loading = null; } static const _appDirChannel = MethodChannel('openchamber/appdir'); Future _petsRoot() async { String? base; if (Platform.isAndroid) { // A tiny channel in MainActivity: enough to find the app's files dir // without the JNI-based path_provider, which this engine cannot load. try { base = await _appDirChannel.invokeMethod('documents'); } catch (_) { // Fall through to the StateError below. } } else { final env = Platform.environment; final data = env['XDG_DATA_HOME']; base = data != null && data.isNotEmpty ? '$data/openchamber' : '${env['HOME'] ?? '.'}/.local/share/openchamber'; } if (base == null || base.isEmpty) { throw StateError('no writable directory for pets'); } final root = Directory('$base/pets'); if (!await root.exists()) await root.create(recursive: true); return root; } static List _content(ArchiveFile file) { final content = file.content; return content is List ? content : List.from(content as List); } static String _safeId(String raw) { final id = raw .toLowerCase() .replaceAll(RegExp(r'[^a-z0-9._-]+'), '-') .replaceAll(RegExp(r'^[-._]+|[-._]+$'), ''); return id.isEmpty ? 'pet' : id; } }