### Launch RetroArch with core resolution and 3DS setup Source: https://github.com/abduznik/freegosy/wiki/commit-e39958e Refactored launch method: normalizes the ROM path, checks for 3DS platforms to run setup, resolves the core path, and starts the process with the appropriate arguments. Throws MissingRetroArchCoreException if the core cannot be found. ```dart final normalizedRomPath = p.normalize(romPath); final coreName = _getCoreForSlug(game.platformSlug); // 1. Check if platform is 3DS-related final is3ds = [ '3ds', 'n3ds', 'nintendo-3ds', 'nintendo3ds', 'new-nintendo-3ds', 'new-nintendo-3ds-xl' ].contains(game.platformSlug?.toLowerCase()); if (is3ds) { // 2. Ensure 'citra' exists inside the RetroArch 'system' directory await _ensure3dsSetup(); } if (coreName == null) { await Process.start(exePath, [normalizedRomPath], mode: ProcessStartMode.detached); return; } final corePath = await _resolveCorePath(exePath, coreName); if (corePath == null) { final sep = io.Platform.isWindows ? r'\' : '/'; final exeDir = io.File(exePath).parent.path; throw MissingRetroArchCoreException( coreName: coreName, corePath: '$exeDir${sep}cores$sep$coreName', exePath: exePath, ); } await Process.start( exePath, ['-L', corePath, normalizedRomPath], mode: ProcessStartMode.detached, ); ``` -------------------------------- ### Add Download Button and Start Download Function Source: https://github.com/abduznik/freegosy/wiki/commit-e39958e Adds an ElevatedButton to trigger emulator download and defines the _startDownload function that shows a snackbar, starts the download via the downloadProvider, and listens for completion to update state and show success or error messages. ```dart if (!isInstalled && canManage) ElevatedButton( onPressed: () => _startDownload(context, ref, emulatorId, emulatorName, emulatorInstallStates, setState), child: const Text('Download'), ), ``` ```dart void _startDownload( BuildContext context, WidgetRef ref, String emulatorId, String emulatorName, Map emulatorInstallStates, Function(void Function()) setState, ) { final messenger = ScaffoldMessenger.of(context); messenger.showSnackBar(SnackBar( content: Text('Starting download for $emulatorName...'), )); ref.read(downloadProvider.notifier).startEmulatorDownload(emulatorId, emulatorName); // Listen for download completion and update state StreamSubscription? sub; sub = ref.read(downloadProvider.notifier).stream.listen((downloads) { final progress = downloads[emulatorId]; if (progress != null && (progress.isComplete || progress.error != null)) { if (progress.isComplete) { emulatorInstallStates[emulatorId] = true; if (context.mounted) setState(() {}); messenger.showSnackBar(SnackBar( content: Text('$emulatorName downloaded successfully.'), )); } else if (progress.error != null) { if (context.mounted) setState(() {}); messenger.showSnackBar(SnackBar( content: Text('Failed to download $emulatorName: ${progress.error}'), )); } sub?.cancel(); } }); } ``` -------------------------------- ### Setup Wizard Navigation and Scaffold Source: https://github.com/abduznik/freegosy/wiki/commit-8c1616d Implements the PageView controller for step navigation and the main Scaffold layout with a radial gradient background. ```dart + _pageController.previousPage( + duration: const Duration(milliseconds: 300), + curve: Curves.easeInOut, + ); + setState(() => _currentStep--); + } + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF0f0f0f), + body: Container( + decoration: BoxDecoration( + gradient: RadialGradient( + center: Alignment.topLeft, + radius: 1.5, + colors: [ + Colors.deepPurple.withValues(alpha: 0.15), + Colors.transparent, + ], + ), + ), + child: Column( + children: [ + Expanded( + child: PageView( + controller: _pageController, + physics: const NeverScrollableScrollPhysics(), + children: [ + _buildWelcomeStep(), + _buildServerStep(), + _buildStorageStep(), + _buildFinishStep(), + ], + ), + ), + _buildBottomBar(), + ], + ), + ), + ); + } ``` -------------------------------- ### Handle emulator download completion and errors Source: https://github.com/abduznik/freegosy/wiki/commit-3f0775a In the emulator settings section, this code starts an emulator download and listens to the download provider's stream. It updates the install state and shows a success or failure SnackBar, then cancels the subscription. Requires the `dart:async` import for `StreamSubscription`. ```dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:file_picker/file_picker.dart'; // ... ref.read(downloadProvider.notifier).startEmulatorDownload(emulatorId, emulatorName); // Listen for download completion and update state StreamSubscription? sub; sub = ref.read(downloadProvider.notifier).stream.listen((downloads) { final progress = downloads[emulatorId]; if (progress != null && (progress.isComplete || progress.error != null)) { if (progress.isComplete) { emulatorInstallStates[emulatorId] = true; if (context.mounted) setState(() {}); messenger.showSnackBar(SnackBar( content: Text('$emulatorName downloaded successfully.'), )); } else if (progress.error != null) { if (context.mounted) setState(() {}); messenger.showSnackBar(SnackBar( content: Text('Failed to download $emulatorName: ${progress.error}'), )); } sub?.cancel(); } }); ``` -------------------------------- ### Setup Mock File System for Emulator Strategies Source: https://github.com/abduznik/freegosy/wiki/commit-2ce9c83 Initializes a temporary directory structure for EmuDeck and RetroDeck to test path resolution strategies. ```dart emudeckRoot = Directory(p.join(tempHome.path, 'Emulation')); await emudeckRoot.create(); await Directory(p.join(emudeckRoot.path, 'roms')).create(); await Directory(p.join(emudeckRoot.path, 'tools', 'launchers')).create(recursive: true); await Directory(p.join(emudeckRoot.path, 'bios')).create(); // Mock EmuDeck Save symlink structure for Cemu final cemuSaves = Directory(p.join(emudeckRoot.path, 'saves', 'Cemu', 'saves')); await cemuSaves.create(recursive: true); // Create a dummy launch script final launcher = File(p.join(emudeckRoot.path, 'tools', 'launchers', 'cemu.sh')); await launcher.writeAsString('#!/bin/bash'); // --- Setup Mock RetroDECK Structure --- await Directory(p.join(tempHome.path, 'retrodeck', 'roms')).create(recursive: true); await Directory(p.join(tempHome.path, 'retrodeck', 'tools')).create(recursive: true); // RetroDECK uses Flatpak standard paths retrodeckVarConfig = Directory(p.join(tempHome.path, '.var', 'app', 'net.retrodeck.retrodeck', 'config')); await Directory(p.join(retrodeckVarConfig.path, 'bios')).create(recursive: true); // Mock RetroDECK save structure for PCSX2 await Directory(p.join(retrodeckVarConfig.path, 'PCSX2', 'saves')).create(recursive: true); // Initialize strategies emudeckStrategy = EmuDeckStrategy(); retrodeckStrategy = RetroDeckStrategy(); }); tearDown(() async { // Clean up the fake file tree if (await tempHome.exists()) { await tempHome.delete(recursive: true); } }); ``` -------------------------------- ### Build Emulator List UI Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 Renders a list of emulators with installation status, path overrides, and download triggers. ```dart bool emulatorsLoaded, Map emulatorInstallStates, Function(void Function()) setState, WidgetRef ref, ) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Emulators', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const SizedBox(height: 16), if (!emulatorsLoaded) const Center(child: CircularProgressIndicator()) else ...kEmulatorDefinitions.map((def) { final emulatorId = def['id'] as String; final emulatorName = def['name'] as String; final isInstalled = emulatorInstallStates[emulatorId] ?? false; final overridePath = directoryService.getEmulatorPathOverride(emulatorId); return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: Row( children: [ Icon( isInstalled ? Icons.check_circle : Icons.cancel, color: isInstalled ? Colors.green : Colors.red, ), const SizedBox(width: 8), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(emulatorName), if (overridePath != null) Text( overridePath, style: const TextStyle(fontSize: 11, color: Colors.grey), overflow: TextOverflow.ellipsis, ), ], ), ), IconButton( icon: const Icon(Icons.folder_open, size: 20), tooltip: 'Set custom directory', onPressed: () async { String? selectedDirectory = await FilePicker.platform.getDirectoryPath(); if (selectedDirectory != null) { await directoryService.setEmulatorPathOverride(emulatorId, selectedDirectory); setState(() {}); // Trigger parent state update } }, ), ElevatedButton( onPressed: isInstalled ? null : () async { // Capture context safely before any async operations. final messenger = ScaffoldMessenger.of(context); messenger.showSnackBar(SnackBar( content: Text('Starting download for $emulatorName...'), )); ref.read(downloadProvider.notifier).startEmulatorDownload(emulatorId, emulatorName); // Listen for download completion and update state ref.read(downloadProvider.notifier).stream.listen((downloads) { final progress = downloads[emulatorId]; if (progress != null && progress.isComplete) { // Use safeContext here // Update the map directly. setState will re-render using the updated map. emulatorInstallStates[emulatorId] = true; setState(() {}); // Trigger parent state update messenger.showSnackBar(SnackBar( content: Text('$emulatorName downloaded.'), )); } }); }, child: Text(isInstalled ? 'Installed' : 'Download'), ), ], ), ); }), ], ); } ``` -------------------------------- ### Original _handleLaunch method Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 Original _handleLaunch method. It reads the strategyRegistryProvider synchronously and gets the strategy for the game's platform slug. The diff replaces this method with _startDownload. ```dart Future _handleLaunch(BuildContext context, WidgetRef ref, game) async { final registry = ref.read(strategyRegistryProvider); final strategy = registry?.getStrategyForSlug(game.platformSlug ?? ''); } ``` -------------------------------- ### EdenStrategy launch method (removed) Source: https://github.com/abduznik/freegosy/wiki/commit-965243b This is the removed implementation of the launch method in EdenStrategy. It used to start the emulator process directly, handling Linux launch scripts and .sh files with bash, and used normal process start mode. ```dart final args = [resolvedPath]; if (io.Platform.isLinux && _directoryService.isEmuLaunchScript(exePath)) { return await io.Process.start( 'bash', [exePath, '-e', 'eden', ...args], mode: io.ProcessStartMode.normal, workingDirectory: workingDir, ); } else if (io.Platform.isLinux && exePath.endsWith('.sh')) { return await io.Process.start( 'bash', [exePath, ...args], mode: io.ProcessStartMode.normal, workingDirectory: workingDir, ); } return await io.Process.start( exePath, args, mode: io.ProcessStartMode.normal, workingDirectory: workingDir, ); ``` -------------------------------- ### Execute Custom Emulator Process Source: https://github.com/abduznik/freegosy/wiki/commit-9728917 Uses a raw process start to execute custom emulators that may not follow standard EmuDeck structures. ```dart + final normalizedRomPath = p.absolute(p.normalize(romPath)); + + // We use a raw process start because custom emulators might not be in the standard EmuDeck structure + await io.Process.run(exePath, [normalizedRomPath], runInShell: true); + } +} ``` -------------------------------- ### PCSX2 launchInWindow method with platform-specific handling Source: https://github.com/abduznik/freegosy/wiki/commit-e39958e Similar to launch, this method normalizes paths for Windows and uses original paths elsewhere, returning the started process. ```dart @override Future launchInWindow(Game game, String romPath) async { final exePath = await _directoryService.findEmulatorExecutable( emulatorId, getExecutableForPlatform(), ); if (exePath == null) throw Exception('$name not found. Please download it first.'); if (io.Platform.isWindows) { final normalizedRom = romPath.replaceAll('/', '\\'); final normalizedExe = exePath.replaceAll('/', '\\'); return await Process.start(normalizedExe, [normalizedRom], mode: ProcessStartMode.normal); } else { return await Process.start(exePath, [romPath], mode: ProcessStartMode.normal); } } ``` -------------------------------- ### Storage Setup Step with Platform Presets and Path Selectors Source: https://github.com/abduznik/freegosy/wiki/commit-8c1616d Builds the storage configuration screen. On Linux, it shows preset options (Manual/Native, EmuDeck, RetroDeck) and always provides directory pickers for ROMs and emulators using FilePicker. ```dart Widget _buildStorageStep() { return SingleChildScrollView( padding: const EdgeInsets.all(40.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( 'Storage Setup', style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), const Text( 'Where should we store your games and emulators?', style: TextStyle(color: Colors.grey), ), const SizedBox(height: 40), if (io.Platform.isLinux) ...[ const Text('Platform Preset', style: TextStyle(fontWeight: FontWeight.bold)), const SizedBox(height: 12), _buildPresetOption( id: 'default', title: 'Manual / Native', subtitle: 'Custom paths for everything.', icon: Icons.folder, ), const SizedBox(height: 12), _buildPresetOption( id: 'emudeck', title: 'EmuDeck', subtitle: 'Standard Steam Deck layout.', icon: Icons.sports_esports, ), const SizedBox(height: 12), _buildPresetOption( id: 'retrodeck', title: 'RetroDeck', subtitle: 'Flatpak-based all-in-one.', icon: Icons.grid_view, ), const SizedBox(height: 32), ], _buildPathSelector( label: 'ROMs Directory', currentPath: _romsRoot ?? 'Loading...', onTap: () async { final path = await FilePicker.platform.getDirectoryPath(); if (path != null) setState(() => _romsRoot = path); }, ), const SizedBox(height: 24), _buildPathSelector( label: 'Emulators Directory', currentPath: _emusRoot ?? 'Loading...', onTap: () async { final path = await FilePicker.platform.getDirectoryPath(); if (path != null) setState(() => _emusRoot = path); }, ), ], ), ); } ``` -------------------------------- ### GitHub Actions: Example of Appending Labels Source: https://github.com/abduznik/freegosy/wiki/commit-6ef0279 Example command that appends the labels 'bug' and 'enhancement' to the environment file at '/tmp/runner/env'. This is a concrete example of the previous command. ```bash echo "SELECTED_LABELS=bug,enhancement" >> "/tmp/runner/env" ``` -------------------------------- ### GET /api/devices/{device_id} Source: https://github.com/abduznik/freegosy/blob/main/docs/romm_49_save_sync_research.md Gets information for a specific device. ```APIDOC ## GET /api/devices/{device_id} ### Description Gets information for a specific device. ### Method GET ### Endpoint /api/devices/{device_id} ### Parameters #### Path Parameters - **device_id** (string) - Required - The device identifier. ### Response #### Success Response (200) Returns device information. ``` -------------------------------- ### New _startDownload method Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 New _startDownload method. It reads the rommServiceProvider, shows a snackbar if not connected, constructs a download URL with basic auth, starts the download via downloadProvider.notifier, and shows a snackbar with the game name. It also reads the directoryServiceProvider and schedules a delayed action. ```dart void _startDownload(BuildContext context, WidgetRef ref, Game game) { final service = ref.read(rommServiceProvider); if (service == null) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Not connected to RomM')), ); return; } final url = service.getDownloadUrl(game); final basicAuth = 'Basic ${base64Encode(utf8.encode('${service.config.username}:${service.config.password}'))}'; final headers = {'Authorization': basicAuth}; ref.read(downloadProvider.notifier).startDownload(game, url, headers: headers); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Downloading ${game.name}...')), ); final dirService = ref.read(directoryServiceProvider).asData?.value; if (dirService != null) { Future.delayed(const Duration(seconds: 2), () { // ... (rest of the method is not shown in the diff) }); } } ``` -------------------------------- ### Handle Game Launch with Sync Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 The _handleLaunch method manages the game launch sequence, including registry checks, cloud save synchronization, and process monitoring for auto-syncing saves upon exit. ```dart Future _handleLaunch(BuildContext context, WidgetRef ref, Game game) async { final messenger = ScaffoldMessenger.of(context); // Ensure strategy registry preferences are loaded final registryReady = await ref.read(strategyRegistryProvider.future); if (registryReady == null) return; final strategy = registryReady.getStrategyForSlug(game.platformSlug ?? ''); if (strategy == null) { messenger.showSnackBar( SnackBar( content: Text( 'No emulator configured for ${game.platformDisplayName ?? game.platformSlug ?? 'this platform'}')), ); return; } // Wait for save sync service to be ready (FutureProvider chain) final syncService = await ref.read(saveSyncServiceProvider.future); final dir = await ref.read(directoryServiceProvider.future); if (!context.mounted) return; if (dir == null) { messenger.showSnackBar( const SnackBar(content: Text('Storage service not available')), ); return; } if (syncService != null) { final syncMode = ref.read(retroarchSyncModeProvider); messenger.showSnackBar( SnackBar( content: Text('Pushing saves for ${game.name}...'), duration: const Duration(seconds: 30), ), ); await syncService.pushSaves(game, existingRomPath, syncMode: syncMode); if (!context.mounted) return; messenger.clearSnackBars(); try { final pulled = await syncService.pullSave(game, existingRomPath); if (!context.mounted) return; if (pulled) { messenger.showSnackBar( const SnackBar( content: Text('Cloud save restored'), duration: Duration(seconds: 2)), ); } } catch (e) { // Handle sync error } } try { messenger.showSnackBar( SnackBar( content: Text('Launching ${game.name}...'), duration: const Duration(seconds: 3), ), ); // Try to get process handle for auto-sync when game closes Process? process = await strategy.launchWithHandle(game, existingRomPath); if (process == null) { // Fall back to regular launch if no process handle available await strategy.launch(game, existingRomPath); } else { // Start background Future to handle process exit unawaited(Future.delayed(Duration.zero, () async { try { await process.exitCode; if (!context.mounted) return; messenger.showSnackBar( const SnackBar( content: Text('Auto-syncing saves...'), duration: Duration(seconds: 2), ), ); if (syncService != null) { final syncMode = ref.read(retroarchSyncModeProvider); await syncService.pushSaves(game, existingRomPath, syncMode: syncMode); } if (!context.mounted) return; messenger.showSnackBar( const SnackBar( content: Text('Saves synced'), duration: Duration(seconds: 2), ), ); } catch (e) { // Silently ignore errors in auto-sync } })); } } catch (e) { if (!context.mounted) return; if (e is MissingRetroArchCoreException) { final shouldDownload = await showDialog( context: context, builder: (ctx) => AlertDialog( title: const Text('RetroArch Core Missing'), content: Text( 'The core ${e.coreName} is required for this game but is not installed. Would you like Freegosy to download and install it automatically?'), actions: [ TextButton( onPressed: () => Navigator.of(ctx).pop(false), child: const Text('Cancel'), ), ElevatedButton( ``` -------------------------------- ### Installation rules for executable, libraries, and assets Source: https://github.com/abduznik/freegosy/blob/main/windows/CMakeLists.txt Configures installation of the executable, Flutter ICU data, Flutter library, plugin libraries, native assets, and Flutter assets. Sets the install prefix to the build bundle directory and makes install default for Visual Studio builds. ```cmake # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ``` -------------------------------- ### Device management endpoints Source: https://github.com/abduznik/freegosy/blob/main/docs/romm_49_save_sync_research.md List, get, update, and unregister devices. Requires devices.read for GET and devices.write for PUT/DELETE. ```http GET /api/devices → list all devices GET /api/devices/{device_id} → get device info PUT /api/devices/{device_id} → update name/sync_enabled DELETE /api/devices/{device_id} → unregister ``` -------------------------------- ### GitHub Actions CI workflow for Flutter analyze, test, and Linux build Source: https://github.com/abduznik/freegosy/wiki/commit-25cf195 GitHub Actions workflow that runs on every push and pull request to any branch. The analyze-and-test job runs flutter pub get, flutter analyze --fatal-infos, and flutter test. The build-linux job depends on analyze-and-test and performs a full Linux release build with flutter build linux --release, installing required system packages first. ```yaml name: CI on: push: branches: ["**"] pull_request: branches: ["**"] jobs: analyze-and-test: name: Analyze & Test runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Flutter uses: subosito/flutter-action@v2 with: channel: stable cache: true - name: Install dependencies run: flutter pub get - name: Analyze run: flutter analyze --fatal-infos - name: Run tests run: flutter test build-linux: name: Build Linux runs-on: ubuntu-latest needs: analyze-and-test steps: - name: Checkout uses: actions/checkout@v4 - name: Install Linux build dependencies run: | sudo apt-get update -q sudo apt-get install -y clang cmake ninja-build pkg-config libgtk-3-dev liblzma-dev - name: Set up Flutter uses: subosito/flutter-action@v2 with: channel: stable cache: true - name: Install dependencies run: flutter pub get - name: Build Linux run: flutter build linux --release ``` -------------------------------- ### Start download from RomM service Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 Starts a download from RomM service. Checks if the service is available, shows a snackbar if not connected, then constructs the download URL and basic authentication header using the service's username and password. ```dart void _startDownload(BuildContext context, WidgetRef ref, game) { final service = ref.read(rommServiceProvider); if (service == null) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Not connected to RomM')), ); return; } final url = service.getDownloadUrl(game); final basicAuth = 'Basic ${base64Encode(utf8.encode('${service.config.username}:${service.config.password}'))}'; ``` -------------------------------- ### GET /api/devices Source: https://github.com/abduznik/freegosy/blob/main/docs/romm_49_save_sync_research.md Lists all registered devices. ```APIDOC ## GET /api/devices ### Description Lists all registered devices. ### Method GET ### Endpoint /api/devices ### Response #### Success Response (200) Returns a list of device objects. ``` -------------------------------- ### Diff: onboarding_screen.dart - persist preset and root paths Source: https://github.com/abduznik/freegosy/wiki/commit-5affcc9 Shows the changes to `lib/ui/screens/onboarding_screen.dart`. It now saves the selected Linux preset before setting the root, clears custom paths when using a preset, and saves custom paths when using manual configuration. ```diff diff --git a/lib/ui/screens/onboarding_screen.dart b/lib/ui/screens/onboarding_screen.dart index 37282e8..783158b 100644 --- a/lib/ui/screens/onboarding_screen.dart +++ b/lib/ui/screens/onboarding_screen.dart @@ -138,24 +138,25 @@ class _OnboardingScreenState extends ConsumerState { await SecureStorageService.write('rommApiKey', _apiKeyController.text.trim(), prefs); if (io.Platform.isLinux && _linuxPreset != 'default' && _presetRoot != null) { + await prefs.setString('linuxSyncPreset', _linuxPreset); if (_linuxPreset == 'emudeck') { - _romsRoot = p.join(_presetRoot!, 'roms'); - _emusRoot = p.join(_presetRoot!, 'tools', 'launchers'); await prefs.setString('emudeckRootPath', _presetRoot!); } else if (_linuxPreset == 'retrodeck') { - _romsRoot = p.join(_presetRoot!, 'roms'); - _emusRoot = p.join(_presetRoot!, 'tools'); await prefs.setString('retrodeckRootPath', _presetRoot!); } - await prefs.setString('linuxSyncPreset', _linuxPreset); + // Clear custom paths so DirectoryService uses the preset/root logic + await prefs.remove('romsRootPath'); + await prefs.remove('emulatorsRootPath'); } else if (io.Platform.isLinux) { await prefs.setString('linuxSyncPreset', 'default'); + if (_romsRoot != null) await prefs.setString('romsRootPath', _romsRoot!); + if (_emusRoot != null) await prefs.setString('emulatorsRootPath', _emusRoot!); + } else { + // Non-Linux behavior + if (_romsRoot != null) await prefs.setString('romsRootPath', _romsRoot!); ``` -------------------------------- ### Test setup: stub getLatestSave and pruneOldSaves with keepCount Source: https://github.com/abduznik/freegosy/wiki/commit-8c1616d In the test setup, getLatestSave is stubbed to return null, and pruneOldSaves is stubbed with keepCount parameter. This ensures the service can proceed without remote save data and handles pruning correctly. ```dart when(mockRommService.getLatestSave(any)).thenAnswer((_) async => null); service = SaveSyncService(mockRommService, mockDirectoryService, mockStrategyRegistry, prefs); ``` ```dart when(mockRommService.pruneOldSaves(any, keepCount: anyNamed('keepCount'))).thenAnswer((_) async {}); ``` -------------------------------- ### AzaharStrategy: launch method with macOS app bundle handling Source: https://github.com/abduznik/freegosy/wiki/commit-e39958e Launches the emulator. On macOS, if the executable is a .dylib, throws an exception to switch to RetroArch. If the executable is inside an .app bundle, uses 'open' with --args to launch. Otherwise, starts the process detached. ```dart @override Future launch(Game game, String romPath) async { final exePath = await _directoryService.findEmulatorExecutable( emulatorId, getExecutableForPlatform(), ); if (exePath == null) throw Exception('$name not found. Please download it first.'); if (io.Platform.isMacOS) { if (exePath.endsWith('.dylib')) { throw Exception('Found Azahar Libretro core. Please switch to RetroArch in Settings to play this game.'); } // On macOS, launching via 'open -a App.app --args rom' is much more stable than launching internal binary final parts = exePath.split('/'); final appIdx = parts.indexWhere((p) => p.endsWith('.app')); if (appIdx != -1) { final appBundlePath = parts.sublist(0, appIdx + 1).join('/'); if (await Directory(appBundlePath).exists()) { await _ensure3dsSetup(); await io.Process.run('open', [appBundlePath, '--args', romPath]); return; } } } await _ensure3dsSetup(); await Process.start(exePath, [romPath], mode: ProcessStartMode.detached); } ``` -------------------------------- ### AzaharStrategy: launchWithHandle method with macOS dylib check Source: https://github.com/abduznik/freegosy/wiki/commit-e39958e Launches the emulator and returns a Process handle. On macOS, throws an exception if the executable is a .dylib. Calls _ensure3dsSetup before starting the process in normal mode. ```dart @override Future launchWithHandle(Game game, String romPath) async { final exePath = await _directoryService.findEmulatorExecutable( emulatorId, getExecutableForPlatform(), ); if (exePath == null) throw Exception('$name not found. Please download it first.'); if (io.Platform.isMacOS && exePath.endsWith('.dylib')) { throw Exception('Found Azahar Libretro core. Please switch to RetroArch in Settings to play this game.'); } await _ensure3dsSetup(); return await Process.start(exePath, [romPath], mode: ProcessStartMode.normal); } ``` -------------------------------- ### GET /api/saves/summary Source: https://github.com/abduznik/freegosy/blob/main/docs/romm_49_save_sync_research.md Returns a summary of saves grouped by slot, useful for building a slot picker. ```APIDOC ## GET /api/saves/summary ### Description Returns a summary of saves grouped by slot, useful for building a slot picker. ### Method GET ### Endpoint /api/saves/summary?rom_id={id} ### Parameters #### Query Parameters - **rom_id** (integer) - Required - ROM identifier. ### Response #### Success Response (200) - **total_count** (integer) - Total number of saves. - **slots** (array) - Array of slot summaries, each with: - **slot** (string|null) - Slot name or null. - **count** (integer) - Number of saves in slot. - **latest** (object) - Latest save object (SaveSchema). #### Response Example { "total_count": 6, "slots": [ { "slot": null, "count": 3, "latest": { ...SaveSchema... } }, { "slot": "Main Playthrough", "count": 2, "latest": { ...SaveSchema... } }, { "slot": "autosave", "count": 1, "latest": { ...SaveSchema... } } ] } ``` -------------------------------- ### RetroArchStrategy launchWithHandle and downloadCore Source: https://github.com/abduznik/freegosy/wiki/commit-3850059 Implements process launching with handle support and a method to download and extract RetroArch cores from the Libretro buildbot. ```dart @override Future launchWithHandle(Game game, String romPath) async { final exePath = await _directoryService.findEmulatorExecutable( emulatorId, getExecutableForPlatform()); if (exePath == null) { throw Exception('$name not found. Please download it first.'); } final normalizedExe = exePath.replaceAll('/', r'\'); final normalizedRom = romPath.replaceAll('/', r'\'); final coreName = _getCoreForSlug(game.platformSlug); if (coreName == null) { return await Process.start( normalizedExe, [normalizedRom], mode: ProcessStartMode.normal, ); } final exeDir = File(normalizedExe).parent.path; final corePath = '$exeDir\\cores\\$coreName'; if (!await File(corePath).exists()) { throw MissingRetroArchCoreException( coreName: coreName, corePath: corePath, exePath: normalizedExe, ); } return await Process.start( normalizedExe, ['-L', corePath, normalizedRom], mode: ProcessStartMode.normal, ); } Future downloadCore(String coreName, String coresDir, Dio dio) async { final url = 'https://buildbot.libretro.com/nightly/windows/x86_64/latest/$coreName.zip'; final tempDir = await getTemporaryDirectory(); final zipPath = p.join(tempDir.path, '$coreName.zip'); try { await dio.download(url, zipPath); final bytes = await File(zipPath).readAsBytes(); final archive = ZipDecoder().decodeBytes(bytes); for (final entry in archive) { if (entry.isFile && entry.name.endsWith('.dll')) { final outFile = File('$coresDir\\${entry.name}'); await outFile.parent.create(recursive: true); await outFile.writeAsBytes(entry.content as List); } } } finally { final f = File(zipPath); if (await f.exists()) await f.delete(); } } ``` -------------------------------- ### Launch logic with emulator key mapping and bash script handling Source: https://github.com/abduznik/freegosy/wiki/commit-965243b Shows the launch and launchStandalone methods that map emulator IDs to executable names (e.g., pcsx2 to pcsx2-Qt) and use bash for launch scripts or .sh files. For standalone launches, the working directory is set to the executable's directory when not using bash. ```dart final emuKeyMap = { 'pcsx2': 'pcsx2-Qt', 'retroarch': 'retroarch', 'xemu': 'xemu-emu', 'dolphin': 'dolphin-emu', 'citra': 'citra-qt', 'azahar': 'azahar', 'eden': 'eden', 'ryujinx': 'ryujinx', }; final emuKey = emuKeyMap[emulatorId] ?? emulatorId; return await io.Process.start('bash', [exePath, '-e', emuKey, ...args, romPath], mode: io.ProcessStartMode.normal); } else if (exePath.endsWith('.sh')) { return await io.Process.start('bash', [exePath, ...args, romPath], mode: io.ProcessStartMode.normal); } else { return await io.Process.start(exePath, [...args, romPath], mode: io.ProcessStartMode.normal); } } @override Future launchStandalone(String emulatorId, String exePath, {List args = const []}) async { if (isEmuLaunchScript(exePath)) { final emuKeyMap = { 'pcsx2': 'pcsx2-Qt', 'retroarch': 'retroarch', 'xemu': 'xemu-emu', 'dolphin': 'dolphin-emu', 'citra': 'citra-qt', 'azahar': 'azahar', 'eden': 'eden', 'ryujinx': 'ryujinx', }; final emuKey = emuKeyMap[emulatorId] ?? emulatorId; await io.Process.start('bash', [exePath, '-e', emuKey, ...args], mode: io.ProcessStartMode.detached); } else if (exePath.endsWith('.sh')) { await io.Process.start('bash', [exePath, ...args], mode: io.ProcessStartMode.detached); } else { final exeDir = io.File(exePath).parent.path; await io.Process.start(exePath, args, mode: io.ProcessStartMode.detached, workingDirectory: exeDir); } } } ``` -------------------------------- ### Setup Configuration Template Source: https://github.com/abduznik/freegosy/blob/main/testing/README.md Copy the template environment file to begin configuring the RomM instance credentials. ```bash cp testing/config/.env.example testing/config/.env # edit testing/config/.env ``` -------------------------------- ### EdenSaveStrategy setup Source: https://github.com/abduznik/freegosy/wiki/commit-38510af Initializes the save strategy for the Eden (Switch) emulator, specifying the save data location. ```dart import 'dart:io'; import 'dart:typed_data'; import 'package:archive/archive.dart'; import 'package:flutter/widgets.dart'; import '../../romm/romm_models.dart'; import '../save_strategy.dart'; /// Save strategy for Eden (Switch) emulator. /// /// Save data is located in: /// AppData/Roaming/eden/nand/user/save/0000000000000000/{profile}/{titleId}/ ``` -------------------------------- ### AzaharStrategy launch method (simplified) Source: https://github.com/abduznik/freegosy/wiki/commit-965243b Fragment from the AzaharStrategy launch method after removing macOS-specific handling. It finds the emulator executable and throws an exception if not found, then ensures the 3DS setup is performed. ```dart final exePath = await _directoryService.findEmulatorExecutable( emulatorId, getExecutableForPlatform(), ); if (exePath == null) throw Exception('$name not found. Please download it first.'); await _ensure3dsSetup(); ``` -------------------------------- ### Setup RommService Test Environment Source: https://github.com/abduznik/freegosy/wiki/commit-2ce9c83 Configures the RommService with a mock Dio adapter for testing API interactions. ```dart import 'package:flutter_test/flutter_test.dart'; import 'package:dio/dio.dart'; import 'package:http_mock_adapter/http_mock_adapter.dart'; import 'package:freegosy/core/romm/romm_models.dart'; import 'package:freegosy/core/romm/romm_service.dart'; void main() { late RommService rommService; late Dio dio; late DioAdapter dioAdapter; const String testBaseUrl = 'https://romm.example.com'; const String testApiKey = 'test_api_key_12345'; setUp(() { dio = Dio(BaseOptions(baseUrl: testBaseUrl)); dioAdapter = DioAdapter(dio: dio); final config = RomMConfig( baseUrl: testBaseUrl, username: '', password: '', apiKey: testApiKey, ); rommService = RommService(config, dio: dio); }); ``` -------------------------------- ### onboarding_screen.dart: add preset root path handling Source: https://github.com/abduznik/freegosy/wiki/commit-481ba0f Adds a '_presetRoot' field and logic to load the emudeck or retrodeck root path from preferences based on the selected Linux preset. This is part of the Linux presets feature. ```diff diff --git a/lib/ui/screens/onboarding_screen.dart b/lib/ui/screens/onboarding_screen.dart index f7e8c63..37282e8 100644 --- a/lib/ui/screens/onboarding_screen.dart +++ b/lib/ui/screens/onboarding_screen.dart @@ -1,5 +1,6 @@ import 'dart:io' as io; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:file_picker/file_picker.dart'; import 'package:path/path.dart' as p; @@ -32,6 +33,7 @@ class _OnboardingScreenState extends ConsumerState { // Step 2: Storage Config String? _romsRoot; String? _emusRoot; + String? _presetRoot; String _linuxPreset = 'default'; bool _isStorageInitialized = false; @@ -49,6 +51,12 @@ class _OnboardingScreenState extends ConsumerState { final romsRoot = prefs.getString('romsRootPath'); final emusRoot = prefs.getString('emulatorsRootPath'); final linuxPreset = prefs.getString('linuxSyncPreset') ?? 'default'; + String? presetRoot; + if (linuxPreset == 'emudeck') { + presetRoot = prefs.getString('emudeckRootPath'); + } else if (linuxPreset == 'retrodeck') { + presetRoot = prefs.getString('retrodeckRootPath'); + } if (!mounted) return; @@ -60,6 +68,7 @@ class _OnboardingScreenState extends ConsumerState { if (romsRoot != null) _romsRoot = romsRoot; ``` -------------------------------- ### Onboarding: Adjust preset root when selecting 'emulation' directory Source: https://github.com/abduznik/freegosy/wiki/commit-5affcc9 When the user picks a directory, if the basename is 'emulation' (case-insensitive), the parent directory is used as the preset root. This prevents selecting the 'emulation' subfolder directly. ```dart if (path != null) { var finalPath = path; if (p.basename(finalPath).toLowerCase() == 'emulation') { finalPath = p.dirname(finalPath); } setState(() => _presetRoot = finalPath); } ``` -------------------------------- ### Add setLinuxSyncPreset and setEmudeckRoot methods Source: https://github.com/abduznik/freegosy/wiki/commit-f573f12 Adds asynchronous methods for setting the Linux sync preset and EmuDeck root path to the mock service. ```dart + @override + _i5.Future setLinuxSyncPreset(String? preset) => + (super.noSuchMethod( + Invocation.method(#setLinuxSyncPreset, [preset]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); + + @override + _i5.Future setEmudeckRoot(String? path) => + (super.noSuchMethod( + Invocation.method(#setEmudeckRoot, [path]), + returnValue: _i5.Future.value(), + returnValueForMissingStub: _i5.Future.value(), + ) + as _i5.Future); ``` -------------------------------- ### Emulator Section UI Structure Source: https://github.com/abduznik/freegosy/wiki/commit-357b925 Builds the emulator management section by iterating over emulator definitions and checking installation status. ```dart Widget _buildEmulatorsSection(DirectoryService directoryService) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text('Emulators', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), const SizedBox(height: 16), ...kEmulatorDefinitions.map((def) { final emulatorId = def['id'] as String; final emulatorName = def['name'] as String; final windowsExecutable = def['windows_executable'] as String; return FutureBuilder( future: directoryService.isEmulatorInstalled(emulatorId, windowsExecutable), builder: (context, snapshot) { final isInstalled = snapshot.data ?? false; return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), ```