Manic EMU is an all-in-one retro game emulator for iOS. It packs powerful features while keeping a clean, sleek UI and delivering buttery-smooth gameplay.
Swift
Reconstruct iCloud sync
Daiunoa69d75bef701
diff --git a/ManicEmu/ManicEmu.xcodeproj/project.pbxproj b/ManicEmu/ManicEmu.xcodeproj/project.pbxprojindex 0e92239f..b9b0f0f5 100644--- a/ManicEmu/ManicEmu.xcodeproj/project.pbxproj+++ b/ManicEmu/ManicEmu.xcodeproj/project.pbxproj@@ -1465,6 +1465,27 @@57E9632A2D6B01450022914C /* ImportFileCollectionViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57E963292D6B013B0022914C /* ImportFileCollectionViewCell.swift */; };57E9632C2D6B06320022914C /* ImportFooterCollectionReusableView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57E9632B2D6B06090022914C /* ImportFooterCollectionReusableView.swift */; };57E9632E2D6B0B8A0022914C /* SparkleSeperatorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57E9632D2D6B0B7D0022914C /* SparkleSeperatorView.swift */; };+ 57EBA5533052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5523052D8AA0017A6C3 /* FilesSyncManager.swift */; };+ 57EBA5543052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5523052D8AA0017A6C3 /* FilesSyncManager.swift */; };+ 57EBA5553052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5523052D8AA0017A6C3 /* FilesSyncManager.swift */; };+ 57EBA5613052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5603052D8AA0017A6C3 /* FilesSyncPolicy.swift */; };+ 57EBA5623052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5603052D8AA0017A6C3 /* FilesSyncPolicy.swift */; };+ 57EBA5633052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5603052D8AA0017A6C3 /* FilesSyncPolicy.swift */; };+ 57EBA5653052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5643052D8AA0017A6C3 /* FilesSyncIndex.swift */; };+ 57EBA5663052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5643052D8AA0017A6C3 /* FilesSyncIndex.swift */; };+ 57EBA5673052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5643052D8AA0017A6C3 /* FilesSyncIndex.swift */; };+ 57EBA5693052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5683052D8AA0017A6C3 /* FilesSyncEngine.swift */; };+ 57EBA56A3052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5683052D8AA0017A6C3 /* FilesSyncEngine.swift */; };+ 57EBA56B3052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5683052D8AA0017A6C3 /* FilesSyncEngine.swift */; };+ 57EBA56D3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA56C3052D8AA0017A6C3 /* FilesSyncIO.swift */; };+ 57EBA56E3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA56C3052D8AA0017A6C3 /* FilesSyncIO.swift */; };+ 57EBA56F3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA56C3052D8AA0017A6C3 /* FilesSyncIO.swift */; };+ 57EBA5713052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5703052D8AA0017A6C3 /* FilesSyncWatchers.swift */; };+ 57EBA5723052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5703052D8AA0017A6C3 /* FilesSyncWatchers.swift */; };+ 57EBA5733052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5703052D8AA0017A6C3 /* FilesSyncWatchers.swift */; };+ 57EBA5753052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5743052D8AA0017A6C3 /* FilesSyncRecord.swift */; };+ 57EBA5763052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5743052D8AA0017A6C3 /* FilesSyncRecord.swift */; };+ 57EBA5773052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EBA5743052D8AA0017A6C3 /* FilesSyncRecord.swift */; };57EC6AA62D801F56002920F0 /* GamesListBlankSlateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EC6AA52D801F4D002920F0 /* GamesListBlankSlateView.swift */; };57EC6AB82D803810002920F0 /* PlayHistoryBlankSlateView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EC6AB72D8037FE002920F0 /* PlayHistoryBlankSlateView.swift */; };57EC6AC82D8119D9002920F0 /* SyncManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57EC6AC72D8119D8002920F0 /* SyncManager.swift */; };@@ -1971,7 +1992,6 @@575A39CD2DCD00FE00B28FC2 /* OnlineCoverManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnlineCoverManager.swift; sourceTree = "<group>"; };575A39CF2DCD2B3500B28FC2 /* UIImageViewExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIImageViewExtensions.swift; sourceTree = "<group>"; };575A39D32DCD9C7000B28FC2 /* LibretroCoverSearchView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LibretroCoverSearchView.swift; sourceTree = "<group>"; };- 575A3A422DCEE9F300B28FC2 /* Config-SideloadRelease.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Config-SideloadRelease.xcconfig"; sourceTree = "<group>"; };575F03A62DD59AED00950399 /* manic_joypad.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = manic_joypad.m; path = ../Dependencies/Libretro/input/drivers_joypad/manic_joypad.m; sourceTree = SOURCE_ROOT; };575F03BA2DD5E46B00950399 /* platform_darwin.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = platform_darwin.m; path = ../Dependencies/Libretro/frontend/drivers/platform_darwin.m; sourceTree = SOURCE_ROOT; };575FF8E72D34A6DF0043B2F3 /* System.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = System.swift; sourceTree = "<group>"; };@@ -6612,6 +6632,13 @@57E963292D6B013B0022914C /* ImportFileCollectionViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportFileCollectionViewCell.swift; sourceTree = "<group>"; };57E9632B2D6B06090022914C /* ImportFooterCollectionReusableView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImportFooterCollectionReusableView.swift; sourceTree = "<group>"; };57E9632D2D6B0B7D0022914C /* SparkleSeperatorView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SparkleSeperatorView.swift; sourceTree = "<group>"; };+ 57EBA5523052D8AA0017A6C3 /* FilesSyncManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncManager.swift; sourceTree = "<group>"; };+ 57EBA5603052D8AA0017A6C3 /* FilesSyncPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncPolicy.swift; sourceTree = "<group>"; };+ 57EBA5643052D8AA0017A6C3 /* FilesSyncIndex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncIndex.swift; sourceTree = "<group>"; };+ 57EBA5683052D8AA0017A6C3 /* FilesSyncEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncEngine.swift; sourceTree = "<group>"; };+ 57EBA56C3052D8AA0017A6C3 /* FilesSyncIO.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncIO.swift; sourceTree = "<group>"; };+ 57EBA5703052D8AA0017A6C3 /* FilesSyncWatchers.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncWatchers.swift; sourceTree = "<group>"; };+ 57EBA5743052D8AA0017A6C3 /* FilesSyncRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FilesSyncRecord.swift; sourceTree = "<group>"; };57EC6AA52D801F4D002920F0 /* GamesListBlankSlateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GamesListBlankSlateView.swift; sourceTree = "<group>"; };57EC6AB72D8037FE002920F0 /* PlayHistoryBlankSlateView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayHistoryBlankSlateView.swift; sourceTree = "<group>"; };57EC6AC72D8119D8002920F0 /* SyncManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SyncManager.swift; sourceTree = "<group>"; };@@ -6684,8 +6711,6 @@B28EB6D72A6E7A1C00086CDB /* ManicEmu.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = ManicEmu.entitlements; sourceTree = "<group>"; };B2C97B4D2A09F3B900053A4C /* UIColorExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIColorExtensions.swift; sourceTree = "<group>"; };B2C97B4F2A09F3DE00053A4C /* UIimageExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIimageExtensions.swift; sourceTree = "<group>"; };- B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Config-Debug.xcconfig"; sourceTree = "<group>"; };- B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Config-Release.xcconfig"; sourceTree = "<group>"; };B2F4B7AF2A138C74003B0E07 /* PhotoSaver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PhotoSaver.swift; sourceTree = "<group>"; };B2F4B7B12A147226003B0E07 /* UIViewExtensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIViewExtensions.swift; sourceTree = "<group>"; };B93489E15EFD47F2AE825436 /* Amiga.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Amiga.swift; sourceTree = "<group>"; };@@ -12806,6 +12831,20 @@path = Views;sourceTree = "<group>";};+ 57EBA53E3052D6650017A6C3 /* Sync */ = {+ isa = PBXGroup;+ children = (+ 57EBA5523052D8AA0017A6C3 /* FilesSyncManager.swift */,+ 57EBA5603052D8AA0017A6C3 /* FilesSyncPolicy.swift */,+ 57EBA5643052D8AA0017A6C3 /* FilesSyncIndex.swift */,+ 57EBA5683052D8AA0017A6C3 /* FilesSyncEngine.swift */,+ 57EBA56C3052D8AA0017A6C3 /* FilesSyncIO.swift */,+ 57EBA5703052D8AA0017A6C3 /* FilesSyncWatchers.swift */,+ 57EBA5743052D8AA0017A6C3 /* FilesSyncRecord.swift */,+ );+ path = Sync;+ sourceTree = "<group>";+ };57F0D8402DE2CD7500760F57 /* Cores */ = {isa = PBXGroup;children = (@@ -13042,6 +13081,7 @@A58C3F4D248E448E0099E068 /* Tools */ = {isa = PBXGroup;children = (+ 57EBA53E3052D6650017A6C3 /* Sync */,57F0D8402DE2CD7500760F57 /* Cores */,F0C5000000000000000000FF /* FocusKit */,57E8A110304A4A1100000014 /* JIT */,@@ -13095,10 +13135,7 @@A5A0020024555A5F006E0F0E /* Info.plist */,A5DE1F1A256BC78B0099425B /* InfoPlist.strings */,A5DE1F21256BC7F10099425B /* Localizable.strings */,- B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */,57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */,- B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */,- 575A3A422DCEE9F300B28FC2 /* Config-SideloadRelease.xcconfig */,57E8A110304A4A1100000002 /* JITEnablerExtension.xcconfig */,57C7595C2FD451130093A2B3 /* System.core */,);@@ -14000,6 +14037,13 @@579094C9303C7D9100A53656 /* EmulationCore.swift in Sources */,579094CA303C7D9100A53656 /* GameListView.swift in Sources */,579094CB303C7D9100A53656 /* TriggerButton.swift in Sources */,+ 57EBA5533052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */,+ 57EBA5613052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */,+ 57EBA5653052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */,+ 57EBA5693052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */,+ 57EBA56D3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */,+ 57EBA5713052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */,+ 57EBA5753052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */,579094CC303C7D9100A53656 /* UniversalScript.c in Sources */,579094CD303C7D9100A53656 /* ShaderInfoView.swift in Sources */,579094CE303C7D9100A53656 /* ASListItemView.swift in Sources */,@@ -14455,6 +14499,13 @@57CDCEB22FD5CBD3005BA4C8 /* EmulationCore.swift in Sources */,57CDCEB32FD5CBD3005BA4C8 /* GameListView.swift in Sources */,57CDCEB42FD5CBD3005BA4C8 /* TriggerButton.swift in Sources */,+ 57EBA5543052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */,+ 57EBA5623052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */,+ 57EBA5663052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */,+ 57EBA56A3052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */,+ 57EBA56E3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */,+ 57EBA5723052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */,+ 57EBA5763052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */,57CDCEB52FD5CBD3005BA4C8 /* UniversalScript.c in Sources */,57CDCEB62FD5CBD3005BA4C8 /* ShaderInfoView.swift in Sources */,57C65AEC2FD6B2E300BB73E0 /* ASListItemView.swift in Sources */,@@ -14853,6 +14904,13 @@579C114B2D1D0B1900CFD1F5 /* ApplicationSceneDelegate.swift in Sources */,B2C97B502A09F3DE00053A4C /* UIimageExtensions.swift in Sources */,577006092D3F980400762E8F /* CollectionHeaderReusableView.swift in Sources */,+ 57EBA5553052D8AA0017A6C3 /* FilesSyncManager.swift in Sources */,+ 57EBA5633052D8AA0017A6C3 /* FilesSyncPolicy.swift in Sources */,+ 57EBA5673052D8AA0017A6C3 /* FilesSyncIndex.swift in Sources */,+ 57EBA56B3052D8AA0017A6C3 /* FilesSyncEngine.swift in Sources */,+ 57EBA56F3052D8AA0017A6C3 /* FilesSyncIO.swift in Sources */,+ 57EBA5733052D8AA0017A6C3 /* FilesSyncWatchers.swift in Sources */,+ 57EBA5773052D8AA0017A6C3 /* FilesSyncRecord.swift in Sources */,57B5E3242ECCCD0800DE17E9 /* MAMEKit.swift in Sources */,5796DB4A2FE41A630051F661 /* ASProgress.swift in Sources */,57ABFB622FEBC335001C1425 /* SettingsMembershipView.swift in Sources */,@@ -15190,9 +15248,8 @@};575A3A3F2DCEE98500B28FC2 /* SideloadRelease */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {- APP_BUILD_CONDITIONS = "";ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;@@ -15230,7 +15287,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = SIDE_LOAD;SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15239,9 +15296,8 @@};57909588303C7D9100A53656 /* Debug */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {- APP_BUILD_CONDITIONS = "DEBUG SIDE_LOAD";ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;@@ -15278,7 +15334,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG SIDE_LOAD";SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15287,7 +15343,7 @@};57909589303C7D9100A53656 /* Release */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -15326,7 +15382,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = SIDE_LOAD;SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15335,7 +15391,7 @@};5790958A303C7D9100A53656 /* SideloadRelease */ = {isa = XCBuildConfiguration;- baseConfigurationReference = 575A3A422DCEE9F300B28FC2 /* Config-SideloadRelease.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -15374,7 +15430,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = SIDE_LOAD;SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15690,9 +15746,8 @@};57CDCF762FD5CBD3005BA4C8 /* Debug */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {- APP_BUILD_CONDITIONS = "DEBUG SIDE_LOAD";ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;@@ -15729,7 +15784,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15738,7 +15793,7 @@};57CDCF772FD5CBD3005BA4C8 /* Release */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -15777,7 +15832,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -15786,7 +15841,7 @@};57CDCF782FD5CBD3005BA4C8 /* SideloadRelease */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -15825,7 +15880,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG SIDE_LOAD";SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -16038,7 +16093,7 @@};A5A0020424555A5F006E0F0E /* Debug */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B562A0A420E00053A4C /* Config-Debug.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -16076,7 +16131,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";@@ -16085,7 +16140,7 @@};A5A0020524555A5F006E0F0E /* Release */ = {isa = XCBuildConfiguration;- baseConfigurationReference = B2C97B572A0A423B00053A4C /* Config-Release.xcconfig */;+ baseConfigurationReference = 57BA45C12D1B235400BCA5E1 /* Config-Base.xcconfig */;buildSettings = {ASSETCATALOG_COMPILER_ALTERNATE_APPICON_NAMES = "AppIcon_Dark AppIcon_Retro AppIcon_Color AppIcon_Halloween AppIcon_Xmas AppIcon_Pixel32 AppIcon_ChineseNewYear AppIcon_Lily AppIcon_Rainbow1 AppIcon_Rainbow2 AppIcon_Rainbow3 AppIcon_Unity";ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;@@ -16124,7 +16179,7 @@SUPPORTS_MACCATALYST = NO;SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES;SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;- SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(APP_BUILD_CONDITIONS)";+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = "";SWIFT_OBJC_BRIDGING_HEADER = "$(SRCROOT)/ManicEmu/Sources/Base/Bridging-Header.h";SWIFT_VERSION = 5.0;TARGETED_DEVICE_FAMILY = "1,2";diff --git a/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuRelease.xcscheme b/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuRelease.xcschemeindex 1dccbc7b..3054b601 100644--- a/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuRelease.xcscheme+++ b/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuRelease.xcscheme@@ -31,7 +31,7 @@shouldAutocreateTestPlan = "YES"></TestAction><LaunchAction- buildConfiguration = "Release"+ buildConfiguration = "Debug"selectedDebuggerIdentifier = ""selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"launchStyle = "0"diff --git a/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuSideload.xcscheme b/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuSideload.xcschemeindex fad547de..a10926dd 100644--- a/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuSideload.xcscheme+++ b/ManicEmu/ManicEmu.xcodeproj/xcshareddata/xcschemes/ManicEmuSideload.xcscheme@@ -31,7 +31,7 @@shouldAutocreateTestPlan = "YES"></TestAction><LaunchAction- buildConfiguration = "SideloadRelease"+ buildConfiguration = "Debug"selectedDebuggerIdentifier = ""selectedLauncherIdentifier = "Xcode.IDEFoundation.Launcher.PosixSpawn"launchStyle = "0"diff --git a/ManicEmu/ManicEmu/Resources/Config-Debug.xcconfig b/ManicEmu/ManicEmu/Resources/Config-Debug.xcconfigdeleted file mode 100644index fc7efa21..00000000--- a/ManicEmu/ManicEmu/Resources/Config-Debug.xcconfig+++ /dev/null@@ -1,16 +0,0 @@-//-// ConfigDebug.xcconfig-// ManicEmu-//-// Created by Aoshuang Lee on 2023/5/9.-// Copyright © 2023 Aoshuang Lee. All rights reserved.-//-// SPDX-License-Identifier: AGPL-3.0-or-later--// Configuration settings file format documentation can be found at:-// https://help.apple.com/xcode/#/dev745c5c974-#include "ManicEmu/Resources/Config-Base.xcconfig"--APP_BUILD_CONDITIONS = DEBUG SIDE_LOAD-// SIDE_LOAD is set on ManicEmuDebug / ManicEmuSideload target settings only.-// Do not enable it here: ManicEmuRelease Debug also includes this file.diff --git a/ManicEmu/ManicEmu/Resources/Config-Release.xcconfig b/ManicEmu/ManicEmu/Resources/Config-Release.xcconfigdeleted file mode 100644index f2a308b9..00000000--- a/ManicEmu/ManicEmu/Resources/Config-Release.xcconfig+++ /dev/null@@ -1,12 +0,0 @@-//-// Config-Realeas.xcconfig-// ManicEmu-//-// Created by Aoshuang Lee on 2023/5/9.-// Copyright © 2023 Aoshuang Lee. All rights reserved.-//-// SPDX-License-Identifier: AGPL-3.0-or-later--// Configuration settings file format documentation can be found at:-// https://help.apple.com/xcode/#/dev745c5c974-#include "ManicEmu/Resources/Config-Base.xcconfig"diff --git a/ManicEmu/ManicEmu/Resources/Config-SideloadRelease.xcconfig b/ManicEmu/ManicEmu/Resources/Config-SideloadRelease.xcconfigdeleted file mode 100644index 7ef976ec..00000000--- a/ManicEmu/ManicEmu/Resources/Config-SideloadRelease.xcconfig+++ /dev/null@@ -1,15 +0,0 @@-//-// Config-SideloadRelease.xcconfig-// ManicEmu-//-// Created by Daiuno on 2025/5/10.-// Copyright © 2025 Manic EMU. All rights reserved.-//-// SPDX-License-Identifier: AGPL-3.0-or-later--// Configuration settings file format documentation can be found at:-// https://help.apple.com/xcode/#/dev745c5c974--#include "ManicEmu/Resources/Config-Base.xcconfig"--APP_BUILD_CONDITIONS = SIDE_LOADdiff --git a/ManicEmu/ManicEmu/Resources/en.lproj/Localizable.strings b/ManicEmu/ManicEmu/Resources/en.lproj/Localizable.stringsindex a6d65fbc..804afaf9 100644--- a/ManicEmu/ManicEmu/Resources/en.lproj/Localizable.strings+++ b/ManicEmu/ManicEmu/Resources/en.lproj/Localizable.strings@@ -1129,3 +1129,22 @@ Press the controller button to complete mapping...";"SlowMotionRatio" = "Slow Motion %@";"SlowMotionSpeedLimit" = "Maximum speed limited to 2x! Upgrade to Premium for 5x slow motion";"SlowMotionDesc" = "Slow motion has lower priority than fast forward. If fast forward is enabled, slow motion turns off automatically.";++"ICloudROMSyncSetting" = "ROM Sync Settings";+"ICloudROMSyncDesc" = "ROM sync is on by default. Turning it off stops future uploads. You can choose whether to remove existing copies from iCloud Drive. Local files stay on this device.";+"ICloudROMPlatformConfig" = "Platform Settings";+"ICloudROMGameConfig" = "Game Settings";+"ICloudROMRemoveDriveTitle" = "Remove from iCloud Drive?";+"ICloudROMRemoveDriveDetail" = "This only deletes the iCloud Drive copy to free space. The ROM stays on this device. Other devices that already downloaded it keep their local copies.";+"ICloudROMRemoveDriveConfirm" = "Remove from iCloud Drive";+"ICloudROMKeepDrive" = "Keep iCloud Copy";+"ICloudSyncPaused" = "iCloud Sync Paused";+"ICloudSyncProgressFormat" = "%d/%d";+"ICloudRepairSync" = "Repair Sync";+"ICloudRepairSyncDesc" = "Compares local files with iCloud Drive and retries uploads or downloads that failed or were missed. Progress appears above. Use this if a ROM did not appear in iCloud after import, or after the device was offline.";+"ICloudRepairSyncInProgress" = "Repair is already in progress.";+"ICloudRepairSyncNotReady" = "iCloud sync is still starting. Try again in a moment.";+"ICloudRepairSyncAlreadyDone" = "Local files and iCloud Drive already match.";+"ICloudRepairSyncResult" = "Repair finished. Uploaded %d, downloaded %d.";+"ICloudRepairSyncResultPending" = "Repair finished. Uploaded %d, downloaded %d. %d files will retry later.";+"ICloudROMStillSyncing" = "This ROM is still downloading from iCloud. Try again in a moment.";diff --git a/ManicEmu/ManicEmu/Resources/zh-Hans.lproj/Localizable.strings b/ManicEmu/ManicEmu/Resources/zh-Hans.lproj/Localizable.stringsindex c5e53200..3553a371 100644--- a/ManicEmu/ManicEmu/Resources/zh-Hans.lproj/Localizable.strings+++ b/ManicEmu/ManicEmu/Resources/zh-Hans.lproj/Localizable.strings@@ -1124,3 +1124,23 @@"SlowMotionRatio" = "慢放%@";"SlowMotionSpeedLimit" = "你的最高慢放是x2!请升级成为会员解锁最高x5倍慢放";"SlowMotionDesc" = "慢放的优先级低于加速。如果开启了加速,慢放会自动关闭。";++"ICloudROMSyncSetting" = "ROM 同步配置";+"ICloudROMSyncDesc" = "ROM 默认同步。关闭后将停止后续上传,并可选择是否从 iCloud 云盘移除已有副本。本机文件会保留在此设备上。";+"ICloudROMPlatformConfig" = "平台设置";+"ICloudROMGameConfig" = "游戏设置";+"ICloudROMRemoveDriveTitle" = "要从 iCloud 云盘移除吗?";+"ICloudROMRemoveDriveDetail" = "此操作只会删除 iCloud 云盘中的副本以释放空间。ROM 仍会保留在本机。其他设备上已下载的本地副本不会受影响。";+"ICloudROMRemoveDriveConfirm" = "从 iCloud 云盘移除";+"ICloudROMKeepDrive" = "保留 iCloud 副本";+"ICloudSyncPaused" = "iCloud 同步已暂停";+"ICloudSyncProgressFormat" = "%d/%d";+"ICloudRepairSync" = "修复同步";+"ICloudRepairSyncDesc" = "将本机文件与 iCloud 云盘进行比对,并重试失败或遗漏的上传和下载。进度显示在上方。如果导入后 ROM 未出现在 iCloud,或设备曾离线,可使用此功能。";+"ICloudRepairSyncInProgress" = "修复已在进行中。";+"ICloudRepairSyncNotReady" = "iCloud 同步仍在启动,请稍后再试。";+"ICloudRepairSyncAlreadyDone" = "本机文件与 iCloud 云盘已一致。";+"ICloudRepairSyncResult" = "修复完成。已上传 %d 个,已下载 %d 个。";+"ICloudRepairSyncResultPending" = "修复完成。已上传 %d 个,已下载 %d 个。另有 %d 个文件稍后重试。";+"ICloudROMStillSyncing" = "此 ROM 仍在从 iCloud 下载,请稍后再试。";+diff --git a/ManicEmu/ManicEmu/Sources/Base/ApplicationSceneDelegate.swift b/ManicEmu/ManicEmu/Sources/Base/ApplicationSceneDelegate.swiftindex 71557606..6d4a0b53 100644--- a/ManicEmu/ManicEmu/Sources/Base/ApplicationSceneDelegate.swift+++ b/ManicEmu/ManicEmu/Sources/Base/ApplicationSceneDelegate.swift@@ -85,6 +85,10 @@ class ApplicationSceneDelegate: UIResponder, UIWindowSceneDelegate {}}+ func sceneDidBecomeActive(_ scene: UIScene) {+ FilesSyncManager.shared.handleDidBecomeActive()+ }+func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {for URLContext in URLContexts {let url = URLContext.urldiff --git a/ManicEmu/ManicEmu/Sources/Base/Constants.swift b/ManicEmu/ManicEmu/Sources/Base/Constants.swiftindex f9c8fc9b..82c0fef3 100644--- a/ManicEmu/ManicEmu/Sources/Base/Constants.swift+++ b/ManicEmu/ManicEmu/Sources/Base/Constants.swift@@ -449,6 +449,11 @@ extension _R {static let ZipWorkSpace = Temp.appendingPathComponent("ZipWorkSpace")static let Realm = Library.appendingPathComponent("Realm")static let RealmFilePath = Realm.appendingPathComponent("default.realm")+ static let FilesSync = Library.appendingPathComponent("FilesSync")+ static let FilesSyncIndex = FilesSync.appendingPathComponent("index.json")+ static let FilesSyncPending = FilesSync.appendingPathComponent("pending.json")+ static let ManicSync = Document.appendingPathComponent(".manic-sync")+ static let FilesSyncConflicts = ManicSync.appendingPathComponent("conflicts")static let Resource = Library.appendingPathComponent("System.bundle")static let ThreeDS = Document.appendingPathComponent("3DS")static let ThreeDSSystemData = ThreeDS.appendingPathComponent("sysdata")diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASIcon.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASIcon.swiftindex 8fe77c08..f25eb654 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASIcon.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASIcon.swift@@ -65,14 +65,13 @@ enum ASIcon {}}- static func imageConfig(size: CGFloat, weight: UIImage.SymbolWeight, colors: [UIColor]) -> UIImage.SymbolConfiguration {- var symbolConfig = UIImage.SymbolConfiguration(pointSize: size, weight: weight)- if colors.count > 0 {- symbolConfig = symbolConfig.applying(UIImage.SymbolConfiguration(paletteColors: colors))- } else {- symbolConfig = symbolConfig.applying(UIImage.SymbolConfiguration(paletteColors: [R.Color.LabelPrimary]))+ static func imageConfig(size: CGFloat? = nil, weight: UIImage.SymbolWeight, colors: [UIColor]) -> UIImage.SymbolConfiguration {+ let palette = colors.isEmpty ? [R.Color.LabelPrimary] : colors+ let colorConfig = UIImage.SymbolConfiguration(paletteColors: palette)+ if let size, size > .ulpOfOne {+ return UIImage.SymbolConfiguration(pointSize: size, weight: weight).applying(colorConfig)}- return symbolConfig+ return UIImage.SymbolConfiguration(weight: weight).applying(colorConfig)}///If no color is set inside the icon, the passed-in color will be used for updating.diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASListPage.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASListPage.swiftindex 3fe4cc99..efb7702a 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASListPage.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ASListPage.swift@@ -290,7 +290,7 @@ extension ASListPage {chevronTitle: String? = nil) -> Self {var styles = [Style]()if let icon {- styles.append(.icon(icon, iconSize: iconSize))+ styles.append(.icon(icon, iconSize: .fixSize(CGSize(iconSize))))}if let title {styles.append(.title(.largeText(title, color: titleColor)))@@ -323,6 +323,7 @@ extension ASListPage {///icon: 24x24 title: 15 mediumstatic func iconTitleDetailSwitchCell(icon: ASIcon? = nil,+ iconSize: ASListPage.Cell.Style.IconSize = .fixSize(CGSize(R.Size.ButtonExtraExtraSmall)),title: String? = nil,titleColor: UIColor = R.Color.LabelPrimary,detail: String? = nil,@@ -331,7 +332,7 @@ extension ASListPage {enablePressEffect: Bool = true) -> Self {var styles = [Style]()if let icon {- styles.append(.icon(icon))+ styles.append(.icon(icon, iconSize: iconSize))}if let title {styles.append(.title(.largeText(title, color: titleColor)))@@ -352,7 +353,7 @@ extension ASListPage {enablePressEffect: Bool = true) -> Self {var styles = [Style]()if let icon {- styles.append(.icon(icon, iconSize: iconSize))+ styles.append(.icon(icon, iconSize: .fixSize(CGSize(iconSize))))}if let title {styles.append(.title(.largeText(title, color: titleColor)))@@ -463,7 +464,7 @@ extension ASListPage {isSelected: Bool = false) -> Self {var styles = [Style]()if let icon {- styles.append(.icon(icon, iconSize: iconSize))+ styles.append(.icon(icon, iconSize: .fixSize(CGSize(iconSize))))}if let title {styles.append(.title(.largeText(title, color: titleColor)))@@ -492,7 +493,13 @@ extension ASListPage {}enum Style {- case icon(ASIcon, iconSize: CGFloat = R.Size.ButtonExtraExtraSmall)+ enum IconSize: Equatable {+ case fixHeight(CGFloat)+ case fixSize(CGSize)+ case autoLayout+ }++ case icon(ASIcon, iconSize: IconSize = .fixSize(CGSize(R.Size.ButtonExtraExtraSmall)))case title(ASText, subTitle: ASText? = nil, subtitleFollows: Bool = true, enabledInteraction: Bool = false)case detail(ASText, enabledInteraction: Bool = false)case button(ASButton)@@ -504,7 +511,7 @@ extension ASListPage {case progress(ASProgress) //0-1case segment(ASSegment)- var iconValue: (ASIcon, iconSize: CGFloat)? {+ var iconValue: (ASIcon, iconSize: IconSize)? {if case let .icon(icon, iconSize) = self {return (icon, iconSize)}diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swiftindex e3447820..a96e185d 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Models/ExtraKey.swift@@ -88,4 +88,6 @@ enum ExtraKey: String {case dolphinManicInterpretercase autoEnableJITOnLaunchcase slowMotionSpeed+ case iCloudSyncROM+ case iCloudSyncROMPlatforms}diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASIconView.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASIconView.swiftindex 5d6f898a..af75c3f8 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASIconView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASIconView.swift@@ -9,7 +9,20 @@ import Kingfisherclass ASIconView: BaseView {- private let imageView = UIImageView()+ /// Bitmap UIImageView reports image.size as intrinsic; that must never drive this view's layout.+ private final class FillingImageView: UIImageView {+ override var intrinsicContentSize: CGSize {+ CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)+ }+ }++ enum SizeStyle: Equatable {+ case auto+ case fixHeight(CGFloat)+ case fixSize(CGSize)+ }++ private let imageView = FillingImageView()private var defaultContentSize: CGSize = .zerovar icon: ASIcon? = nil {@@ -20,6 +33,15 @@ class ASIconView: BaseView {}}+ /// Declared size policy. `.fixHeight` makes intrinsic width follow height × image aspect.+ var sizeStyle: SizeStyle = .auto {+ didSet {+ guard oldValue != sizeStyle else { return }+ invalidateIntrinsicContentSize()+ setNeedsLayout()+ }+ }+var animated = false {didSet {applyAnimated()@@ -30,12 +52,15 @@ class ASIconView: BaseView {init(_ icon: ASIcon? = nil) {self.icon = iconsuper.init(frame: .zero)+ translatesAutoresizingMaskIntoConstraints = falsesetContentHuggingPriority(.required, for: .horizontal)setContentHuggingPriority(.required, for: .vertical)setContentCompressionResistancePriority(.required, for: .horizontal)setContentCompressionResistancePriority(.required, for: .vertical)+ imageView.clipsToBounds = true+addSubview(imageView)imageView.snp.makeConstraints { make inmake.edges.equalToSuperview()@@ -49,8 +74,7 @@ class ASIconView: BaseView {}override var intrinsicContentSize: CGSize {- let size = computedIntrinsicContentSize()- return size+ computedIntrinsicContentSize()}override func layoutSubviews() {@@ -62,37 +86,29 @@ class ASIconView: BaseView {// MARK: - Intrinsic sizing- private var contentAspectRatio: CGFloat {+ var contentAspectRatio: CGFloat {guard defaultContentSize.height > .ulpOfOne else { return 1 }return defaultContentSize.width / defaultContentSize.height}- private var hasExplicitLayoutDimension: Bool {- resolvedLayoutDimension(.width) != nil || resolvedLayoutDimension(.height) != nil- }-private func computedIntrinsicContentSize() -> CGSize {guard defaultContentSize.width > .ulpOfOne, defaultContentSize.height > .ulpOfOne else {return .zero}- let width = resolvedLayoutDimension(.width)- let height = resolvedLayoutDimension(.height)-- switch (width, height) {- case (.some, .some):- return CGSize(width: UIView.noIntrinsicMetric, height: UIView.noIntrinsicMetric)- case let (width?, nil):- return CGSize(width: width, height: width / contentAspectRatio)- case let (nil, height?):- return CGSize(width: height * contentAspectRatio, height: height)- case (nil, nil):+ switch sizeStyle {+ case .auto:return defaultContentSize+ case .fixHeight(let height):+ return CGSize(width: height * contentAspectRatio, height: height)+ case .fixSize(let size):+ return size}}// MARK: - Layout dimension resolution+ /// Laid-out size for symbol pointSize.private func resolvedLayoutDimension(_ attribute: NSLayoutConstraint.Attribute) -> CGFloat? {switch attribute {case .width where bounds.width > .ulpOfOne:@@ -103,32 +119,16 @@ class ASIconView: BaseView {break}- if let value = explicitConstraintConstant(for: attribute, in: constraints) {- return value- }- if let superview, let value = explicitConstraintConstant(for: attribute, in: superview.constraints) {- return value- }- return nil- }-- private func explicitConstraintConstant(- for attribute: NSLayoutConstraint.Attribute,- in constraints: [NSLayoutConstraint]- ) -> CGFloat? {- for constraint in constraints where constraint.isActive && constraint.relation == .equal {- if constraint.firstItem as AnyObject === self,- constraint.firstAttribute == attribute,- constraint.secondItem == nil {- return constraint.constant- }- if constraint.secondItem as AnyObject === self,- constraint.secondAttribute == attribute,- constraint.firstItem == nil {- return constraint.constant- }+ switch sizeStyle {+ case .fixHeight(let height) where attribute == .height:+ return height+ case .fixSize(let size) where attribute == .width:+ return size.width+ case .fixSize(let size) where attribute == .height:+ return size.height+ default:+ return nil}- return nil}// MARK: - Icon content@@ -139,22 +139,23 @@ class ASIconView: BaseView {guard let icon else {imageView.image = nilimageView.preferredSymbolConfiguration = nil+ imageView.tintColor = nildefaultContentSize = .zeroreturn}switch icon {- case .symbol(let symbol, _, _, _, _):+ case .symbol(let symbol, let weight, let colors, _, _):let defaultImage = UIImage(systemSymbol: symbol)defaultContentSize = defaultImage.size- imageView.preferredSymbolConfiguration = nilimageView.image = defaultImage+ applySymbolAppearance(weight: weight, colors: colors)- case .symbolImage(let symbolImage, _, _, _, _):+ case .symbolImage(let symbolImage, let weight, let colors, _, _):let symbolImage = symbolImage ?? R.image.logo_iconSymbols() ?? UIImage(systemSymbol: .photo)defaultContentSize = symbolImage.size- imageView.preferredSymbolConfiguration = nilimageView.image = symbolImage+ applySymbolAppearance(weight: weight, colors: colors)case .image(let image, let color, _):let image = image ?? R.image.logo_iconSymbols() ?? UIImage(systemSymbol: .photo)@@ -171,57 +172,40 @@ class ASIconView: BaseView {case .imageUrl(let url, let processSize, _):imageView.preferredSymbolConfiguration = nil+ imageView.tintColor = nilimageView.contentMode = .scaleAspectFilldefaultContentSize = processSizeimageView.kf.setImage(with: url, options: [.processor(DownsamplingImageProcessor(size: processSize))])}}- /// Only apply a SymbolConfiguration with pointSize to vector icons when the user specifies a width or height.+ /// Palette must always be applied; otherwise SF Symbols fall back to the window tintColor.+ /// pointSize is optional and only attached when a layout dimension is known.+ private func applySymbolAppearance(weight: UIImage.SymbolWeight, colors: [UIColor], pointSize: CGFloat? = nil) {+ let palette = colors.isEmpty ? [R.Color.LabelPrimary] : colors+ imageView.tintColor = palette[0]+ imageView.preferredSymbolConfiguration = ASIcon.imageConfig(size: pointSize, weight: weight, colors: palette)+ }+private func applyVectorSymbolConfigurationIfNeeded() {guard let icon else { return }- guard hasExplicitLayoutDimension, let pointSize = resolvedSymbolPointSize() else {- switch icon {- case .symbol(let symbol, _, _, _, _):- imageView.preferredSymbolConfiguration = nil- imageView.image = UIImage(symbol: symbol)-- case .symbolImage(let symbolImage, _, _, _, _):- imageView.preferredSymbolConfiguration = nil- imageView.image = symbolImage-- case .image, .imageUrl:- break- }- return- }-+ let pointSize = resolvedSymbolPointSize()switch icon {case .symbol(let symbol, let weight, let colors, _, _):- let symbolImage = UIImage(systemSymbol: symbol)- imageView.image = symbolImage- imageView.preferredSymbolConfiguration = ASIcon.imageConfig(- size: pointSize,- weight: weight,- colors: colors- )+ imageView.image = UIImage(systemSymbol: symbol)+ applySymbolAppearance(weight: weight, colors: colors, pointSize: pointSize)case .symbolImage(let symbolImage, let weight, let colors, _, _):imageView.image = symbolImage- imageView.preferredSymbolConfiguration = ASIcon.imageConfig(- size: pointSize,- weight: weight,- colors: colors- )+ applySymbolAppearance(weight: weight, colors: colors, pointSize: pointSize)+case .image, .imageUrl:break}}private func resolvedSymbolPointSize() -> CGFloat? {- guard hasExplicitLayoutDimension else { return nil }-let width = resolvedLayoutDimension(.width)let height = resolvedLayoutDimension(.height)diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASListItemView.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASListItemView.swiftindex 94603388..e8c389ab 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASListItemView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Views/ASListItemView.swift@@ -121,7 +121,7 @@ class ASListItemView: BaseView {private var groupGuide: UILayoutGuide? = nil///icon default size- private var iconSize: CGFloat = R.Size.ButtonExtraExtraSmall+ private var iconSize: ASListPage.Cell.Style.IconSize = .fixSize(CGSize(R.Size.ButtonExtraExtraSmall))///accessory horizontal spacingprivate let accessorySpacing = R.Size.ContentSpaceMedium///icon text spacing@@ -148,7 +148,7 @@ class ASListItemView: BaseView {}let hasIcon: Bool- let iconSize: CGFloat+ let iconSize: ASListPage.Cell.Style.IconSizelet hasTitle: Boollet hasSubTitle: Boollet subtitleFollows: Bool@@ -181,7 +181,7 @@ class ASListItemView: BaseView {}var hasIcon = false- var iconSize = R.Size.ButtonExtraExtraSmall+ var iconSize: ASListPage.Cell.Style.IconSize = .fixSize(CGSize(R.Size.ButtonExtraExtraSmall))if case let .icon(_, size) = icon {hasIcon = trueiconSize = size@@ -354,7 +354,9 @@ class ASListItemView: BaseView {/// Structure unchanged: update leaf content in place without detaching views or rebuilding constraints.private func applyContentUpdates(parsed: ParsedStyles) {- _ = configureIcon(from: parsed.icon)+ if let iconView = configureIcon(from: parsed.icon) {+ applyIconPositionAndSize(iconView)+ }updateTextContentInPlace(title: parsed.title, detail: parsed.detail)updateAccessoriesInPlace(from: styles)@@ -404,6 +406,14 @@ class ASListItemView: BaseView {} else {iconView?.icon = itemIcon}+ switch iconSize {+ case .fixHeight(let height):+ iconView?.sizeStyle = .fixHeight(height)+ case .fixSize(let size):+ iconView?.sizeStyle = .fixSize(size)+ case .autoLayout:+ iconView?.sizeStyle = .auto+ }return iconView}@@ -691,24 +701,36 @@ class ASListItemView: BaseView {//MARK: - Layout constraints+ private func applyIconPositionAndSize(_ iconView: ASIconView) {+ iconView.snp.remakeConstraints { make in+ make.leading.equalToSuperview()+ make.centerY.equalToSuperview()+ switch iconSize {+ case .fixHeight(let height):+ make.height.equalTo(height)+ make.width.equalTo(iconView.snp.height).multipliedBy(iconView.contentAspectRatio)+ case .fixSize(let size):+ make.size.equalTo(size)+ case .autoLayout:+ make.top.greaterThanOrEqualToSuperview().inset(verticalPadding)+ make.bottom.lessThanOrEqualToSuperview().inset(verticalPadding)+ }+ }+ iconView.invalidateIntrinsicContentSize()+ }+private func layout(iconView: ASIconView?,textBlockContainer: UIView?,accessoryStack: UIStackView?,progressView: ASProgressView?,itemProgress: ASProgress?) {- //icon: Aligned to the leading edge, fixed size, vertically centered relative to the entire line.- // 必须 remake:cell 复用时 iconView 会保留旧的 size 常量约束(常见为默认 24),- // 再用 makeConstraints 叠加新尺寸会冲突,系统往往会打断较大的那个 → ESRP 图标缩成 24。+ // Icon: leading aligned, vertically centered. Remake is required: reused cells keep old+ // size constants (often the default 24); stacking with makeConstraints conflicts and+ // Auto Layout typically drops the larger one, shrinking icons like ESRP to 24.if let iconView {addSubview(iconView)- iconView.snp.remakeConstraints { make in- make.leading.equalToSuperview()- make.size.equalTo(iconSize)- make.centerY.equalToSuperview()- make.top.greaterThanOrEqualToSuperview().inset(verticalPadding)- make.bottom.lessThanOrEqualToSuperview().inset(verticalPadding)- }+ applyIconPositionAndSize(iconView)}//accessory: Keep its own size by trailing, and center it vertically relative to the entire line.diff --git a/ManicEmu/ManicEmu/Sources/Business/Common/Views/PlatformSelectionView.swift b/ManicEmu/ManicEmu/Sources/Business/Common/Views/PlatformSelectionView.swiftindex a762c2a9..6d84d619 100644--- a/ManicEmu/ManicEmu/Sources/Business/Common/Views/PlatformSelectionView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Common/Views/PlatformSelectionView.swift@@ -56,6 +56,9 @@ class PlatformSelectionView: BaseView {Log.debug("[PlatformSelection] using \(globalCoreSwitch.getUsingCoreName(gameType: gameType) ?? "Unknown")(index) core for \(gameType.localizedShortName)")game.defaultCore = index}+#if !SIDE_LOAD+ FilesSyncPolicy.applyDefaultROMSyncFlag(to: game)+#endif}}// Fill PSP game code when switching to PSP.@@ -91,6 +94,9 @@ class PlatformSelectionView: BaseView {for game in games {game.matchCover(force: true)}+#if !SIDE_LOAD+ FilesSyncManager.shared.applyROMSyncAfterGameTypeChange(for: games)+#endif}completion?()})diff --git a/ManicEmu/ManicEmu/Sources/Business/GameInfo/VIews/SaveStateListView.swift b/ManicEmu/ManicEmu/Sources/Business/GameInfo/VIews/SaveStateListView.swiftindex c6c71de9..fd64cec1 100644--- a/ManicEmu/ManicEmu/Sources/Business/GameInfo/VIews/SaveStateListView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/GameInfo/VIews/SaveStateListView.swift@@ -325,7 +325,7 @@ class SaveStateListView: BaseView {var styles = [ASListPage.Cell.Style]()styles.append(.icon(.image(.tryDataImageOrPlaceholder(tryData: saveState.stateCover?.storedData()),cornerStyle: .radius(R.Size.CornerRadiusMicro)),- iconSize: R.Size.ButtonMedium))+ iconSize: .fixSize(CGSize(R.Size.ButtonMedium))))if saveState.isCompatible {styles.append(.title(.largeText(R.string.localizable.gameSaveTitle(index))))} else {diff --git a/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOption.swift b/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOption.swiftindex b55a5fb0..dd006161 100644--- a/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOption.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOption.swift@@ -226,7 +226,7 @@ enum GameOption: Int, CaseIterable {case .symbianDevice:.symbol(.candybarphone)case .slowMotion:- .symbol(.tortoise)+ .symbol(.slowmo)}}diff --git a/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOptionPerform.swift b/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOptionPerform.swiftindex 590cf02d..d8716738 100644--- a/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOptionPerform.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Games/Models/GameOptionPerform.swift@@ -85,11 +85,13 @@ extension GameOption {try? FileManager.safeCopyItem(at: url, to: firstGame.gameSaveUrl, shouldReplace: true)UIView.makeToast(message: R.string.localizable.importGameSaveSuccessTitle())firstGame.processNDSGameSave()+ SyncManager.upload(localFilePath: firstGame.gameSaveUrl.path)})} else {try? FileManager.safeCopyItem(at: url, to: firstGame.gameSaveUrl, shouldReplace: true)UIView.makeToast(message: R.string.localizable.importGameSaveSuccessTitle())firstGame.processNDSGameSave()+ SyncManager.upload(localFilePath: firstGame.gameSaveUrl.path)}}}@@ -113,6 +115,8 @@ extension GameOption {let performDelete = {Game.change { realm infor game in games {+ // Evict Drive copies even if ROM sync was turned off and the cloud file was kept.+ FilesSyncManager.shared.noteGameROMRemoval(for: game)if game.gameType == .symbian {// SIS packages were already uninstalled off the main thread.if !game.ngageRelativeFiles.isEmpty {diff --git a/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameListLandscapeView.swift b/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameListLandscapeView.swiftindex f0b8f36c..96aa769d 100644--- a/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameListLandscapeView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameListLandscapeView.swift@@ -910,7 +910,7 @@ class GameListLandscapeView: BaseView {func radioCell(icon: ASIcon, title: String, selected: Bool) -> ASListPage.Cell {.normal([- .icon(icon, iconSize: R.Size.ButtonSmall),+ .icon(icon, iconSize: .fixSize(CGSize(R.Size.ButtonSmall))),.title(.largeText(title)),.radio(.init(isSelected: selected))])diff --git a/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameMetadataView.swift b/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameMetadataView.swiftindex 3fae1456..b9add8d5 100644--- a/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameMetadataView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Games/Views/GameMetadataView.swift@@ -295,7 +295,7 @@ extension GameMetadataView {private static func makeESRPCell(metadata: GameMetadata) -> ASListPage.Cell {if let rating = metadata.ESRPRating {return .normal([- .icon(rating.icon, iconSize: R.Size.ButtonExtraLarge),+ .icon(rating.icon, iconSize: .fixSize(CGSize(R.Size.ButtonExtraLarge))),.title(.largeText(rating.abbr)),.detail(.extraSmallText(rating.desc, numberOfLines: 0)),.chevron(.init())@@ -309,7 +309,7 @@ extension GameMetadataView {private static func makeESRPOptionCell(rating: ESRP?, isSelected: Bool) -> ASListPage.Cell {if let rating {return .normal([- .icon(rating.icon, iconSize: R.Size.ButtonSmall),+ .icon(rating.icon, iconSize: .fixSize(CGSize(R.Size.ButtonSmall))),.title(.largeText(rating.abbr)),.detail(.extraSmallText(rating.desc, numberOfLines: 0)),.radio(.init(isSelected: isSelected))diff --git a/ManicEmu/ManicEmu/Sources/Business/Import/Views/DownloadManageView.swift b/ManicEmu/ManicEmu/Sources/Business/Import/Views/DownloadManageView.swiftindex 8578ef33..5e711b71 100644--- a/ManicEmu/ManicEmu/Sources/Business/Import/Views/DownloadManageView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Import/Views/DownloadManageView.swift@@ -111,7 +111,7 @@ class DownloadManageView: BaseView {private func getCell(task: DownloadTask) -> ASListPage.Cell {var styles = [ASListPage.Cell.Style]()styles.append(.icon(.image(R.image.file_browser_document()),- iconSize: R.Size.IconSizeExtraLarge.height))+ iconSize: .fixSize(R.Size.IconSizeExtraLarge)))styles.append(.title(.largeText(task.fileName)))if task.status == .failed {styles.append(.detail(.extraSmallText(R.string.localizable.downloadFailed())))diff --git a/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift b/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swiftindex ff6c2787..a8f865bc 100644--- a/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Play/VIewControllers/PlayViewController.swift@@ -161,7 +161,6 @@ class PlayViewController: GameViewController {game.ensurePS1BinCueSheet()if game.isRomExtsts || game.isNDSHomeMenuGame || game.isDOSHomeMenuGame {- UIView.hideLoadingToast(forceHide: true)func showPlayView() {if game.isBIOSMissing() {//检查是否缺失BIOS@@ -261,16 +260,24 @@ class PlayViewController: GameViewController {showPlayView()}} else {+ let availability = FilesSyncManager.shared.romAvailability(for: game)+ if availability == .syncing {+ UIView.makeToast(message: R.string.localizable.iCloudROMStillSyncing())+ }+ if !FilesSyncPolicy.shouldSyncROM(game) {+ if availability != .syncing {+ UIView.makeToast(message: R.string.localizable.loadGameErrorRomNotExist())+ }+ return+ }UIView.makeLoading()- SyncManager.isiCloudFileExist(localFilePath: game.romUrl.path) { fileExists in+ FilesSyncManager.shared.ensureROM(for: game) { error inUIView.hideLoading()- if fileExists {- //rom存在iCloud上- //rom还没离线下来- UIView.makeLoadingToast(message: R.string.localizable.loadingTitle())- SyncManager.download(to: game.romUrl.path) { error in- UIView.hideLoadingToast()- UIView.makeToast(message: R.string.localizable.loadRomSuccess(game.displayName))+ if error == nil, game.isRomExtsts {+ UIView.makeToast(message: R.string.localizable.loadRomSuccess(game.displayName))+ } else if FilesSyncManager.shared.romAvailability(for: game) == .syncing {+ if availability != .syncing {+ UIView.makeToast(message: R.string.localizable.iCloudROMStillSyncing())}} else {UIView.makeToast(message: R.string.localizable.loadGameErrorRomNotExist())@@ -287,9 +294,6 @@ class PlayViewController: GameViewController {triggerProUpdateToken = nilsettingsUpdateToken = nilnotificationTokens.forEach { NotificationCenter.default.removeObserver($0) }- if SyncManager.shared.hasDownloadTask {- UIView.makeLoadingToast(message: R.string.localizable.loadingTitle())- }}private init(game: Game, saveState: GameSaveState? = nil) {diff --git a/ManicEmu/ManicEmu/Sources/Business/Settings/Models/SettingItem.swift b/ManicEmu/ManicEmu/Sources/Business/Settings/Models/SettingItem.swiftindex 40c31d3d..60c13f35 100644--- a/ManicEmu/ManicEmu/Sources/Business/Settings/Models/SettingItem.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Settings/Models/SettingItem.swift@@ -20,7 +20,7 @@ struct SettingItem {var enablePressEffect = false//iconstyles.append(.icon(icon,- iconSize: R.Size.ButtonExtraExtraSmall))+ iconSize: .fixSize(CGSize(R.Size.ButtonExtraExtraSmall))))//titlestyles.append(.title(.largeText(title)))//detail@@ -271,6 +271,28 @@ struct SettingItem {return Settings.appearance.desc} else if type == .triggerPro {return R.string.localizable.triggerProDesc()+ } else if type == .iCloud {+#if SIDE_LOAD+ return R.string.localizable.iCloudNotEnable()+#else+ if !Settings.defalut.iCloudSyncEnable {+ return R.string.localizable.iCloudNotEnable()+ }+ let progress = FilesSyncManager.shared.progress+ switch progress.phase {+ case .idle:+ return R.string.localizable.iCloudSynced()+ case .paused:+ return R.string.localizable.iCloudSyncPaused()+ case .unavailable:+ return R.string.localizable.iCloudNotEnable()+ case .scanning, .syncing:+ if progress.totalCount > 0 {+ return R.string.localizable.iCloudSyncing() + " " + R.string.localizable.iCloudSyncProgressFormat(progress.completedCount, progress.totalCount)+ }+ return R.string.localizable.iCloudSyncing()+ }+#endif}return nil}diff --git a/ManicEmu/ManicEmu/Sources/Business/Settings/Models/Settings.swift b/ManicEmu/ManicEmu/Sources/Business/Settings/Models/Settings.swiftindex 96c56c67..ce6435cd 100644--- a/ManicEmu/ManicEmu/Sources/Business/Settings/Models/Settings.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Settings/Models/Settings.swift@@ -48,6 +48,8 @@ class Settings: Object, ObjectUpdatable {///iCloud同步 只会在本地进行存储,意味着一个新设备安装的时候 默认都是false#if SIDE_LOADvar iCloudSyncEnable: Bool = false+ /// UserDefaults only; safe from any thread. Do not read `Settings.defalut` off its Realm thread.+ static var iCloudSyncEnableValue: Bool { false }#elsevar iCloudSyncEnable: Bool {set {@@ -65,6 +67,10 @@ class Settings: Object, ObjectUpdatable {UserDefaults.standard.bool(forKey: "iCloudSyncEnable")}}+ /// UserDefaults only; safe from any thread. Do not read `Settings.defalut` off its Realm thread.+ static var iCloudSyncEnableValue: Bool {+ UserDefaults.standard.bool(forKey: "iCloudSyncEnable")+ }#endif///3DS模式 默认兼容模式@Persisted var threeDSMode: ThreeDSMode = .compatibilitydiff --git a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/JITSettingView.swift b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/JITSettingView.swiftindex c31339ed..c6fb090b 100644--- a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/JITSettingView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/JITSettingView.swift@@ -157,7 +157,7 @@ class JITSettingView: BaseView {let jitEnable = LibretroCore.jitAvailable()let statusCell = ASListPage.Cell.normal([- .icon(.symbol(.boltFill, colors: [R.Color.LabelPrimary.forceStyle(.dark)]), iconSize: R.Size.IconSizeLarge.height),+ .icon(.symbol(.boltFill, colors: [R.Color.LabelPrimary.forceStyle(.dark)]), iconSize: .fixSize(R.Size.IconSizeLarge)),.title(.largeText(jitEnable ? R.string.localizable.jitAllow() : R.string.localizable.jitNotAllow(),color: jitEnable ? R.Color.Green : R.Color.Red))], enablePressEffect: false)@@ -360,7 +360,7 @@ class JITSettingView: BaseView {}self?.reloadList()DispatchQueue.main.asyncAfter(delay: 0.35, execute: {- UIView.hideLoadingToast(forceHide: true)+ UIView.hideLoadingToast()})}}diff --git a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/SettingsListView.swift b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/SettingsListView.swiftindex bfaed9d6..8fcd25db 100644--- a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/SettingsListView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/SettingsListView.swift@@ -373,11 +373,13 @@ class SettingsListView: BaseView {}case .iCloud:+#if !SIDE_LOADif UIDevice.isPad {didTapDetailView?(ICloudSettingView(showClose: false))} else {ICloudSettingView.show()}+#endifcase .jit:if UIDevice.isPad {diff --git a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/iCloudSettingView.swift b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/iCloudSettingView.swiftindex 93ae1817..6e5915ad 100644--- a/ManicEmu/ManicEmu/Sources/Business/Settings/Views/iCloudSettingView.swift+++ b/ManicEmu/ManicEmu/Sources/Business/Settings/Views/iCloudSettingView.swift@@ -8,262 +8,30 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport UIKit+import RealmSwift+#if !SIDE_LOADclass ICloudSettingView: BaseView {- class ICloudSettingViewCell: UICollectionViewCell {- private let titleLabel: UILabel = {- let view = UILabel()- return view- }()-- private let enableContainer: UIView = {- let view = UIView()- view.backgroundColor = R.Color.BackgroundSecondary- view.layerCornerRadius = R.Size.CornerRadiusMedium- return view- }()-- var enableSwitchButton: DisabledTapSwitch = {- let view = DisabledTapSwitch()- view.onTintColor = R.Color.Main- view.tintColor = R.Color.BackgroundTertiary- return view- }()-- private let storageLabel: UILabel = {- let view = UILabel()- view.font = R.Font.Caption()- view.textColor = R.Color.LabelSecondary- return view- }()-- private lazy var storageView: UIView = {- let view = UIView()-- let titleContainerView = UIView()- view.addSubview(titleContainerView)- titleContainerView.snp.makeConstraints { make in- make.top.equalToSuperview().offset(R.Size.ContentSpaceTiny)- make.leading.trailing.equalToSuperview()- make.height.equalTo(R.Size.ItemHeightSmall)- }-- let titleLabel = UILabel()- titleLabel.text = R.string.localizable.iCloudUsage()- titleLabel.font = R.Font.Footnote(emphasis: true)- titleLabel.textColor = R.Color.LabelSecondary- titleContainerView.addSubview(titleLabel)- titleLabel.snp.makeConstraints { make in- make.edges.equalToSuperview()- }-- let storageContainer = UIView()- storageContainer.backgroundColor = R.Color.BackgroundSecondary- storageContainer.layerCornerRadius = R.Size.CornerRadiusMedium- view.addSubview(storageContainer)- storageContainer.snp.makeConstraints { make in- make.leading.trailing.equalToSuperview()- make.top.equalTo(titleContainerView.snp.bottom)- make.height.equalTo(R.Size.ItemHeightLarge)- }-- let storageIconView = UIImageView()- storageIconView.contentMode = .center- storageIconView.layerCornerRadius = 6- storageIconView.image = UIImage(symbol: .opticaldiscdriveFill, font: R.Font.Footnote(emphasis: true), color: R.Color.LabelPrimary.forceStyle(.dark))- storageIconView.backgroundColor = R.Color.BackgroundTertiary.forceStyle(.dark)- storageContainer.addSubview(storageIconView)- storageIconView.snp.makeConstraints { make in- make.leading.equalToSuperview().offset(R.Size.ContentSpaceMedium)- make.size.equalTo(R.Size.IconSizeLarge)- make.centerY.equalToSuperview()- }-- let storageTitleLabel = UILabel()- storageTitleLabel.text = R.string.localizable.usage()- storageTitleLabel.textColor = R.Color.LabelPrimary- storageTitleLabel.font = R.Font.Body(emphasis: true)- storageContainer.addSubview(storageTitleLabel)- storageTitleLabel.snp.makeConstraints { make in- make.centerY.equalTo(storageIconView)- make.leading.equalTo(storageIconView.snp.trailing).offset(R.Size.ContentSpaceSmall)- }-- storageContainer.addSubview(storageLabel)- storageLabel.snp.makeConstraints { make in- make.centerY.equalTo(storageIconView)- make.trailing.equalToSuperview().inset(R.Size.ContentSpaceMedium)- }-- view.isHidden = true- return view- }()-- private let detailLabel: UILabel = {- let view = UILabel()- view.numberOfLines = 0- view.text = R.string.localizable.iCloudDesc()- view.font = R.Font.Caption()- view.textColor = R.Color.LabelSecondary- return view- }()-- override init(frame: CGRect) {- super.init(frame: frame)-- let titleContainerView = UIView()- addSubview(titleContainerView)- titleContainerView.snp.makeConstraints { make in- make.leading.top.trailing.equalToSuperview()- make.height.equalTo(R.Size.ItemHeightSmall)- }- titleContainerView.addSubview(titleLabel)- titleLabel.snp.makeConstraints { make in- make.leading.centerY.trailing.equalToSuperview()- }-- addSubview(enableContainer)- enableContainer.snp.makeConstraints { make in- make.leading.trailing.equalToSuperview()- make.top.equalTo(titleContainerView.snp.bottom)- make.height.equalTo(R.Size.ItemHeightLarge)- }-- let enableIconView = UIImageView()- enableIconView.contentMode = .center- enableIconView.layerCornerRadius = 6- let symbol: SFSymbol- if #available(iOS 17.0, *) {- symbol = .arrowTriangle2CirclepathIcloudFill- } else {- symbol = .cloudFill- }- enableIconView.image = UIImage(symbol: symbol, font: R.Font.Footnote(emphasis: true), color: R.Color.LabelPrimary.forceStyle(.dark))- enableIconView.backgroundColor = R.Color.Indigo- enableContainer.addSubview(enableIconView)- enableIconView.snp.makeConstraints { make in- make.leading.equalToSuperview().offset(R.Size.ContentSpaceMedium)- make.size.equalTo(R.Size.IconSizeLarge)- make.centerY.equalToSuperview()- }-- let enableTitleLabel = UILabel()- enableTitleLabel.text = R.string.localizable.iCloudTitle()- enableTitleLabel.textColor = R.Color.LabelPrimary- enableTitleLabel.font = R.Font.Body(emphasis: true)- enableContainer.addSubview(enableTitleLabel)- enableTitleLabel.snp.makeConstraints { make in- make.centerY.equalTo(enableIconView)- make.leading.equalTo(enableIconView.snp.trailing).offset(R.Size.ContentSpaceSmall)- }-- enableContainer.addSubview(enableSwitchButton)- enableSwitchButton.snp.makeConstraints { make in- make.centerY.equalTo(enableIconView)- make.trailing.equalToSuperview().inset(R.Size.ContentSpaceMedium)- if #available(iOS 26.0, tvOS 26.0, *) {- make.size.equalTo(CGSize(width: 63, height: 28))- } else {- make.size.equalTo(CGSize(width: 51, height: 31))- }- }- if #available(iOS 26.0, tvOS 26.0, *) {} else {- enableSwitchButton.transform = CGAffineTransformMakeScale(0.9, 0.9)- }-- addSubview(storageView)- storageView.snp.makeConstraints { make in- make.leading.trailing.equalToSuperview()- make.top.equalTo(enableContainer.snp.bottom)- make.height.equalTo(108)- }-- addSubview(detailLabel)- detailLabel.snp.makeConstraints { make in- make.leading.trailing.equalToSuperview()- make.top.equalTo(enableContainer.snp.bottom).offset(R.Size.ContentSpaceSmall)- }-- }-- required init?(coder: NSCoder) {- fatalError("init(coder:) has not been implemented")- }-- func setDatas() {- var matt = NSMutableAttributedString(string: "")- var detail = R.string.localizable.iCloudNotEnable()- var color = R.Color.LabelSecondary- if Settings.defalut.iCloudSyncEnable && PurchaseManager.isMember {- if SyncManager.shared.syncState == .idle {- detail = R.string.localizable.iCloudSynced()- color = R.Color.Green- } else if SyncManager.shared.syncState == .syncing {- detail = R.string.localizable.iCloudSyncing()- color = R.Color.Yellow- }-- enableSwitchButton.setOn(true, animated: true)-- storageView.isHidden = false-- if let iCloudPath = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.path {- storageLabel.text = FileType.humanReadableFileSize(CacheManager.folderSize(atPath: iCloudPath)) ?? "-"- } else {- storageLabel.text = "-"- }-- detailLabel.snp.updateConstraints { make in- make.top.equalTo(enableContainer.snp.bottom).offset(120)- }- } else {- enableSwitchButton.setOn(false, animated: true)- storageView.isHidden = true- detailLabel.snp.updateConstraints { make in- make.top.equalTo(enableContainer.snp.bottom).offset(R.Size.ContentSpaceSmall)- }- }-- enableSwitchButton.isEnabled = PurchaseManager.isMember-- matt.append(NSAttributedString(string: "●", attributes: [.font: R.Font.Caption(), .foregroundColor: color, .baselineOffset: 1]))- matt.append(NSAttributedString(string: " " + detail, attributes: [.font: R.Font.Footnote(emphasis: true), .foregroundColor: color]))- let style = NSMutableParagraphStyle()- style.lineSpacing = R.Size.ContentSpaceTiny/2- matt = matt.applying(attributes: [.paragraphStyle: style]) as! NSMutableAttributedString- titleLabel.attributedText = matt- }+ private enum MainRow {+ case master+ case progress+ case platform+ case games+ case repair}- private lazy var navigationView: ASNavigationView = {- var navigation = ASListPage.Navigation.defaultNavigation(title: R.string.localizable.iCloudTitle(),- titleIcon: .symbolImage(R.image.icloudsync_iconSymbols()))- navigation.enableClose = showClose- let view = ASNavigationView(navigation)- view.didTapClose = { [weak self] in- guard let self = self else { return }- self.hide()- }- return view- }()+ private let showClose: Bool+ private var iCloudDriveSyncChangeNotification: Any?- private lazy var collectionView: UICollectionView = {- let view = UICollectionView(frame: .zero, collectionViewLayout: createLayout())- view.backgroundColor = .clear- view.contentInsetAdjustmentBehavior = .never- view.register(cellWithClass: ICloudSettingViewCell.self)- view.showsVerticalScrollIndicator = false- view.dataSource = self- view.delegate = self- view.isFocusable = true- view.contentInset = .insets(bottom: UIDevice.isPad ? (R.Size.ContentInsetBottom + R.Size.HomeTabBarSize.height + R.Size.ContentSpaceLarge) : R.Size.ContentInsetBottom)+ private lazy var listPageView: ASListPageView = {+ let view = ASListPageView(getListPage())+ view.didActionOccurred = { [weak self] action in+ self?.handleAction(action)+ }return view}()- private let showClose: Bool- private var iCloudDriveSyncChangeNotification: Any? = nil-deinit {if let iCloudDriveSyncChangeNotification {NotificationCenter.default.removeObserver(iCloudDriveSyncChangeNotification)@@ -273,27 +41,12 @@ class ICloudSettingView: BaseView {required init?(parameters: Any...) {self.showClose = parameters.compactMap({ $0 as? Bool }).first ?? truesuper.init(frame: .zero)-- addSubview(navigationView)- navigationView.snp.makeConstraints { make in- make.leading.trailing.equalTo(safeAreaLayoutGuide)- if showClose {- make.top.equalToSuperview().offset(R.Size.SheetGrabberTopInset)- } else {- make.top.equalToSuperview().offset(R.Size.ContentInsetTop)- }- make.height.equalTo(R.Size.NavigationHeight)- }-- addSubview(collectionView)- collectionView.snp.makeConstraints { make in- make.top.equalTo(navigationView.snp.bottom)- make.leading.trailing.bottom.equalToSuperview()+ addSubview(listPageView)+ listPageView.snp.makeConstraints { make in+ make.edges.equalToSuperview()}-- iCloudDriveSyncChangeNotification = NotificationCenter.default.addObserver(forName: R.NotificationName.iCloudDriveSyncChange, object: nil, queue: .main) { [weak self] _ in- guard let self else { return }- self.collectionView.reloadData()+ iCloudDriveSyncChangeNotification = NotificationCenter.default.addObserver(forName: R.NotificationName.iCloudDriveSyncChange, object: nil, queue: .main) { [weak self] notification in+ self?.handleProgressNotification(notification)}}@@ -305,73 +58,362 @@ class ICloudSettingView: BaseView {fatalError("init(coder:) has not been implemented")}- private func createLayout() -> UICollectionViewLayout {- let layout = UICollectionViewCompositionalLayout { sectionIndex, env in- //item布局- let item = NSCollectionLayoutItem(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1),- heightDimension: .fractionalHeight(1)))-- //group布局- let group = NSCollectionLayoutGroup.horizontal(layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .estimated(280)), subitems: [item])- group.contentInsets = NSDirectionalEdgeInsets(top: 0,- leading: R.Size.ContentSpaceMedium,- bottom: 0,- trailing: R.Size.ContentSpaceMedium)-- //section布局- let section = NSCollectionLayoutSection(group: group)- section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: R.Size.ContentSpaceSmall, trailing: 0)-- return section+ private func reloadList() {+ listPageView.updatePage(getListPage())+ }++ private var isSyncEnabled: Bool {+ Settings.defalut.iCloudSyncEnable && PurchaseManager.isMember+ }++ private func getListPage() -> ASListPage {+ var navigation = ASListPage.Navigation.defaultNavigation(title: R.string.localizable.iCloudTitle(),+ titleIcon: .symbolImage(R.image.icloudsync_iconSymbols()))+ navigation.enableClose = showClose++ var sections: [ASListPage.Section] = [+ ASListPage.Section(cells: [masterCell()],+ footer: .texts([.smallText(R.string.localizable.iCloudDesc(), numberOfLines: 0)], pin: false))+ ]+ if isSyncEnabled {+ var progressSection = ASListPage.Section(cells: [progressCell(FilesSyncManager.shared.progress)])+ progressSection.itemLayout = .fixedHeight(R.Size.ItemHeightExtraLarge)+ sections.append(progressSection)+ sections.append(ASListPage.Section(cells: [+ .iconTitleDetailChevronCell(icon: .symbolImage(R.image.category_iconSymbols()),+ title: R.string.localizable.iCloudROMPlatformConfig()),+ .iconTitleDetailChevronCell(icon: .symbolImage(R.image.games_iconSymbols()),+ title: R.string.localizable.iCloudROMGameConfig())+ ], header: .defaultHeader(title: R.string.localizable.iCloudROMSyncSetting()),+ footer: .texts([.smallText(R.string.localizable.iCloudROMSyncDesc(), numberOfLines: 0)], pin: false)))+ sections.append(ASListPage.Section(cells: [+ .iconTitleDetailChevronCell(icon: .symbolImage(R.image.refresh_iconSymbols()),+ title: R.string.localizable.iCloudRepairSync())+ ], footer: .texts([.smallText(R.string.localizable.iCloudRepairSyncDesc(), numberOfLines: 0)], pin: false)))}- return layout++ let listInsetBottom = (UIDevice.isPad && !showClose) ? R.Size.ContentInsetBottom + R.Size.HomeTabBarSize.height + R.Size.ContentSpaceMedium : 0+ return ASListPage(navigation: navigation,+ sections: sections,+ backgroundColor: .clear,+ listInsets: .insets(bottom: listInsetBottom),+ pageInsets: .insets(top: showClose ? R.Size.SheetGrabberTopInset : R.Size.ContentInsetTop))}-}--extension ICloudSettingView: UICollectionViewDataSource {- func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {- return 1+ private func masterCell() -> ASListPage.Cell {+ let enabled = Settings.defalut.iCloudSyncEnable+ let state: ASSwitch.State+ if !PurchaseManager.isMember {+ state = .disabled+ } else {+ state = enabled ? .on : .off+ }+ let detail: String+ if enabled && PurchaseManager.isMember {+ if let iCloudPath = FileManager.default.url(forUbiquityContainerIdentifier: nil)?.path {+ detail = FileType.humanReadableFileSize(CacheManager.folderSize(atPath: iCloudPath)) ?? R.string.localizable.iCloudSynced()+ } else {+ detail = R.string.localizable.iCloudSynced()+ }+ } else {+ detail = R.string.localizable.iCloudNotEnable()+ }+ return .iconTitleDetailSwitchCell(icon: .symbolImage(R.image.icloudsync_iconSymbols()),+ title: R.string.localizable.iCloudTitle(),+ detail: detail,+ state: state,+ enablePressEffect: false)}- func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {- let cell = collectionView.dequeueReusableCell(withClass: ICloudSettingViewCell.self, for: indexPath)- cell.setDatas()- cell.enableSwitchButton.onChange { [weak cell, weak self] value in- //icloud设置- if value {+ private func progressCell(_ progress: FilesSyncProgress) -> ASListPage.Cell {+ let title: String+ switch progress.phase {+ case .idle:+ title = R.string.localizable.iCloudSynced()+ case .paused:+ title = R.string.localizable.iCloudSyncPaused()+ case .unavailable:+ title = R.string.localizable.iCloudNotEnable()+ case .scanning, .syncing:+ if let name = progress.currentFileName?.components(separatedBy: "/").last, !name.isEmpty {+ title = R.string.localizable.iCloudSyncing() + " · " + name+ } else {+ title = R.string.localizable.iCloudSyncing()+ }+ }+ let total = max(progress.totalCount, 0)+ let completed = min(progress.completedCount, total)+ return .iconTitleProgressCell(icon: .symbolImage(R.image.icloudsync_iconSymbols()),+ title: title,+ progress: .init(value: progress.fraction,+ interaction: .disabled(.small)))+ }++ private func handleProgressNotification(_ notification: Notification) {+ guard isSyncEnabled else { return }+ let progress = (notification.object as? FilesSyncProgress) ?? FilesSyncManager.shared.progress+ guard listPageView.sections.count > 1 else {+ reloadList()+ return+ }+ listPageView.updateCellData(progressCell(progress), indexPath: IndexPath(row: 0, section: 1))+ }++ private func row(at indexPath: IndexPath) -> MainRow? {+ if indexPath.section == 0 { return .master }+ if !isSyncEnabled { return nil }+ if indexPath.section == 1 { return .progress }+ if indexPath.section == 2 {+ return indexPath.row == 0 ? .platform : .games+ }+ if indexPath.section == 3 { return .repair }+ return nil+ }++ private func handleAction(_ action: ASListPage.Action) {+ if action.navigationValue?.isTapClose == true {+ hide()+ return+ }+ guard let value = action.normalItemValue, let row = row(at: value.indexPath) else { return }+ switch row {+ case .master:+ if value.subActions?.extraValue == nil {+ topViewController()?.present(PurchaseViewController(featuresType: .iCloud), animated: true)+ return+ }+ guard let isOn = value.subActions?.extraValue as? Bool else { return }+ if isOn {UIView.makeAlert(title: R.string.localizable.iCloudTipsTitle(),detail: R.string.localizable.iCloudTipsDetail(),- confirmTitle: R.string.localizable.iCloudConfirm(), cancelAction: { [weak cell] in- cell?.enableSwitchButton.setOn(false, animated: true)- }, confirmAction: {- Settings.defalut.iCloudSyncEnable = value- if value, let iCloudServiceEnable = SyncManager.shared.iCloudServiceEnable, !iCloudServiceEnable {- //尝试开启iCloud 但是目前iCloud服务不可用 弹出一个提示- UIView.makeAlert(title: R.string.localizable.iCloudDisableTitle(), detail: R.string.localizable.iCloudDisableDetail(), cancelTitle: R.string.localizable.confirmTitle())+ confirmTitle: R.string.localizable.iCloudConfirm(),+ cancelAction: { [weak self] in+ self?.listPageView.updateCellData(value.cellData.updateNormalSwitch(state: .off), indexPath: value.indexPath)+ }, confirmAction: { [weak self] in+ Settings.defalut.iCloudSyncEnable = true+ if let iCloudServiceEnable = SyncManager.shared.iCloudServiceEnable, !iCloudServiceEnable {+ UIView.makeAlert(title: R.string.localizable.iCloudDisableTitle(),+ detail: R.string.localizable.iCloudDisableDetail(),+ cancelTitle: R.string.localizable.confirmTitle())}- self?.collectionView.reloadData()- }, tapBackgroundAction: {- cell?.enableSwitchButton.setOn(false, animated: true)+ self?.reloadList()+ }, tapBackgroundAction: { [weak self] in+ self?.listPageView.updateCellData(value.cellData.updateNormalSwitch(state: .off), indexPath: value.indexPath)})} else {- Settings.defalut.iCloudSyncEnable = value- self?.collectionView.reloadData()+ Settings.defalut.iCloudSyncEnable = false+ reloadList()}+ case .progress:+ break+ case .platform:+ showPlatformConfig()+ case .games:+ showGameConfig()+ case .repair:+ repairSync()}- cell.enableSwitchButton.onDisableTap {- topViewController()?.present(PurchaseViewController(featuresType: .iCloud), animated: true)+ }++ private func showPlatformConfig() {+ let gameTypes = FilesSyncPolicy.configurableROMGameTypes()+ guard gameTypes.count > 0 else { return }++ let cells: [[ASListPage.Cell]] = gameTypes.map { gameType in+ if R.Style.GamesGroupTitleStyle == .brand {+ let icon: ASIcon+ let iconSize: ASListPage.Cell.Style.IconSize+ if let image = gameType.brandImage {+ icon = .image(image)+ iconSize = .fixHeight(gameType == .lynx ? 16 : 20)+ } else {+ icon = .symbolImage(R.image.category_iconSymbols())+ iconSize = .fixSize(CGSize(R.Size.ButtonExtraExtraSmall))+ }+ return [.iconTitleDetailSwitchCell(icon: icon,+ iconSize: iconSize,+ state: FilesSyncPolicy.isPlatformROMSyncEnabled(gameType) ? .on : .off,+ enablePressEffect: false)]+ } else {+ let title = R.Style.GamesGroupTitleStyle == .fullName ? gameType.localizedName : gameType.localizedShortName+ return [.iconTitleDetailSwitchCell(title: title,+ state: FilesSyncPolicy.isPlatformROMSyncEnabled(gameType) ? .on : .off,+ enablePressEffect: false)]+ }}-- return cell+ var sheetStyle: ASSheet.Style = .simpleList(icon: .symbolImage(R.image.category_iconSymbols()),+ title: R.string.localizable.iCloudROMPlatformConfig(),+ detail: .smallText(R.string.localizable.iCloudROMSyncDesc(), numberOfLines: 0),+ options: cells)++ ASSheetView.show(.init(style: sheetStyle), action: { action, updation in+ guard let normalItemValue = action.listPageValue?.normalItemValue else {+ return .dismiss()+ }+ guard let isOn = normalItemValue.subActions?.extraValue as? Bool else {+ return .none+ }+ let index = normalItemValue.indexPath.section+ guard index < gameTypes.count else { return .dismiss() }+ let gameType = gameTypes[index]+ Self.applyPlatformROMSync(gameType: gameType, enabled: isOn)+ if case let .simpleList(icon, title, detail, options, cancelEnable) = sheetStyle {+ var next = options+ next[index][0] = normalItemValue.cellData.updateNormalSwitch(state: isOn ? .on : .off)+ sheetStyle = .simpleList(icon: icon, title: title, detail: detail, options: next, cancelEnable: cancelEnable)+ updation?(sheetStyle)+ }+ return .none+ })}-}--extension ICloudSettingView: UICollectionViewDelegate {-}--extension ICloudSettingView: ShowableView {+ private func showGameConfig() {+ let realm = Database.realm+ let games = realm.objects(Game.self).where({ !$0.isDeleted && $0.gameType != .symbian })+ let configurable = Set(FilesSyncPolicy.configurableROMGameTypes())+ guard games.contains(where: { configurable.contains($0.gameType) }) else {+ UIView.makeToast(message: R.string.localizable.transferPakNoGames())+ return+ }++ var datas = [[Game]]()+ var sections = [ASListPage.Section]()+ let groupGames = Dictionary(grouping: Array(games), by: { $0.gameType })+ System.allGameTypes.forEach { sortGameType in+ guard configurable.contains(sortGameType), let games = groupGames[sortGameType] else { return }+ datas.append(games)+ let cells = games.map { game in+ ASListPage.Cell.iconTitleDetailSwitchCell(icon: game.gameCoverIcon,+ iconSize: .fixSize(CGSize(R.Size.ButtonMedium)),+ title: game.displayName,+ detail: game.fileName,+ state: FilesSyncPolicy.shouldSyncROM(game) ? .on : .off,+ enablePressEffect: false)+ }+ var headerTitle = sortGameType.localizedShortName+ if R.Style.GamesGroupTitleStyle == .fullName {+ headerTitle = sortGameType.localizedName+ }+ sections.append(ASListPage.Section(cells: cells, header: .defaultHeader(title: headerTitle)))+ }++ let navigation = ASListPage.Navigation.defaultNavigation(title: R.string.localizable.iCloudROMGameConfig(),+ titleIcon: .symbolImage(R.image.games_iconSymbols()))+ let listPage = ASListPage(navigation: navigation, sections: sections)+ var sheetStyle: ASSheet.Style = .listPage(listPage)++ ASSheetView.show(.init(style: sheetStyle), action: { action, updation in+ if action.listPageValue?.navigationValue?.isTapClose == true {+ return .dismiss()+ }+ guard let normalItemValue = action.listPageValue?.normalItemValue else {+ return .dismiss()+ }+ guard let isOn = normalItemValue.subActions?.extraValue as? Bool else {+ return .none+ }+ let indexPath = normalItemValue.indexPath+ guard indexPath.section < datas.count, indexPath.row < datas[indexPath.section].count else {+ return .dismiss()+ }+ let game = datas[indexPath.section][indexPath.row]+ Self.applyGameROMSync(game: game, enabled: isOn)+ if case var .listPage(listPage) = sheetStyle {+ listPage.sections[indexPath.section].cells[indexPath.row] = normalItemValue.cellData.updateNormalSwitch(state: isOn ? .on : .off)+ sheetStyle = .listPage(listPage)+ updation?(sheetStyle)+ }+ return .none+ })+ }+ private static func applyPlatformROMSync(gameType: GameType, enabled: Bool) {+ let wasEnabled = FilesSyncPolicy.isPlatformROMSyncEnabled(gameType)+ guard wasEnabled != enabled else { return }+ FilesSyncPolicy.setPlatformROMSyncEnabled(gameType, enabled: enabled)+ var targets: [Game] = []+ Game.change { realm in+ let games = realm.objects(Game.self).where { !$0.isDeleted && $0.gameType == gameType }+ for game in games {+ FilesSyncPolicy.setGameROMSyncEnabled(game, enabled: enabled)+ targets.append(game)+ }+ }+ guard FilesSyncPolicy.isDriveSyncAvailable, !targets.isEmpty else { return }+ if enabled {+ for game in targets {+ FilesSyncManager.shared.uploadROMFiles(for: game)+ }+ } else {+ confirmRemoveCloudROMs(games: targets)+ }+ }++ private static func confirmRemoveCloudROMs(games: [Game]) {+ guard !games.isEmpty, FilesSyncPolicy.isDriveSyncAvailable else { return }+ let ids = games.map(\.id)+ UIView.makeAlert(title: R.string.localizable.iCloudROMRemoveDriveTitle(),+ detail: R.string.localizable.iCloudROMRemoveDriveDetail(),+ cancelTitle: R.string.localizable.iCloudROMKeepDrive(),+ confirmTitle: R.string.localizable.iCloudROMRemoveDriveConfirm(),+ confirmAction: {+ let realm = Database.realm+ let targets = ids.compactMap { id -> Game? in+ guard let game = realm.object(ofType: Game.self, forPrimaryKey: id), !game.isDeleted else { return nil }+ return game+ }+ FilesSyncManager.shared.excludeCloudROMs(for: targets)+ })+ }++ private func repairSync() {+ let started = FilesSyncManager.shared.repair { [weak self] event in+ self?.handleRepairEvent(event)+ }+ if started {+ UIView.makeLoading()+ }+ }++ private func handleRepairEvent(_ event: FilesSyncRepairEvent) {+ switch event {+ case .alreadyRunning:+ UIView.makeToast(message: R.string.localizable.iCloudRepairSyncInProgress())+ case .notStarted:+ UIView.hideLoading {+ UIView.makeToast(message: R.string.localizable.iCloudRepairSyncNotReady())+ }+ case .scanFinished(let stats):+ UIView.hideLoading {+ if stats.queued == 0 {+ UIView.makeToast(message: R.string.localizable.iCloudRepairSyncAlreadyDone())+ }+ }+ case .completed(let uploaded, let downloaded, let remaining):+ if uploaded == 0 && downloaded == 0 && remaining == 0 {+ return+ }+ if remaining > 0 {+ UIView.makeToast(message: R.string.localizable.iCloudRepairSyncResultPending(uploaded, downloaded, remaining))+ } else {+ UIView.makeToast(message: R.string.localizable.iCloudRepairSyncResult(uploaded, downloaded))+ }+ }+ }++ private static func applyGameROMSync(game: Game, enabled: Bool) {+ Game.change { _ in+ FilesSyncPolicy.setGameROMSyncEnabled(game, enabled: enabled)+ }+ guard FilesSyncPolicy.isDriveSyncAvailable else { return }+ if enabled {+ FilesSyncManager.shared.uploadROMFiles(for: game)+ } else {+ confirmRemoveCloudROMs(games: [game])+ }+ }}++extension ICloudSettingView: ShowableView {}+#endifdiff --git a/ManicEmu/ManicEmu/Sources/Tools/Extensions/UIViewExtensions.swift b/ManicEmu/ManicEmu/Sources/Tools/Extensions/UIViewExtensions.swiftindex 62787ea1..d914f208 100644--- a/ManicEmu/ManicEmu/Sources/Tools/Extensions/UIViewExtensions.swift+++ b/ManicEmu/ManicEmu/Sources/Tools/Extensions/UIViewExtensions.swift@@ -192,21 +192,11 @@ extension UIView {LoadingToastRepeater = task}- static func hideLoadingToast(forceHide: Bool = false) {- func hideAction() {- UIView.hideToast(identifier: LoadingToastIdentifier)- LoadingToastRepeater?.cancel()- TaskCenter.default.resume(byTag: LoadingToastIdentifier)- LoadingToastRepeater = nil- }- if forceHide {- hideAction()- } else {- //判断一下还有没有下载中的任务- if !DownloadManager.shared.hasDownloadTask && !SyncManager.shared.hasDownloadTask {- hideAction()- }- }+ static func hideLoadingToast() {+ UIView.hideToast(identifier: LoadingToastIdentifier)+ LoadingToastRepeater?.cancel()+ TaskCenter.default.resume(byTag: LoadingToastIdentifier)+ LoadingToastRepeater = nil}private static let LoadingIdentifier = "LoadingIdentifier"diff --git a/ManicEmu/ManicEmu/Sources/Tools/Others/Database.swift b/ManicEmu/ManicEmu/Sources/Tools/Others/Database.swiftindex ea04da9e..d6780160 100644--- a/ManicEmu/ManicEmu/Sources/Tools/Others/Database.swift+++ b/ManicEmu/ManicEmu/Sources/Tools/Others/Database.swift@@ -14,7 +14,7 @@ import ZIPFoundationstruct Database {/// Independent of marketing version. Bump only when Realm object schema changes; never decrease./// Existing 2.0.0 databases already store this as 200 (`"2.0.0"` with dots stripped).- private static let schemaVersion: UInt64 = 200+ private static let schemaVersion: UInt64 = 201static func setup(completion: (()->Void)? = nil) {do {@@ -423,8 +423,8 @@ struct Database {// Additive changes (new types/optional properties) apply automatically when this// version increases. Put property renames or destructive transforms inside.config.migrationBlock = { _, oldSchemaVersion in- if oldSchemaVersion < 200 {- // Prefference is a new type; Realm creates its table automatically.+ if oldSchemaVersion < 201 {+ // FilesSyncRecord is a new type; Realm creates its table automatically.}}return configdiff --git a/ManicEmu/ManicEmu/Sources/Tools/Others/FilesImporter.swift b/ManicEmu/ManicEmu/Sources/Tools/Others/FilesImporter.swiftindex e2ebfe8b..582f6937 100644--- a/ManicEmu/ManicEmu/Sources/Tools/Others/FilesImporter.swift+++ b/ManicEmu/ManicEmu/Sources/Tools/Others/FilesImporter.swift@@ -551,10 +551,9 @@ extension FilesImporter {try FileManager.safeCopyItem(at: item, to: URL(fileURLWithPath: romParentPath.appendingPathComponent(item.lastPathComponent)), shouldReplace: true)}// Upload all files (main + companions) to iCloud- SyncManager.upload(localFilePath: romUrl.path)- for item in items {- SyncManager.upload(localFilePath: romParentPath.appendingPathComponent(item.lastPathComponent))- }+ FilesSyncManager.shared.uploadROMFiles(for: game, extraFiles: items.map {+ URL(fileURLWithPath: romParentPath.appendingPathComponent($0.lastPathComponent))+ })recoverDeletedGame(game, realm: realm, recoverFaile: {completion?(game.id, game.name, nil)})@@ -562,6 +561,7 @@ extension FilesImporter {} else {try FileManager.safeCopyItem(at: url, to: game.romUrl, shouldReplace: true)+ FilesSyncManager.shared.uploadROMFiles(for: game)//文件复制成功recoverDeletedGame(game, realm: realm, recoverFaile: {completion?(game.id, game.name, nil)@@ -690,15 +690,13 @@ extension FilesImporter {}}do {- try realm.write { realm.add(game) }- SyncManager.upload(localFilePath: game.romUrl.path)- // Upload companion files (.bin, .img, .sub, etc.) for multi-file ROMs- if items.count > 0 {- let romParentPath = game.romUrl.path.deletingLastPathComponent- for item in items {- SyncManager.upload(localFilePath: romParentPath.appendingPathComponent(item.lastPathComponent))- }+ try realm.write {+ FilesSyncPolicy.applyDefaultROMSyncFlag(to: game)+ realm.add(game)}+ FilesSyncManager.shared.uploadROMFiles(for: game, extraFiles: items.map {+ URL(fileURLWithPath: game.romUrl.path.deletingLastPathComponent.appendingPathComponent($0.lastPathComponent))+ })OnlineCoverManager.shared.addCoverMatch(OnlineCoverManager.CoverMatch(game: game))completion?(game.id, game.gameType == ._3ds ? (game.displayName) : game.name, nil)@@ -872,7 +870,6 @@ extension FilesImporter {try realm.write {realm.add(skin)}- SyncManager.upload(localFilePath: skin.fileURL.path)completion?(skin.name, nil)return} catch {diff --git a/ManicEmu/ManicEmu/Sources/Tools/Others/SyncManager.swift b/ManicEmu/ManicEmu/Sources/Tools/Others/SyncManager.swiftindex 26e4ad9b..3e91bedc 100644--- a/ManicEmu/ManicEmu/Sources/Tools/Others/SyncManager.swift+++ b/ManicEmu/ManicEmu/Sources/Tools/Others/SyncManager.swift@@ -11,101 +11,50 @@ import UIKitimport Foundationimport IceCreamimport CloudKit-import SwiftCloudDriveclass SyncManager: NSObject {static let shared = SyncManager()- //数据库与CloudKit同步private var realmSyncEngine: SyncEngine?-- private var cloudDrive: CloudDrive?-var iCloudServiceEnable: Bool? = nil-- var hasDownloadTask: Bool {- downloadingFiles.count > 0- }-- private var downloadingFiles: [String] = []-- private var stopGameNotification: Any? = nil-- private var iCloudAccountChangedNotification: Any? = nil+ private var iCloudAccountChangedNotification: Any?enum SyncState: String {case undefinecase idle- case syncing //上传文件到iCloud drive 或 从iCloud Drive下载文件 或 正在删除iCloud Drive的文件+ case syncing}- private(set) var syncState: SyncState = .undefine {- didSet {- if oldValue != syncState {- NotificationCenter.default.post(name: R.NotificationName.iCloudDriveSyncChange, object: syncState)- Log.debug("[iCloud Sync] 同步状态变化: \(oldValue.rawValue) -> \(syncState.rawValue)")- }- }+ var hasDownloadTask: Bool {+ FilesSyncManager.shared.hasDownloadTask}- // MARK: - iCloud 文件状态监控- private let metadataQuery = NSMetadataQuery()- private var metadataQueryNotificationTokens: [NSObjectProtocol] = []- private var isMonitoring = false- private var monitoredUploadingFiles = Set<URL>()- private var monitoredDownloadingFiles = Set<URL>()- private let monitoringQueue = DispatchQueue(label: "com.manicemu.syncmanager.monitoring")-- deinit {- stopiCloudFileMonitoring()- if let iCloudAccountChangedNotification = iCloudAccountChangedNotification {- NotificationCenter.default.removeObserver(iCloudAccountChangedNotification)- }- metadataQueryNotificationTokens.forEach { NotificationCenter.default.removeObserver($0) }+ var syncState: SyncState {+ FilesSyncManager.shared.syncState}private override init() {super.init()updateiCloudAccountstatus()- iCloudAccountChangedNotification = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: .main) { [weak self] notification in- guard let self = self else { return }- self.updateiCloudAccountstatus()+ iCloudAccountChangedNotification = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: .main) { [weak self] _ in+ self?.updateiCloudAccountstatus()}}- /// 开始同步func startSync() {if realmSyncEngine == nil {setupRealmSync()- setupDocumentSync()- // 启动 iCloud 文件监控- startiCloudFileMonitoring()- stopGameNotification = NotificationCenter.default.addObserver(forName: R.NotificationName.StopPlayGame, object: nil, queue: .main) { notification in- SyncManager.syncDocument()- }}+ FilesSyncManager.shared.start()}- //停止同步func stopSync() {realmSyncEngine = nil- // 停止 iCloud 文件监控- stopiCloudFileMonitoring()- if let stopGameNotification = stopGameNotification {- NotificationCenter.default.removeObserver(stopGameNotification)- }+ FilesSyncManager.shared.stop()}- private func setupDocumentSync() {- Task {- cloudDrive = try await CloudDrive()- SyncManager.syncDocument()- }- }-private func setupRealmSync() {guard realmSyncEngine == nil else { return }IceCream.shared.logAction = { Log.debug($0) }- //注册Realm同步管理器let configuration = Database.realm.configurationrealmSyncEngine = SyncEngine(objects: [SyncObject(realmConfiguration: configuration, type: Game.self, uListElementType: GameSaveState.self, vListElementType: GameCheat.self),@@ -118,7 +67,8 @@ class SyncManager: NSObject {SyncObject(realmConfiguration: configuration, type: Theme.self),SyncObject(realmConfiguration: configuration, type: Trigger.self, uListElementType: TriggerItem.self),SyncObject(realmConfiguration: configuration, type: TriggerItem.self),- SyncObject(realmConfiguration: configuration, type: Prefference.self)+ SyncObject(realmConfiguration: configuration, type: Prefference.self),+ SyncObject(realmConfiguration: configuration, type: FilesSyncRecord.self)])realmSyncEngine?.setupCompletion = { error inif let error = error {@@ -133,478 +83,37 @@ class SyncManager: NSObject {private func updateiCloudAccountstatus() {#if !SIDE_LOADCKContainer.default().accountStatus { [weak self] status, error in- guard let self = self else { return }- self.iCloudServiceEnable = status == .available+ self?.iCloudServiceEnable = status == .available}#endif}- // MARK: - iCloud 文件状态监控方法- private func startiCloudFileMonitoring() {- guard !isMonitoring else { return }- guard FileManager.default.ubiquityIdentityToken != nil else {- Log.debug("[iCloud Sync] 未检测到iCloud账户,无法开启文件状态监控")- return- }-- isMonitoring = true- DispatchQueue.main.async { [weak self] in- self?.configureMetadataQuery()- self?.metadataQuery.enableUpdates()- self?.metadataQuery.start()- Log.debug("[iCloud Sync] 开始监控iCloud文件状态")- }- }-- private func stopiCloudFileMonitoring() {- guard isMonitoring else { return }- isMonitoring = false- DispatchQueue.main.async { [weak self] in- self?.metadataQuery.stop()- self?.metadataQuery.disableUpdates()- self?.teardownMetadataQueryObservers()- Log.debug("[iCloud Sync] 停止监控iCloud文件状态")- }- monitoringQueue.async { [weak self] in- self?.resetTrackingState()- }- }-- private func configureMetadataQuery() {- guard metadataQueryNotificationTokens.isEmpty else { return }- metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]- metadataQuery.predicate = NSPredicate(value: true)- metadataQuery.notificationBatchingInterval = 0.5-- let center = NotificationCenter.default- let finishToken = center.addObserver(forName: .NSMetadataQueryDidFinishGathering, object: metadataQuery, queue: .main) { [weak self] _ in- self?.metadataQuery.disableUpdates()- self?.processMetadataQueryResults()- self?.metadataQuery.enableUpdates()- }-- let updateToken = center.addObserver(forName: .NSMetadataQueryDidUpdate, object: metadataQuery, queue: .main) { [weak self] _ in- self?.processMetadataQueryResults()- }-- metadataQueryNotificationTokens.append(contentsOf: [finishToken, updateToken])- }-- private func teardownMetadataQueryObservers() {- metadataQueryNotificationTokens.forEach { NotificationCenter.default.removeObserver($0) }- metadataQueryNotificationTokens.removeAll()- }-- private func processMetadataQueryResults() {- guard isMonitoring else { return }- let results = metadataQuery.results- monitoringQueue.async { [weak self] in- guard let self = self else { return }- for case let item as NSMetadataItem in results {- self.handleMetadataItem(item)- }- self.updateSyncState()- }- }-- private func handleMetadataItem(_ item: NSMetadataItem) {- guard let fileURL = item.value(forAttribute: NSMetadataItemURLKey) as? URL else { return }-- // 过滤掉目录,只处理文件- // 方法1: 检查 URL 路径是否以 / 结尾(目录通常以 / 结尾)- if fileURL.path.hasSuffix("/") {- return- }-- // 方法2: 使用 FileManager 检查(如果文件已存在)- var isDirectory: ObjCBool = false- if FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isDirectory),- isDirectory.boolValue {- return- }-- // 方法3: 检查内容类型(如果可用)- if let contentType = item.value(forAttribute: NSMetadataItemContentTypeKey) as? String,- contentType == "public.directory" || contentType == "public.folder" {- return- }-- let wasUploading = monitoredUploadingFiles.contains(fileURL)- let wasDownloading = monitoredDownloadingFiles.contains(fileURL)-- let uploading = isUploading(item)- let downloading = isDownloading(item, cloudFileUrl: fileURL)-- // 处理上传状态- if uploading {- if !wasUploading {- monitoredUploadingFiles.insert(fileURL)- }- } else {- if wasUploading {- monitoredUploadingFiles.remove(fileURL)- }- }-- // 处理下载状态- if downloading {- if !wasDownloading {- monitoredDownloadingFiles.insert(fileURL)- }- } else {- if wasDownloading {- monitoredDownloadingFiles.remove(fileURL)- }- }- }-- private func isUploading(_ item: NSMetadataItem) -> Bool {- if let uploading = item.value(forAttribute: NSMetadataUbiquitousItemIsUploadingKey) as? Bool, uploading {- return true- }- if let percent = item.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? Double, percent > 0.0 && percent < 100.0 {- return true- }- return false- }-- private func isDownloading(_ item: NSMetadataItem, cloudFileUrl: URL) -> Bool {- if let downloading = item.value(forAttribute: NSMetadataUbiquitousItemIsDownloadingKey) as? Bool, downloading {- return true- } else if let status = item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String {- if status == NSMetadataUbiquitousItemDownloadingStatusDownloaded || status == NSMetadataUbiquitousItemDownloadingStatusCurrent {- return false- } else if status == NSMetadataUbiquitousItemDownloadingStatusNotDownloaded {- //该item尚未进行下载 检查一下本地是否已经存在- if let localUrl = SyncManager.convertToLocalUrl(fromCloudUrl: cloudFileUrl) {- //url合法- if FileManager.default.fileExists(atPath: localUrl.path) {- //本地文件已经存在- return false- } else {- //本地文件不存在 则进行下载- SyncManager.download(to: localUrl.path)- return true- }- } else {- //url不合法- return false- }- }- }- return false- }-- private func resetTrackingState() {- monitoredUploadingFiles.removeAll()- monitoredDownloadingFiles.removeAll()- updateSyncState()- }-- private func updateSyncState() {- let hasActiveTasks = !monitoredUploadingFiles.isEmpty || !monitoredDownloadingFiles.isEmpty- let newState: SyncState = hasActiveTasks ? .syncing : .idle- guard newState != syncState else { return }- DispatchQueue.main.async { [weak self] in- self?.syncState = newState- }- }-static func upload(localFilePath: String) {- guard Settings.defalut.iCloudSyncEnable else { return }- if let range = localFilePath.range(of: "/Documents/") {- let cloudFilePath = RootRelativePath(path: String(localFilePath[range.lowerBound...]))- if let cloudDrive = SyncManager.shared.cloudDrive {- Task {- Log.debug("[iCloud Sync]开始上传文件到iCloud:\(localFilePath)")- let parentDirectory = RootRelativePath(path: String(localFilePath.deletingLastPathComponent[range.lowerBound...]))- let directoryExists = try await cloudDrive.directoryExists(at: parentDirectory)- if !directoryExists {- try await cloudDrive.createDirectory(at: parentDirectory)- }- try? await cloudDrive.upload(from: URL(fileURLWithPath: localFilePath), to: cloudFilePath)- Log.debug("[iCloud Sync]文件已提交到iCloud上传队列:\(cloudFilePath.path)")- // 注意:文件可能还在上传中,真实状态由 NSMetadataQuery 监控- }- }- }+ FilesSyncManager.shared.noteLocalChange(path: localFilePath)}- static func download(to localFilePath: String, completion: ((Error?)->Void)? = nil) {- if SyncManager.shared.downloadingFiles.contains(localFilePath) {- return- }-- if let range = localFilePath.range(of: "/Documents/") {- let cloudFilePath = RootRelativePath(path: String(localFilePath[range.lowerBound...]))- Task {- do {- let cloudDrive: CloudDrive- if let cd = SyncManager.shared.cloudDrive {- cloudDrive = cd- } else {- cloudDrive = try await CloudDrive()- SyncManager.shared.cloudDrive = cloudDrive- }- Log.debug("[iCloud Sync]开始从iCloud下载文件:\(cloudFilePath.path)")- if !FileManager.default.fileExists(atPath: localFilePath.deletingLastPathComponent) {- try? FileManager.default.createDirectory(atPath: localFilePath.deletingLastPathComponent, withIntermediateDirectories: true)- }- SyncManager.shared.downloadingFiles.append(localFilePath)- try await cloudDrive.download(from: cloudFilePath, toURL: URL(fileURLWithPath: localFilePath))- Log.debug("[iCloud Sync]文件已提交到iCloud下载队列:\(localFilePath)")- // 注意:文件可能还在下载中,真实状态由 NSMetadataQuery 监控- SyncManager.shared.downloadingFiles.removeAll { $0 == localFilePath }- await MainActor.run {- completion?(nil)- }- } catch {- SyncManager.shared.downloadingFiles.removeAll { $0 == localFilePath }- await MainActor.run {- completion?(error as? Error)- }- }- }- }+ static func download(to localFilePath: String, completion: ((Error?) -> Void)? = nil) {+ FilesSyncManager.shared.ensureLocal(at: URL(fileURLWithPath: localFilePath), completion: completion)}static func delete(localFilePath: String) {- guard Settings.defalut.iCloudSyncEnable else { return }- if let range = localFilePath.range(of: "/Documents/") {- let cloudFilePath = RootRelativePath(path: String(localFilePath[range.lowerBound...]))- if let cloudDrive = SyncManager.shared.cloudDrive {- Task {- Log.debug("[iCloud Sync]开始删除iCloud文件:\(localFilePath)")- try? await cloudDrive.removeFile(at: cloudFilePath)- Log.debug("[iCloud Sync]删除iCloud文件成功:\(cloudFilePath.path)")- }- }- }+ FilesSyncManager.shared.noteLocalRemoval(path: localFilePath)}static func deletePath(localPath: String) {- guard Settings.defalut.iCloudSyncEnable else { return }- if let range = localPath.range(of: "/Documents/") {- let cloudFilePath = RootRelativePath(path: String(localPath[range.lowerBound...]))- if let cloudDrive = SyncManager.shared.cloudDrive {- Task {- Log.debug("[iCloud Sync]开始删除iCloud目录:\(localPath)")- try? await cloudDrive.removeDirectory(at: cloudFilePath)- Log.debug("[iCloud Sync]删除iCloud目录成功:\(cloudFilePath.path)")- }- }- }+ FilesSyncManager.shared.noteLocalRemoval(path: localPath)}- static func isiCloudFileExist(localFilePath: String, completion: ((Bool)->Void)? = nil) {- if let range = localFilePath.range(of: "/Documents/") {- let cloudFilePath = RootRelativePath(path: String(localFilePath[range.lowerBound...]))- Task {- let cloudDrive: CloudDrive- if let cd = SyncManager.shared.cloudDrive {- cloudDrive = cd- } else {- cloudDrive = try await CloudDrive()- SyncManager.shared.cloudDrive = cloudDrive- }- if let fileExists = try? await cloudDrive.fileExists(at: cloudFilePath) {- await MainActor.run {- completion?(fileExists)- }- } else {- await MainActor.run {- completion?(false)- }- }- }- }+ static func isiCloudFileExist(localFilePath: String, completion: ((Bool) -> Void)? = nil) {+ FilesSyncManager.shared.cloudFileExists(localFilePath: localFilePath, completion: completion)}static func syncDocument() {- if !Settings.defalut.iCloudSyncEnable && PlayViewController.isGaming {- return;- }- Task {- if let cloudDrive = SyncManager.shared.cloudDrive {- var handledFiles = [String]()- var conflictFiles = [String]()- Log.debug("[iCloud Sync] 开始同步iCloud文件....")- //遍历云文件- if let cloudFileUrls = try? await fetchAllCloudFiles(at: .init(path: "Documents"), cloudDrive: cloudDrive) {- for cloudFileUrl in cloudFileUrls {- if let cloudFileModificationDate = (try cloudFileUrl.resourceValues(forKeys: [.contentModificationDateKey])).contentModificationDate {- if let range = cloudFileUrl.path.range(of: "/Documents/") {- let cloudFileRelativePath = String(cloudFileUrl.path[range.upperBound...])- let cloudFilePath = RootRelativePath(path: "Documents/\(cloudFileRelativePath)")- let localFilePath = R.Path.Document.appendingPathComponent(cloudFileRelativePath)- if FileManager.default.fileExists(atPath: localFilePath) {- if let localFileModificationDate = try FileManager.default.attributesOfItem(atPath: localFilePath)[.modificationDate] as? Date {- if localFileModificationDate > cloudFileModificationDate {- Log.debug("[iCloud Sync]本地文件比较新, 本地覆盖云端 \(cloudFileRelativePath)")- try? await cloudDrive.removeFile(at: cloudFilePath)- do {- try await cloudDrive.upload(from: URL(fileURLWithPath: localFilePath), to: cloudFilePath)- } catch {- Log.debug("[iCloud Sync]\(cloudFilePath.path) 上传失败:\(error)")- }- } else if localFileModificationDate < cloudFileModificationDate {- Log.debug("[iCloud Sync]云端文件比较新, 云端覆盖本地 \(cloudFileRelativePath)")- try? FileManager.safeRemoveItem(at: URL(fileURLWithPath: localFilePath))- do {- try await cloudDrive.download(from: cloudFilePath, toURL: URL(fileURLWithPath: localFilePath))- } catch {- Log.debug("[iCloud Sync]\(cloudFilePath.path) 下载失败:\(error)")- }-- } else {- //文件没有更新,忽略- }- } else {- Log.debug("[iCloud Sync]无法获取本地文件修改时间,记录冲突,让用户来决定")- conflictFiles.append(cloudFileRelativePath)- }- } else {- Log.debug("[iCloud Sync]本地文件不存在,下载到本地... \(cloudFileRelativePath)")- do {- if !FileManager.default.fileExists(atPath: localFilePath.deletingLastPathComponent) {- try? FileManager.default.createDirectory(atPath: localFilePath.deletingLastPathComponent, withIntermediateDirectories: true)- }- try await cloudDrive.download(from: cloudFilePath, toURL: URL(fileURLWithPath: localFilePath))- } catch {- Log.debug("[iCloud Sync]\(cloudFilePath.path) 下载失败:\(error)")- }- }- handledFiles.append(cloudFileRelativePath)- } else {- Log.debug("[iCloud Sync]无法获取云端文件的相对路径")- }- } else {- Log.debug("[iCloud Sync]无法获取云端文件修改时间")- }- }- }- //遍历本地- let localFileUrls = fetchAllLocalFiles(at: URL(fileURLWithPath: R.Path.Document))- for localFileUrl in localFileUrls {- if let range = localFileUrl.path.range(of: "/Documents/") {- let localFileRelativePath = String(localFileUrl.path[range.upperBound...])- if !handledFiles.contains(localFileRelativePath) {- do {- Log.debug("[iCloud Sync]本地存在的文件,但是云端还没有 进行上传... \(localFileRelativePath)")- let directoryExists = try await cloudDrive.directoryExists(at: RootRelativePath(path: "Documents/\(localFileRelativePath.deletingLastPathComponent)"))- if !directoryExists {- try await cloudDrive.createDirectory(at: RootRelativePath(path: "Documents/\(localFileRelativePath.deletingLastPathComponent)"))- }- try await cloudDrive.upload(from: localFileUrl, to: RootRelativePath(path: "Documents/\(localFileRelativePath)"))- Log.debug("[iCloud Sync]文件上传成功 \(localFileRelativePath)")- } catch {- Log.debug("\(localFileRelativePath)上传失败:\(error)")- }- } else {- //文件无需处理- }- }- }- //处理冲突- for conflictFile in conflictFiles {- Log.debug("[iCloud Sync]处理冲突文件:\(conflictFile)")- Task { @MainActor in- let cloudFilePath = RootRelativePath(path: "Documents/\(conflictFile)")- let localFilePath = R.Path.Document.appendingPathComponent(conflictFile)- UIView.makeAlert(title: R.string.localizable.iCloudSyncConfilictTitle(),- detail: conflictFile,- cancelTitle: R.string.localizable.iCloudSyncConfilictSaveiCloud(),- confirmTitle: R.string.localizable.iCloudSyncConfilictSaveLocal(),- enableForceHide: false,- cancelAction: {- Task {- //保留云端 则删除本地的- try? FileManager.safeRemoveItem(at: URL(fileURLWithPath: localFilePath))- try await cloudDrive.download(from: cloudFilePath, toURL: URL(fileURLWithPath: localFilePath))- // 注意:文件可能还在下载中,真实状态由 NSMetadataQuery 监控- }- },- confirmAction: {- //保留本地的 则删除云端的- Task {- try? await cloudDrive.removeFile(at: cloudFilePath)- try await cloudDrive.upload(from: URL(fileURLWithPath: localFilePath), to: cloudFilePath)- // 注意:文件可能还在上传中,真实状态由 NSMetadataQuery 监控- }- })- }- }- }- }- }-- private static func fetchAllLocalFiles(at url: URL, resourceKeys: [URLResourceKey] = [.isRegularFileKey, .isDirectoryKey, .contentModificationDateKey]) -> [URL] {- var result: [URL] = []- let fileManager = FileManager.default- do {- let items = try fileManager.contentsOfDirectory(at: url, includingPropertiesForKeys: resourceKeys, options: [.skipsHiddenFiles])- for item in items {- let values = try item.resourceValues(forKeys: Set(resourceKeys))- if values.isDirectory == true {- if item.path.contains("/wpkdata") || item.path.contains("/Datas/") {- //特殊目录不需要进行遍历- continue- }- // 递归进入子目录- let subFiles = fetchAllLocalFiles(at: item, resourceKeys: resourceKeys)- result.append(contentsOf: subFiles)- } else if values.isRegularFile == true {- if !item.path.contains("/SYSTEM/CACHE/") {- result.append(item)- }- }- }- } catch {- Log.debug("遍历本地文件失败:\(error)")- }- return result- }-- private static func fetchAllCloudFiles(at path: RootRelativePath, cloudDrive: CloudDrive, resourceKeys: [URLResourceKey] = [.isRegularFileKey, .isDirectoryKey, .contentModificationDateKey]) async throws -> [URL] {- var result: [URL] = []- do {- let items = try await cloudDrive.contentsOfDirectory(at: path, includingPropertiesForKeys: resourceKeys, options: [.skipsHiddenFiles])- for item in items {- let values = try item.resourceValues(forKeys: Set(resourceKeys))- if values.isDirectory == true {- if item.path.contains("/wpkdata") || item.path.contains("/Datas/") {- //特殊目录不需要进行遍历- continue- }- // 递归进入子目录- if let range = item.path.range(of: "/Documents/") {- let subFiles = try await fetchAllCloudFiles(at: RootRelativePath(path: String(item.path[range.lowerBound...])), cloudDrive: cloudDrive, resourceKeys: resourceKeys)- result.append(contentsOf: subFiles)- }-- } else if values.isRegularFile == true {- result.append(item)- }- }- } catch {- Log.debug("[iCloud Sync]遍历云端文件失败:\(error)")- throw error- }- return result+ FilesSyncManager.shared.reconcile()}static func convertToLocalUrl(fromCloudUrl: URL) -> URL? {- if let range = fromCloudUrl.path.range(of: "/Documents/") {- let cloudFileRelativePath = String(fromCloudUrl.path[range.upperBound...])- return URL(fileURLWithPath: R.Path.Document.appendingPathComponent(cloudFileRelativePath))- }- return nil- }-- static func convertToCloudPath(url: URL) -> RootRelativePath? {- if let range = url.path.range(of: "/Documents/") {- return RootRelativePath(path: String(url.path[range.lowerBound...]))- }- return nil+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: fromCloudUrl) else { return nil }+ return FilesSyncPolicy.localURL(relativePath: relative)}}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncEngine.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncEngine.swiftnew file mode 100644index 00000000..0ccf7beb--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncEngine.swift@@ -0,0 +1,1086 @@+//+// FilesSyncEngine.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation++enum FilesSyncOpKind: String, Codable {+ case upload+ case download+ case deleteCloud+ case deleteLocal+}++struct FilesSyncOp: Codable {+ var relativePath: String+ var kind: FilesSyncOpKind+ var tombstoneReason: FilesSyncTombstone.Reason?+ var isDirectory: Bool = false+ var isConflict: Bool = false+ var retries: Int = 0+}++private enum FilesSyncDecideAction {+ case skip+ case upload+ case download+ case deleteCloud+ case deleteLocal+}++final class FilesSyncEngine {+ private let io = FilesSyncIO()+ private let lock = NSLock()+ private var pending: [String: FilesSyncOp] = [:]+ private var deferred: [String: FilesSyncOp] = [:]+ private var inFlight: [String: FilesSyncOpKind] = [:]+ private var drainTask: Task<Void, Never>?+ private var workTail = Task<Void, Never> {}+ private let maxConcurrent = 3+ private let maxRetries = 5+ private var pausedForGameplay = false+ private var started = false+ private var latestCloudFiles: [String: FilesSyncFingerprint] = [:]+ private var notDownloaded = Set<String>()+ private var romExclusion = FilesSyncROMExclusion()+ private var pendingLocalNotes: [URL] = []+ private var pendingInventory: FilesSyncCloudInventory?+ private var repairInFlight = false++ var onProgress: ((FilesSyncProgress) -> Void)?++ private(set) var progress = FilesSyncProgress() {+ didSet { onProgress?(progress) }+ }++ var hasDownloadTask: Bool {+ withLock {+ pending.values.contains(where: { $0.kind == .download })+ || inFlight.values.contains(where: { $0 == .download })+ }+ }++ private var isStarted: Bool {+ withLock { started }+ }++ func start() {+#if SIDE_LOAD+ return+#else+ let alreadyStarted = withLock { () -> Bool in+ if started { return true }+ started = true+ return false+ }+ if alreadyStarted {+ Log.debug("[iCloud Sync] start ignored (already started) main=\(Thread.isMainThread)")+ return+ }+ Log.debug("[iCloud Sync] start queued main=\(Thread.isMainThread)")+ enqueueWork("bootstrap") { [weak self] in+ await self?.bootstrap()+ }+#endif+ }++ func stop() {+ Log.debug("[iCloud Sync] stop main=\(Thread.isMainThread) \(queueSummary())")+ persistQueuedOps()+ withLock {+ started = false+ pending.removeAll()+ deferred.removeAll()+ pendingLocalNotes.removeAll()+ pendingInventory = nil+ repairInFlight = false+ drainTask?.cancel()+ drainTask = nil+ }+ publish {+ $0 = FilesSyncProgress()+ $0.phase = .idle+ }+ }++ func setPausedForGameplay(_ paused: Bool) {+ Log.debug("[iCloud Sync] gameplay pause=\(paused) \(queueSummary())")+ withLock { pausedForGameplay = paused }+ if paused {+ publish { $0.phase = .paused }+ } else {+ enqueueWork("resumeAfterGameplay") { [weak self] in+ self?.flushDeferredOps(reason: "resumeAfterGameplay")+ await self?.reconcile(full: false, saveRootsOnly: true)+ }+ }+ }++ func handleDidBecomeActive() {+ guard isStarted else {+ Log.debug("[iCloud Sync] didBecomeActive ignored (not started)")+ return+ }+ if withLock({ pausedForGameplay }) {+ Log.debug("[iCloud Sync] didBecomeActive ignored (gameplay paused)")+ return+ }+ Log.debug("[iCloud Sync] didBecomeActive queued \(queueSummary())")+ enqueueWork("didBecomeActive") { [weak self] in+ self?.flushDeferredOps(reason: "foreground")+ await self?.reconcile(full: false, saveRootsOnly: true)+ }+ }++ func handleNetworkSatisfied() {+ guard isStarted else {+ Log.debug("[iCloud Sync] network satisfied ignored (not started)")+ return+ }+ if withLock({ pausedForGameplay }) {+ Log.debug("[iCloud Sync] network satisfied ignored (gameplay paused)")+ return+ }+ Log.debug("[iCloud Sync] network satisfied queued \(queueSummary())")+ enqueueWork("networkSatisfied") { [weak self] in+ self?.flushDeferredOps(reason: "network")+ self?.pump()+ }+ }++ @discardableResult+ func requestRepair(_ handler: @escaping (FilesSyncRepairEvent) -> Void) -> Bool {+ guard isStarted else {+ Log.debug("[iCloud Sync] repair ignored (not started)")+ DispatchQueue.main.async { handler(.notStarted) }+ return false+ }+ let accepted = withLock { () -> Bool in+ if repairInFlight { return false }+ repairInFlight = true+ return true+ }+ guard accepted else {+ Log.debug("[iCloud Sync] repair ignored (already running)")+ DispatchQueue.main.async { handler(.alreadyRunning) }+ return false+ }+ Log.debug("[iCloud Sync] repair queued \(queueSummary())")+ enqueueWork("repair") { [weak self] in+ guard let self else { return }+ defer { self.withLock { self.repairInFlight = false } }+ guard self.isStarted else {+ DispatchQueue.main.async { handler(.notStarted) }+ return+ }+ self.flushDeferredOps(reason: "repair")+ let stats = await self.reconcile(full: true)+ Log.debug("[iCloud Sync] repair scan uploads=\(stats.uploads) downloads=\(stats.downloads) deletes=\(stats.deletes)")+ DispatchQueue.main.async { handler(.scanFinished(stats)) }+ if stats.queued > 0 {+ await self.waitUntilIdle()+ }+ let remaining = self.withLock { self.deferred.count }+ Log.debug("[iCloud Sync] repair completed remaining=\(remaining)")+ DispatchQueue.main.async {+ handler(.completed(uploaded: stats.uploads, downloaded: stats.downloads, remaining: remaining))+ }+ }+ return true+ }++ func requestReconcile(full: Bool) {+ guard isStarted else {+ Log.debug("[iCloud Sync] reconcile ignored (not started)")+ return+ }+ enqueueWork("reconcile full=\(full)") { [weak self] in+ await self?.reconcile(full: full)+ }+ }++ func noteLocalChange(at url: URL) {+ if !isStarted {+ withLock { pendingLocalNotes.append(url) }+ Log.debug("[iCloud Sync] noteLocalChange queued (not started): \(url.path)")+ return+ }+ Log.debug("[iCloud Sync] noteLocalChange \(url.path) main=\(Thread.isMainThread)")+ enqueueWork("noteLocal \(url.lastPathComponent)") { [weak self] in+ await self?.processLocalChange(url)+ }+ }++ func noteLocalRemoval(at url: URL) {+ guard isStarted else {+ Log.debug("[iCloud Sync] noteLocalRemoval ignored (not started): \(url.path)")+ return+ }+ Log.debug("[iCloud Sync] noteLocalRemoval \(url.path)")+ enqueueWork("noteRemoval \(url.lastPathComponent)") { [weak self] in+ await self?.processLocalRemoval(url)+ }+ }++ func handleIntentPaths(_ paths: [String]) {+ guard isStarted, !paths.isEmpty else { return }+ Log.debug("[iCloud Sync] intent records changed count=\(paths.count)")+ enqueueWork("intentRecords") { [weak self] in+ await self?.applyIntentPaths(paths)+ }+ }++ func excludeCloudCopies(urls: [URL]) {+ guard isStarted else { return }+ Log.debug("[iCloud Sync] excludeCloudCopies count=\(urls.count)")+ enqueueWork("excludeCloudCopies") { [weak self] in+ await self?.processExcludeCloudCopies(urls)+ }+ }++ func ensureLocal(at url: URL) async -> Error? {+ Log.debug("[iCloud Sync] ensureLocal requested \(url.path) main=\(Thread.isMainThread)")+ return await performEnsureLocal(url)+ }++ func cloudFileExists(relativePath: String) async -> Bool {+ await io.fileExists(relativePath: relativePath)+ }++ func applyCloudInventory(_ inventory: FilesSyncCloudInventory) {+ let uploading = inventory.uploading.prefix(5).joined(separator: ",")+ let downloading = inventory.downloading.prefix(5).joined(separator: ",")+ Log.debug("[iCloud Sync] metadata files=\(inventory.files.count) uploading=\(inventory.uploading.count)[\(uploading)] downloading=\(inventory.downloading.count)[\(downloading)] notDownloaded=\(inventory.notDownloaded.count) main=\(Thread.isMainThread)")+ withLock { pendingInventory = inventory }+ enqueueWork("cloudInventory") { [weak self] in+ await self?.flushCloudInventory()+ }+ }++ private func bootstrap() async {+#if SIDE_LOAD+ return+#else+ guard isStarted else { return }+ let startedAt = Date()+ Log.debug("[iCloud Sync] bootstrap begin main=\(Thread.isMainThread)")+ FilesSyncIndex.load()+ loadDeferredFromDisk()+ Log.debug("[iCloud Sync] ledger files=\(FilesSyncIndex.store.files.count) needsInitialScan=\(FilesSyncIndex.needsInitialScan)")+ do {+ try await io.prepare()+ } catch {+ Log.debug("[iCloud Sync] CloudDrive init failed: \(error)")+ publish { $0.phase = .unavailable }+ return+ }+ flushDeferredOps(reason: "bootstrap")+ FilesSyncIntentStore.pruneExpiredDeleted()+ if FilesSyncIndex.needsInitialScan {+ await reconcile(full: true)+ } else {+ await reconcile(full: false, saveRootsOnly: true)+ catchUpUntrackedContentTrees()+ }+ let notes = withLock { () -> [URL] in+ let queued = pendingLocalNotes+ pendingLocalNotes.removeAll()+ return queued+ }+ if !notes.isEmpty {+ Log.debug("[iCloud Sync] flushing \(notes.count) local changes queued before bootstrap")+ for url in notes {+ guard isStarted else { return }+ await processLocalChange(url)+ }+ }+ Log.debug("[iCloud Sync] bootstrap end elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s \(queueSummary())")+#endif+ }++ @discardableResult+ func reconcile(full: Bool, cloudFiles: [String: FilesSyncFingerprint]? = nil, saveRootsOnly: Bool = false) async -> FilesSyncRepairStats {+#if SIDE_LOAD+ return FilesSyncRepairStats()+#else+ guard isStarted else { return FilesSyncRepairStats() }+ if withLock({ pausedForGameplay }) {+ Log.debug("[iCloud Sync] reconcile skipped (gameplay paused) full=\(full) saveRootsOnly=\(saveRootsOnly)")+ publish { $0.phase = .paused }+ return FilesSyncRepairStats()+ }+ let startedAt = Date()+ Log.debug("[iCloud Sync] reconcile begin full=\(full) saveRootsOnly=\(saveRootsOnly) main=\(Thread.isMainThread)")+ publish { $0.phase = .scanning }+ refreshROMExclusion()+ let mode: FilesSyncIO.EnumerationMode = (full || !saveRootsOnly) ? .all : .saveRoots+ let local = FilesSyncIO.enumerateLocalFiles(mode: mode)+ var allCloud: [String: FilesSyncFingerprint]+ if let cloudFiles {+ allCloud = cloudFiles+ } else if withLock({ latestCloudFiles.isEmpty }) {+ allCloud = await io.listCloudFiles()+ } else {+ allCloud = withLock { latestCloudFiles }+ }+ withLock {+ if !allCloud.isEmpty {+ latestCloudFiles = allCloud+ }+ }+ let cloudForDecide: [String: FilesSyncFingerprint]+ if saveRootsOnly, !full {+ cloudForDecide = allCloud.filter { !FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: $0.key) }+ } else {+ cloudForDecide = allCloud+ }+ let intentPaths = FilesSyncIntentStore.allActive().keys.filter { path in+ if saveRootsOnly, !full, FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: path) {+ return false+ }+ return true+ }+ let keys = Set(local.keys).union(cloudForDecide.keys).union(intentPaths)+ Log.debug("[iCloud Sync] reconcile compare local=\(local.count) cloud=\(cloudForDecide.count) intents=\(intentPaths.count) keys=\(keys.count)")++ var stats = FilesSyncRepairStats()+ var skipCount = 0+ for relative in keys.sorted() {+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) {+ skipCount += 1+ continue+ }+ if saveRootsOnly, !full, FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: relative) {+ skipCount += 1+ continue+ }+ switch decide(relativePath: relative, local: local[relative], cloud: cloudForDecide[relative]) {+ case .upload: stats.uploads += 1+ case .download: stats.downloads += 1+ case .skip: skipCount += 1+ case .deleteCloud, .deleteLocal: stats.deletes += 1+ }+ }++ if full {+ FilesSyncIndex.markFullScan()+ }+ FilesSyncIndex.save()+ persistQueuedOps()+ pump()+ let idle = withLock { pending.isEmpty && inFlight.isEmpty }+ if idle {+ publish {+ $0.phase = .idle+ $0.completedCount = 0+ $0.totalCount = 0+ $0.currentFileName = nil+ }+ }+ Log.debug("[iCloud Sync] reconcile end full=\(full) saveRootsOnly=\(saveRootsOnly) upload=\(stats.uploads) download=\(stats.downloads) delete=\(stats.deletes) skip=\(skipCount) idle=\(idle) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s \(queueSummary())")+ return stats+#endif+ }++ private func catchUpUntrackedContentTrees() {+ refreshROMExclusion()+ let local = FilesSyncIO.enumerateLocalFiles(mode: .all)+ let ledger = FilesSyncIndex.store.files+ let cloud = withLock { latestCloudFiles }+ let cloudKnown = !cloud.isEmpty+ let intents = FilesSyncIntentStore.allActive()+ var untracked = 0+ var missingOnCloud = 0+ var considered = 0+ for (relative, localFp) in local {+ guard FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: relative) else { continue }+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ considered += 1+ let inLedger = ledger[relative] != nil+ let inCloud = cloud[relative] != nil+ let intent = intents[relative]+ Log.debug("[iCloud Sync] catch-up ROM \(relative) ledger=\(inLedger) cloud=\(inCloud) intent=\(intent?.intent.debugLabel ?? "nil") gen=\(intent?.generation ?? 0) applied=\(FilesSyncIndex.appliedGeneration(for: relative)) \(describe(localFp))")+ if romExclusion.contains(relative) {+ Log.debug("[iCloud Sync] catch-up ROM sync off \(relative) intent=\(intent?.intent.debugLabel ?? "nil")")+ _ = decide(relativePath: relative, local: localFp, cloud: cloudKnown ? cloud[relative] : nil)+ continue+ }+ if !inLedger {+ untracked += 1+ }+ if cloudKnown {+ if decide(relativePath: relative, local: localFp, cloud: cloud[relative]) == .upload, !inCloud {+ missingOnCloud += 1+ }+ } else if intent == nil, !inLedger {+ _ = decide(relativePath: relative, local: localFp, cloud: nil)+ }+ }+ for (relative, intent) in intents where FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: relative) {+ if local[relative] != nil { continue }+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ Log.debug("[iCloud Sync] catch-up remote ROM \(relative) intent=\(intent.intent.debugLabel) gen=\(intent.generation) cloud=\(cloud[relative] != nil) excluded=\(romExclusion.contains(relative))")+ _ = decide(relativePath: relative, local: nil, cloud: cloudKnown ? cloud[relative] : nil)+ }+ Log.debug("[iCloud Sync] catch-up content trees considered=\(considered) untracked=\(untracked) ledgerNotInCloud=\(missingOnCloud) cloudKnown=\(cloudKnown)")+ persistQueuedOps()+ pump()+ }++ private func processLocalChange(_ url: URL) async {+ guard isStarted else { return }+ refreshROMExclusion()+ if url.hasDirectoryPath || isDirectory(url) {+ let files = FilesSyncIO.enumerateLocalFiles(root: url)+ Log.debug("[iCloud Sync] local directory change \(url.path) files=\(files.count)")+ for (relative, _) in files {+ enqueueChange(relativePath: relative)+ }+ } else if let relative = FilesSyncPolicy.documentsRelativePath(from: url) {+ Log.debug("[iCloud Sync] local file change \(relative) exists=\(FileManager.default.fileExists(atPath: url.path))")+ enqueueChange(relativePath: relative)+ } else {+ Log.debug("[iCloud Sync] local change skipped (not under Documents): \(url.path)")+ }+ }++ private func processLocalRemoval(_ url: URL) async {+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: url) else { return }+ let directory = isDirectory(url) || url.hasDirectoryPath+ // Local file may already be gone; still collect children from the ledger/intents.+ let ledgerHits = FilesSyncIndex.store.files.keys.filter { $0 == relative || $0.hasPrefix(relative + "/") }+ let intentHits = FilesSyncIntentStore.paths(matchingPrefix: relative)+ var paths = Array(Set(ledgerHits).union(intentHits))+ if !paths.contains(relative) {+ paths.append(relative)+ }+ Log.debug("[iCloud Sync] local removal \(relative) directory=\(directory) matching=\(paths.count)")+ for path in paths {+ FilesSyncIntentStore.markDeleted(relativePath: path)+ enqueue(FilesSyncOp(relativePath: path, kind: .deleteCloud, tombstoneReason: .deleted, isDirectory: path == relative && directory))+ }+ FilesSyncIndex.save()+ persistQueuedOps()+ pump()+ }++ private func processExcludeCloudCopies(_ urls: [URL]) async {+ for url in urls {+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: url) else { continue }+ let directory = isDirectory(url) || url.hasDirectoryPath+ if directory {+ let localFiles = FilesSyncIO.enumerateLocalFiles(root: url)+ var paths = Array(localFiles.keys)+ paths.append(contentsOf: FilesSyncIntentStore.paths(matchingPrefix: relative))+ paths.append(relative)+ Log.debug("[iCloud Sync] exclude cloud directory \(relative) files=\(Set(paths).count)")+ for path in Set(paths) {+ let generation = FilesSyncIntentStore.markExcluded(relativePath: path)+ FilesSyncIndex.setAppliedGeneration(path, generation)+ enqueue(FilesSyncOp(relativePath: path, kind: .deleteCloud, tombstoneReason: .excluded, isDirectory: path == relative && directory))+ }+ } else {+ Log.debug("[iCloud Sync] exclude cloud file \(relative)")+ let generation = FilesSyncIntentStore.markExcluded(relativePath: relative)+ FilesSyncIndex.setAppliedGeneration(relative, generation)+ enqueue(FilesSyncOp(relativePath: relative, kind: .deleteCloud, tombstoneReason: .excluded, isDirectory: false))+ }+ }+ FilesSyncIndex.save()+ persistQueuedOps()+ pump()+ }++ private func performEnsureLocal(_ url: URL) async -> Error? {+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: url) else { return nil }+ refreshROMExclusion()+ if romExclusion.contains(relative) {+ Log.debug("[iCloud Sync] ensureLocal skipped (ROM excluded): \(relative)")+ return NSError(domain: "FilesSync", code: 1, userInfo: [NSLocalizedDescriptionKey: "ROM sync disabled"])+ }+ if let intent = FilesSyncIntentStore.snapshot(relativePath: relative),+ intent.intent == .deleted || intent.intent == .excluded {+ Log.debug("[iCloud Sync] ensureLocal skipped (intent \(intent.intent.debugLabel)): \(relative)")+ return NSError(domain: "FilesSync", code: 1, userInfo: [NSLocalizedDescriptionKey: "ROM sync disabled"])+ }+ if FileManager.default.fileExists(atPath: url.path) {+ Log.debug("[iCloud Sync] ensureLocal already local: \(relative)")+ return nil+ }+ Log.debug("[iCloud Sync] ensureLocal download \(relative)")+ do {+ try await io.download(relativePath: relative, localURL: url)+ if let fingerprint = FilesSyncIndex.fingerprint(for: url, preferHash: false) {+ let generation = FilesSyncIntentStore.snapshot(relativePath: relative)?.generation+ ?? FilesSyncIndex.appliedGeneration(for: relative)+ FilesSyncIndex.recordSynced(relativePath: relative, fingerprint: fingerprint, generation: generation)+ FilesSyncIndex.save()+ }+ return nil+ } catch {+ Log.debug("[iCloud Sync] ensureLocal failed \(relative): \(error)")+ return error+ }+ }++ private func flushCloudInventory() async {+ let inventory: FilesSyncCloudInventory? = withLock {+ let value = pendingInventory+ pendingInventory = nil+ return value+ }+ guard let inventory else {+ Log.debug("[iCloud Sync] cloud inventory coalesced away")+ return+ }+ await handleCloudInventory(inventory)+ }++ private func handleCloudInventory(_ inventory: FilesSyncCloudInventory) async {+ let previous = withLock { () -> [String: FilesSyncFingerprint] in+ let old = latestCloudFiles+ latestCloudFiles = inventory.files+ notDownloaded = inventory.notDownloaded+ return old+ }+ if progress.isBusy {+ publish { progress in+ progress.currentFileName = inventory.uploading.first ?? inventory.downloading.first ?? progress.currentFileName+ progress.bytesTransferred = inventory.bytesTransferred+ progress.bytesTotal = inventory.bytesTotal+ }+ }+ guard isStarted, !withLock({ pausedForGameplay }) else {+ Log.debug("[iCloud Sync] cloud inventory stored, reconcile deferred started=\(isStarted) paused=\(withLock { pausedForGameplay })")+ return+ }+ await reconcileCloudDelta(previous: previous, inventory: inventory)+ }++ private func reconcileCloudDelta(previous: [String: FilesSyncFingerprint], inventory: FilesSyncCloudInventory) async {+ refreshROMExclusion()+ var decided = 0+ for (relative, cloud) in inventory.files {+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ let localURL = FilesSyncPolicy.localURL(relativePath: relative)+ let localExists = FileManager.default.fileExists(atPath: localURL.path)+ if inventory.notDownloaded.contains(relative), localExists {+ continue+ }+ let local = localExists ? FilesSyncIndex.fingerprint(for: localURL, preferHash: false) : nil+ _ = decide(relativePath: relative, local: local, cloud: cloud)+ decided += 1+ }+ // Listing gaps are unknown. Only apply an explicit newer delete/exclude intent.+ var missing = 0+ for relative in previous.keys where inventory.files[relative] == nil {+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ guard let intent = FilesSyncIntentStore.snapshot(relativePath: relative),+ intent.intent == .deleted || intent.intent == .excluded,+ FilesSyncIndex.appliedGeneration(for: relative) < intent.generation else { continue }+ let localURL = FilesSyncPolicy.localURL(relativePath: relative)+ let localExists = FileManager.default.fileExists(atPath: localURL.path)+ let local = localExists ? FilesSyncIndex.fingerprint(for: localURL, preferHash: false) : nil+ _ = decide(relativePath: relative, local: local, cloud: nil)+ missing += 1+ }+ Log.debug("[iCloud Sync] cloud delta decided=\(decided) intentGaps=\(missing) \(queueSummary())")+ persistQueuedOps()+ pump()+ }++ private func enqueueChange(relativePath: String) {+ if FilesSyncPolicy.shouldNeverSync(relativePath: relativePath) {+ Log.debug("[iCloud Sync] skip local change (never sync): \(relativePath)")+ return+ }+ if romExclusion.contains(relativePath) {+ Log.debug("[iCloud Sync] skip local change (ROM sync off, leave cloud): \(relativePath)")+ return+ }+ Log.debug("[iCloud Sync] enqueue upload \(relativePath)")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .upload, tombstoneReason: nil))+ persistQueuedOps()+ pump()+ }++ @discardableResult+ private func decide(relativePath: String, local: FilesSyncFingerprint?, cloud: FilesSyncFingerprint?) -> FilesSyncDecideAction {+ let intent = FilesSyncIntentStore.snapshot(relativePath: relativePath)+ let applied = FilesSyncIndex.appliedGeneration(for: relativePath)+ let ledger = FilesSyncIndex.store.files[relativePath]?.fingerprint++ // Exclude/delete intents win over "ROM sync off". Turning sync off keeps+ // Drive copies; deleting the game or confirming evict must still remove them.+ if let intent, intent.intent == .excluded {+ if cloud != nil, applied < intent.generation {+ Log.debug("[iCloud Sync] decide \(relativePath) -> deleteCloud (intent excluded gen=\(intent.generation))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .deleteCloud, tombstoneReason: .excluded))+ return .deleteCloud+ }+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (intent excluded gen=\(intent.generation))")+ return .skip+ }++ if let intent, intent.intent == .deleted {+ if applied >= intent.generation {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (delete gen=\(intent.generation) already applied)")+ return .skip+ }+ if local != nil {+ Log.debug("[iCloud Sync] decide \(relativePath) -> deleteLocal (intent deleted gen=\(intent.generation) applied=\(applied))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .deleteLocal, tombstoneReason: .deleted))+ return .deleteLocal+ }+ if cloud != nil {+ Log.debug("[iCloud Sync] decide \(relativePath) -> deleteCloud (intent deleted gen=\(intent.generation))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .deleteCloud, tombstoneReason: .deleted))+ return .deleteCloud+ }+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (delete gen=\(intent.generation), nothing left)")+ FilesSyncIndex.setAppliedGeneration(relativePath, intent.generation)+ return .skip+ }++ // Policy off only stops upload/download. Cloud copies stay until the user+ // confirms excludeCloudCopies or deletes the game.+ if romExclusion.contains(relativePath) {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (ROM sync off)")+ return .skip+ }++ if let intent {+ switch intent.intent {+ case .excluded, .deleted:+ return .skip+ case .present:+ if applied >= intent.generation, local != nil {+ return compareReplicas(relativePath: relativePath, local: local, cloud: cloud, ledger: ledger, intent: intent)+ }+ if local == nil {+ Log.debug("[iCloud Sync] decide \(relativePath) -> download (intent present gen=\(intent.generation) applied=\(applied) cloud=\(cloud != nil))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .download, tombstoneReason: nil))+ return .download+ }+ if cloud == nil {+ // Newer remote generation: wait for the blob instead of re-uploading our older copy.+ Log.debug("[iCloud Sync] decide \(relativePath) -> download (wait for present gen=\(intent.generation) blob) applied=\(applied)")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .download, tombstoneReason: nil))+ return .download+ }+ return compareReplicas(relativePath: relativePath, local: local, cloud: cloud, ledger: ledger, intent: intent)+ }+ }++ // No CloudKit intent yet: never infer delete from a listing gap.+ if let local, let cloud {+ return compareReplicas(relativePath: relativePath, local: local, cloud: cloud, ledger: ledger, intent: nil)+ }+ if let local, cloud == nil {+ Log.debug("[iCloud Sync] decide \(relativePath) -> upload (local only, no intent) \(describe(local))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .upload, tombstoneReason: nil))+ return .upload+ }+ if local == nil, cloud != nil {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (cloud only, intent unknown)")+ return .skip+ }+ return .skip+ }++ @discardableResult+ private func compareReplicas(relativePath: String,+ local: FilesSyncFingerprint?,+ cloud: FilesSyncFingerprint?,+ ledger: FilesSyncFingerprint?,+ intent: FilesSyncIntentSnapshot?) -> FilesSyncDecideAction {+ guard let local, let cloud else { return .skip }+ if let ledger, local.matches(ledger), cloud.matches(ledger) {+ if let intent { FilesSyncIndex.setAppliedGeneration(relativePath, intent.generation) }+ return .skip+ }+ if let ledger, local.matches(ledger), !cloud.matches(ledger) {+ if local.samePayload(cloud) {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (iCloud mtime drift) local=\(describe(local)) cloud=\(describe(cloud))")+ if let intent { FilesSyncIndex.setAppliedGeneration(relativePath, intent.generation) }+ return .skip+ }+ if withLock({ notDownloaded.contains(relativePath) }) {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (cloud not downloaded yet)")+ return .skip+ }+ Log.debug("[iCloud Sync] decide \(relativePath) -> download (cloud changed) local=\(describe(local)) cloud=\(describe(cloud))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .download, tombstoneReason: nil))+ return .download+ }+ if let ledger, cloud.matches(ledger), !local.matches(ledger) {+ Log.debug("[iCloud Sync] decide \(relativePath) -> upload (local changed) local=\(describe(local)) cloud=\(describe(cloud))")+ enqueue(FilesSyncOp(relativePath: relativePath, kind: .upload, tombstoneReason: nil))+ return .upload+ }+ if local.matches(cloud) {+ FilesSyncIndex.recordSynced(relativePath: relativePath, fingerprint: local, generation: intent?.generation)+ return .skip+ }+ if ledger == nil, local.samePayload(cloud) {+ FilesSyncIndex.recordSynced(relativePath: relativePath, fingerprint: local, generation: intent?.generation)+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (size match, first ledger)")+ return .skip+ }+ if withLock({ notDownloaded.contains(relativePath) }) {+ Log.debug("[iCloud Sync] decide \(relativePath) -> skip (cloud not downloaded yet)")+ return .skip+ }+ let localWins = local.mtime >= cloud.mtime+ Log.debug("[iCloud Sync] decide \(relativePath) -> \(localWins ? "upload" : "download") (conflict) local=\(describe(local)) cloud=\(describe(cloud))")+ enqueue(FilesSyncOp(relativePath: relativePath,+ kind: localWins ? .upload : .download,+ tombstoneReason: nil,+ isConflict: true))+ return localWins ? .upload : .download+ }++ private func applyIntentPaths(_ paths: [String]) async {+ refreshROMExclusion()+ let cloud = withLock { latestCloudFiles }+ for relative in Set(paths) {+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ let localURL = FilesSyncPolicy.localURL(relativePath: relative)+ let localExists = FileManager.default.fileExists(atPath: localURL.path)+ let local = localExists ? FilesSyncIndex.fingerprint(for: localURL, preferHash: false) : nil+ _ = decide(relativePath: relative, local: local, cloud: cloud[relative])+ }+ persistQueuedOps()+ pump()+ }++ private func enqueue(_ op: FilesSyncOp) {+ withLock { pending[op.relativePath] = op }+ Log.debug("[iCloud Sync] queue \(op.kind) \(op.relativePath) \(queueSummary())")+ }++ private func pump() {+ withLock {+ if drainTask != nil {+ Log.debug("[iCloud Sync] pump: drain already running pending=\(pending.count) inFlight=\(inFlight.count)")+ return+ }+ if pending.isEmpty, inFlight.isEmpty {+ Log.debug("[iCloud Sync] pump: nothing to drain")+ return+ }+ Log.debug("[iCloud Sync] pump: start drain pending=\(pending.count)")+ drainTask = Task.detached { [weak self] in+ await self?.drain()+ }+ }+ }++ private func drain() async {+ Log.debug("[iCloud Sync] drain begin \(queueSummary()) main=\(Thread.isMainThread)")+ while true {+ if withLock({ pausedForGameplay }) {+ withLock { drainTask = nil }+ Log.debug("[iCloud Sync] drain paused for gameplay")+ publish { $0.phase = .paused }+ break+ }+ if !isStarted {+ withLock { drainTask = nil }+ Log.debug("[iCloud Sync] drain stopped")+ break+ }+ let batch: [(key: String, value: FilesSyncOp)]+ let remaining: Int+ (batch, remaining) = withLock {+ let ready = pending.filter { !inFlight.keys.contains($0.key) }+ let next = Array(ready.prefix(maxConcurrent))+ for item in next {+ inFlight[item.key] = item.value.kind+ }+ return (next.map { (key: $0.key, value: $0.value) }, pending.count)+ }++ if batch.isEmpty {+ let idle = withLock { () -> Bool in+ let idle = inFlight.isEmpty && pending.isEmpty+ if idle { drainTask = nil }+ return idle+ }+ if idle {+ Log.debug("[iCloud Sync] drain idle")+ persistQueuedOps()+ publish {+ $0.phase = .idle+ $0.completedCount = 0+ $0.totalCount = 0+ $0.currentFileName = nil+ }+ }+ if idle { break }+ Log.debug("[iCloud Sync] drain waiting for in-flight \(queueSummary())")+ try? await Task.sleep(nanoseconds: 200_000_000)+ continue+ }++ let names = batch.map { "\($0.value.kind):\($0.value.relativePath)" }.joined(separator: ", ")+ Log.debug("[iCloud Sync] drain batch remaining=\(remaining) [\(names)]")+ publish { progress in+ progress.phase = .syncing+ progress.totalCount = remaining+ progress.currentFileName = batch.first?.value.relativePath+ }++ var completed: [String: Bool] = [:]+ await withTaskGroup(of: (String, Bool).self) { group in+ for item in batch {+ group.addTask { [weak self] in+ let ok = await self?.run(item.value) ?? true+ return (item.key, ok)+ }+ }+ for await result in group {+ completed[result.0] = result.1+ }+ }++ let finished = withLock { () -> Int in+ var count = 0+ for item in batch {+ inFlight[item.key] = nil+ if completed[item.key] == true, pending[item.key]?.kind == item.value.kind {+ pending[item.key] = nil+ count += 1+ }+ }+ return count+ }+ Log.debug("[iCloud Sync] drain batch finished=\(finished)/\(batch.count) \(queueSummary())")+ publish { $0.completedCount += finished }+ }+ FilesSyncIndex.save()+ persistQueuedOps()+ Log.debug("[iCloud Sync] drain end \(queueSummary())")+ }++ /// Returns false when the op should stay queued (e.g. paused during gameplay).+ private func run(_ op: FilesSyncOp) async -> Bool {+ if withLock({ pausedForGameplay }), op.kind == .upload || op.kind == .download {+ Log.debug("[iCloud Sync] run deferred (gameplay) \(op.kind) \(op.relativePath)")+ return false+ }+ let localURL = FilesSyncPolicy.localURL(relativePath: op.relativePath)+ switch op.kind {+ case .upload:+ guard FileManager.default.fileExists(atPath: localURL.path) else {+ Log.debug("[iCloud Sync] upload skipped (missing local): \(op.relativePath)")+ return true+ }+ do {+ if op.isConflict {+ await preserveCloudLoser(op: op, localURL: localURL)+ }+ try await io.upload(localURL: localURL, relativePath: op.relativePath)+ if let fingerprint = FilesSyncIndex.fingerprint(for: localURL, preferHash: false) {+ let generation = FilesSyncIntentStore.markPresent(relativePath: op.relativePath, size: fingerprint.size)+ FilesSyncIndex.recordSynced(relativePath: op.relativePath, fingerprint: fingerprint, generation: generation)+ }+ Log.debug("[iCloud Sync] Uploaded \(op.relativePath)")+ } catch {+ Log.debug("[iCloud Sync] Upload failed \(op.relativePath) retry=\(op.retries): \(error)")+ try? await Task.sleep(nanoseconds: 400_000_000)+ return retryOrDrop(op)+ }+ case .download:+ do {+ let cloud = withLock { latestCloudFiles[op.relativePath] }+ if FileManager.default.fileExists(atPath: localURL.path),+ let local = FilesSyncIndex.fingerprint(for: localURL, preferHash: false),+ let cloud,+ !local.matches(cloud) || op.isConflict {+ preserveLocalLoser(localURL: localURL, relativePath: op.relativePath)+ }+ try await io.download(relativePath: op.relativePath, localURL: localURL)+ if let fingerprint = FilesSyncIndex.fingerprint(for: localURL, preferHash: false) {+ let generation = FilesSyncIntentStore.snapshot(relativePath: op.relativePath)?.generation+ ?? FilesSyncIndex.appliedGeneration(for: op.relativePath)+ FilesSyncIndex.recordSynced(relativePath: op.relativePath, fingerprint: fingerprint, generation: generation)+ }+ Log.debug("[iCloud Sync] Downloaded \(op.relativePath)")+ } catch {+ Log.debug("[iCloud Sync] Download failed \(op.relativePath) retry=\(op.retries): \(error)")+ try? await Task.sleep(nanoseconds: 400_000_000)+ return retryOrDrop(op)+ }+ case .deleteCloud:+ await io.removeCloudItem(relativePath: op.relativePath, isDirectory: op.isDirectory)+ if op.tombstoneReason == .deleted {+ FilesSyncIndex.removeFile(op.relativePath)+ }+ if let intent = FilesSyncIntentStore.snapshot(relativePath: op.relativePath) {+ FilesSyncIndex.setAppliedGeneration(op.relativePath, intent.generation)+ }+ Log.debug("[iCloud Sync] Deleted cloud \(op.relativePath)")+ case .deleteLocal:+ try? FileManager.safeRemoveItem(at: localURL)+ FilesSyncIndex.removeFile(op.relativePath)+ if let intent = FilesSyncIntentStore.snapshot(relativePath: op.relativePath) {+ FilesSyncIndex.setAppliedGeneration(op.relativePath, intent.generation)+ }+ Log.debug("[iCloud Sync] Deleted local \(op.relativePath)")+ }+ return true+ }++ private func retryOrDrop(_ op: FilesSyncOp) -> Bool {+ if op.retries < maxRetries {+ var retry = op+ retry.retries += 1+ withLock { pending[op.relativePath] = retry }+ Log.debug("[iCloud Sync] will retry \(op.kind) \(op.relativePath) (\(retry.retries)/\(maxRetries))")+ return false+ }+ var stored = op+ stored.retries = 0+ withLock { deferred[op.relativePath] = stored }+ persistQueuedOps()+ Log.debug("[iCloud Sync] deferred \(op.kind) \(op.relativePath) after \(op.retries) retries")+ return true+ }++ private func loadDeferredFromDisk() {+ let ops = FilesSyncIndex.loadPending()+ guard !ops.isEmpty else { return }+ withLock {+ for (path, op) in ops {+ if pending[path] == nil {+ deferred[path] = op+ }+ }+ }+ Log.debug("[iCloud Sync] loaded deferred from disk count=\(ops.count) \(queueSummary())")+ }++ private func flushDeferredOps(reason: String) {+ let ops: [FilesSyncOp] = withLock {+ let values = Array(deferred.values)+ deferred.removeAll()+ return values+ }+ guard !ops.isEmpty else {+ Log.debug("[iCloud Sync] flush deferred skipped (\(reason)): empty")+ return+ }+ Log.debug("[iCloud Sync] flush deferred (\(reason)) count=\(ops.count)")+ for var op in ops {+ op.retries = 0+ enqueue(op)+ }+ persistQueuedOps()+ }++ private func persistQueuedOps() {+ let snapshot: [String: FilesSyncOp] = withLock {+ var all = deferred+ for (path, op) in pending {+ all[path] = op+ }+ return all+ }+ FilesSyncIndex.savePending(snapshot)+ }++ private func waitUntilIdle() async {+ while isStarted {+ if withLock({ pausedForGameplay }) {+ Log.debug("[iCloud Sync] waitUntilIdle stopped (gameplay paused)")+ return+ }+ let busy = withLock { drainTask != nil || !pending.isEmpty || !inFlight.isEmpty }+ if !busy { return }+ try? await Task.sleep(nanoseconds: 150_000_000)+ }+ }++ private func preserveLocalLoser(localURL: URL, relativePath: String) {+ if FilesSyncPolicy.isImmutableResource(relativePath: relativePath) {+ let sibling = FilesSyncIndex.conflictSiblingURL(for: localURL)+ try? FileManager.safeCopyItem(at: localURL, to: sibling, shouldReplace: true)+ Log.debug("[iCloud Sync] Kept local conflict copy: \(sibling.lastPathComponent)")+ } else {+ FilesSyncIndex.backupLoser(localURL: localURL, relativePath: relativePath)+ }+ }++ private func preserveCloudLoser(op: FilesSyncOp, localURL: URL) async {+ if FilesSyncPolicy.isImmutableResource(relativePath: op.relativePath) {+ let sibling = FilesSyncIndex.conflictSiblingURL(for: localURL)+ try? await io.download(relativePath: op.relativePath, localURL: sibling)+ Log.debug("[iCloud Sync] Kept cloud conflict copy: \(sibling.lastPathComponent)")+ } else {+ try? FileManager.default.createDirectory(atPath: R.Path.FilesSyncConflicts, withIntermediateDirectories: true)+ let dest = URL(fileURLWithPath: R.Path.FilesSyncConflicts)+ .appendingPathComponent("cloud_\(op.relativePath.replacingOccurrences(of: "/", with: "_"))")+ try? await io.download(relativePath: op.relativePath, localURL: dest)+ }+ }++ private func isDirectory(_ url: URL) -> Bool {+ var isDir: ObjCBool = false+ return FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir) && isDir.boolValue+ }++ private func refreshROMExclusion() {+ romExclusion = FilesSyncPolicy.romExclusionSnapshot()+ Log.debug("[iCloud Sync] ROM exclusion files=\(romExclusion.files.count) prefixes=\(romExclusion.prefixes.count)")+ if !romExclusion.files.isEmpty {+ Log.debug("[iCloud Sync] ROM excluded files: \(romExclusion.files.sorted().prefix(10).joined(separator: ", "))")+ }+ }++ private func enqueueWork(_ name: String, _ body: @escaping () async -> Void) {+ lock.lock()+ let previous = workTail+ let next = Task.detached(priority: .utility) {+ await previous.value+ Log.debug("[iCloud Sync] work begin: \(name) main=\(Thread.isMainThread)")+ await body()+ Log.debug("[iCloud Sync] work end: \(name)")+ }+ workTail = next+ lock.unlock()+ }++ private func withLock<T>(_ body: () -> T) -> T {+ lock.lock()+ defer { lock.unlock() }+ return body()+ }++ private func queueSummary() -> String {+ withLock {+ "pending=\(pending.count) deferred=\(deferred.count) inFlight=\(inFlight.count) draining=\(drainTask != nil)"+ }+ }++ private func describe(_ fingerprint: FilesSyncFingerprint?) -> String {+ guard let fingerprint else { return "nil" }+ return "size=\(fingerprint.size) mtime=\(Int(fingerprint.mtime))"+ }++ private func publish(_ update: (inout FilesSyncProgress) -> Void) {+ var next = progress+ update(&next)+ if next.phase != progress.phase || next.currentFileName != progress.currentFileName || next.totalCount != progress.totalCount {+ Log.debug("[iCloud Sync] progress phase=\(next.phase.rawValue) file=\(next.currentFileName ?? "-") completed=\(next.completedCount)/\(next.totalCount)")+ }+ progress = next+ DispatchQueue.main.async {+ NotificationCenter.default.post(name: R.NotificationName.iCloudDriveSyncChange, object: next)+ }+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIO.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIO.swiftnew file mode 100644index 00000000..36b7163f--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIO.swift@@ -0,0 +1,200 @@+//+// FilesSyncIO.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation+import SwiftCloudDrive++final class FilesSyncIO {+ private var cloudDrive: CloudDrive?++ func prepare() async throws {+ if cloudDrive == nil {+ Log.debug("[iCloud Sync] CloudDrive init begin main=\(Thread.isMainThread)")+ let startedAt = Date()+ cloudDrive = try await CloudDrive()+ Log.debug("[iCloud Sync] CloudDrive init end elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s")+ }+ }++ func fileExists(relativePath: String) async -> Bool {+ guard let cloudDrive = try? await resolvedDrive() else { return false }+ return (try? await cloudDrive.fileExists(at: RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath)))) ?? false+ }++ func directoryExists(relativePath: String) async -> Bool {+ guard let cloudDrive = try? await resolvedDrive() else { return false }+ return (try? await cloudDrive.directoryExists(at: RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath)))) ?? false+ }++ func upload(localURL: URL, relativePath: String) async throws {+ let startedAt = Date()+ Log.debug("[iCloud Sync] Upload begin \(relativePath) main=\(Thread.isMainThread) bytes=\(localFileSize(localURL))")+ let drive = try await resolvedDrive()+ let parentRelative = (relativePath as NSString).deletingLastPathComponent+ if !parentRelative.isEmpty, parentRelative != "." {+ let parent = RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: parentRelative))+ if !(try await drive.directoryExists(at: parent)) {+ Log.debug("[iCloud Sync] Create cloud directory \(parentRelative)")+ try await drive.createDirectory(at: parent)+ }+ }+ let cloudPath = RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath))+ if (try? await drive.fileExists(at: cloudPath)) == true {+ Log.debug("[iCloud Sync] Replace existing cloud file \(relativePath)")+ try await drive.removeFile(at: cloudPath)+ }+ try await drive.upload(from: localURL, to: cloudPath)+ Log.debug("[iCloud Sync] Upload end \(relativePath) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s")+ }++ func download(relativePath: String, localURL: URL) async throws {+ let startedAt = Date()+ Log.debug("[iCloud Sync] Download begin \(relativePath) main=\(Thread.isMainThread)")+ let drive = try await resolvedDrive()+ let cloudPath = RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath))+ let tempURL = URL(fileURLWithPath: R.Path.Temp.appendingPathComponent(UUID().uuidString + "-" + localURL.lastPathComponent))+ try await drive.download(from: cloudPath, toURL: tempURL)+ try FileManager.default.createDirectory(at: localURL.deletingLastPathComponent(), withIntermediateDirectories: true)+ try coordinateLocalReplace(from: tempURL, to: localURL)+ Log.debug("[iCloud Sync] Download end \(relativePath) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s")+ }++ func removeFile(relativePath: String) async throws {+ Log.debug("[iCloud Sync] Remove cloud file \(relativePath)")+ let drive = try await resolvedDrive()+ try await drive.removeFile(at: RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath)))+ }++ func removeDirectory(relativePath: String) async throws {+ Log.debug("[iCloud Sync] Remove cloud directory \(relativePath)")+ let drive = try await resolvedDrive()+ try await drive.removeDirectory(at: RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relativePath)))+ }++ func removeCloudItem(relativePath: String, isDirectory: Bool) async {+ do {+ if isDirectory {+ try await removeDirectory(relativePath: relativePath)+ } else {+ try await removeFile(relativePath: relativePath)+ }+ } catch {+ Log.debug("[iCloud Sync] Failed to remove cloud item \(relativePath): \(error)")+ }+ }++ func listCloudFiles() async -> [String: FilesSyncFingerprint] {+ let startedAt = Date()+ guard let drive = try? await resolvedDrive() else {+ Log.debug("[iCloud Sync] listCloudFiles skipped: CloudDrive unavailable")+ return [:]+ }+ var result: [String: FilesSyncFingerprint] = [:]+ await collectCloudFiles(at: RootRelativePath(path: "Documents"), drive: drive, into: &result)+ Log.debug("[iCloud Sync] listCloudFiles count=\(result.count) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s main=\(Thread.isMainThread)")+ return result+ }++ private func resolvedDrive() async throws -> CloudDrive {+ if let cloudDrive { return cloudDrive }+ let drive = try await CloudDrive()+ cloudDrive = drive+ return drive+ }++ private func collectCloudFiles(at path: RootRelativePath,+ drive: CloudDrive,+ into result: inout [String: FilesSyncFingerprint]) async {+ let keys: [URLResourceKey] = [.isRegularFileKey, .isDirectoryKey, .contentModificationDateKey, .fileSizeKey]+ guard let items = try? await drive.contentsOfDirectory(at: path, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else {+ return+ }+ for item in items {+ guard let values = try? item.resourceValues(forKeys: Set(keys)),+ let relative = FilesSyncPolicy.documentsRelativePath(from: item) else { continue }+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) {+ continue+ }+ if values.isDirectory == true {+ await collectCloudFiles(at: RootRelativePath(path: FilesSyncPolicy.cloudRootPath(relativePath: relative)), drive: drive, into: &result)+ } else if values.isRegularFile == true {+ let size = Int64(values.fileSize ?? 0)+ let mtime = values.contentModificationDate?.timeIntervalSince1970 ?? 0+ result[relative] = FilesSyncFingerprint(size: size, mtime: mtime, hash: nil)+ }+ }+ }++ enum EnumerationMode {+ case all+ case saveRoots+ }++ static func enumerateLocalFiles(root: URL = URL(fileURLWithPath: R.Path.Document),+ mode: EnumerationMode = .all) -> [String: FilesSyncFingerprint] {+ let startedAt = Date()+ var result: [String: FilesSyncFingerprint] = [:]+ let keys: [URLResourceKey] = [.isRegularFileKey, .isDirectoryKey, .contentModificationDateKey, .fileSizeKey]+ guard let enumerator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: keys, options: [.skipsHiddenFiles]) else {+ Log.debug("[iCloud Sync] enumerateLocalFiles failed to create enumerator mode=\(mode) root=\(root.lastPathComponent)")+ return result+ }+ for case let item as URL in enumerator {+ guard let values = try? item.resourceValues(forKeys: Set(keys)),+ let relative = FilesSyncPolicy.documentsRelativePath(from: item) else { continue }+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) {+ if values.isDirectory == true {+ enumerator.skipDescendants()+ }+ continue+ }+ if mode == .saveRoots, FilesSyncPolicy.shouldSkipOnSaveScan(relativePath: relative) {+ if values.isDirectory == true {+ enumerator.skipDescendants()+ }+ continue+ }+ if values.isDirectory == true { continue }+ if values.isRegularFile == true {+ let size = Int64(values.fileSize ?? 0)+ let mtime = values.contentModificationDate?.timeIntervalSince1970 ?? 0+ result[relative] = FilesSyncFingerprint(size: size, mtime: mtime, hash: nil)+ }+ }+ Log.debug("[iCloud Sync] enumerateLocalFiles mode=\(mode) count=\(result.count) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s main=\(Thread.isMainThread)")+ return result+ }++ private func localFileSize(_ url: URL) -> Int64 {+ (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Int64($0) } ?? 0+ }++ private func ubiquityURL(relativePath: String) -> URL? {+ FileManager.default.url(forUbiquityContainerIdentifier: nil)?+ .appendingPathComponent("Documents", isDirectory: true)+ .appendingPathComponent(relativePath)+ }++ private func coordinateLocalReplace(from tempURL: URL, to localURL: URL) throws {+ var coordinatorError: NSError?+ var replaceError: NSError?+ NSFileCoordinator().coordinate(writingItemAt: localURL, options: .forReplacing, error: &coordinatorError) { url in+ do {+ if FileManager.default.fileExists(atPath: url.path) {+ _ = try FileManager.default.replaceItemAt(url, withItemAt: tempURL)+ } else {+ try FileManager.safeMoveItem(at: tempURL, to: url, shouldReplace: true)+ }+ } catch {+ replaceError = error as NSError+ }+ }+ if let coordinatorError { throw coordinatorError }+ if let replaceError { throw replaceError }+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIndex.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIndex.swiftnew file mode 100644index 00000000..f7b1a5bb--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncIndex.swift@@ -0,0 +1,193 @@+//+// FilesSyncIndex.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation+import Device++struct FilesSyncFingerprint: Codable, Equatable {+ var size: Int64+ var mtime: TimeInterval+ var hash: String?++ func matches(_ other: FilesSyncFingerprint) -> Bool {+ if size != other.size { return false }+ if let hash, let otherHash = other.hash {+ return hash == otherHash+ }+ return abs(mtime - other.mtime) < 2+ }++ /// iCloud often restamps mtime after upload; size (and hash when present) is the real identity.+ func samePayload(_ other: FilesSyncFingerprint) -> Bool {+ if size != other.size { return false }+ if let hash, let otherHash = other.hash {+ return hash == otherHash+ }+ return true+ }+}++enum FilesSyncTombstone {+ enum Reason: String, Codable {+ case deleted+ case excluded+ }+}++struct FilesSyncIndexStore: Codable {+ var files: [String: FilesSyncLedgerEntry] = [:]+ var lastFullScan: TimeInterval?+ /// Local change-token: last intent generation applied on this device.+ var appliedGenerations: [String: Int] = [:]++ init() {}++ init(from decoder: Decoder) throws {+ let container = try decoder.container(keyedBy: CodingKeys.self)+ files = try container.decodeIfPresent([String: FilesSyncLedgerEntry].self, forKey: .files) ?? [:]+ lastFullScan = try container.decodeIfPresent(TimeInterval.self, forKey: .lastFullScan)+ appliedGenerations = try container.decodeIfPresent([String: Int].self, forKey: .appliedGenerations) ?? [:]+ }+}++struct FilesSyncLedgerEntry: Codable {+ var fingerprint: FilesSyncFingerprint+ var lastSyncedAt: TimeInterval+}++struct FilesSyncPendingStore: Codable {+ var ops: [String: FilesSyncOp] = [:]+}++enum FilesSyncIndex {+ private static let lock = NSLock()+ private static let hashSizeLimit: Int64 = 4 * 1024 * 1024+ private static var _store = FilesSyncIndexStore()++ static var store: FilesSyncIndexStore {+ lock.lock()+ defer { lock.unlock() }+ return _store+ }++ static func modify(_ body: (inout FilesSyncIndexStore) -> Void) {+ lock.lock()+ body(&_store)+ lock.unlock()+ }++ static func load() {+ try? FileManager.default.createDirectory(atPath: R.Path.FilesSync, withIntermediateDirectories: true)+ if let data = try? Data(contentsOf: URL(fileURLWithPath: R.Path.FilesSyncIndex)),+ let decoded = try? JSONDecoder().decode(FilesSyncIndexStore.self, from: data) {+ modify { $0 = decoded }+ Log.debug("[iCloud Sync] ledger loaded files=\(decoded.files.count) applied=\(decoded.appliedGenerations.count) lastFullScan=\(decoded.lastFullScan.map { String(Int($0)) } ?? "nil")")+ } else {+ modify { $0 = FilesSyncIndexStore() }+ Log.debug("[iCloud Sync] ledger missing, starting empty")+ }+ }++ static func save() {+ try? FileManager.default.createDirectory(atPath: R.Path.FilesSync, withIntermediateDirectories: true)+ let snapshot = store+ if let data = try? JSONEncoder().encode(snapshot) {+ try? data.write(to: URL(fileURLWithPath: R.Path.FilesSyncIndex), options: .atomic)+ }+ }++ static func loadPending() -> [String: FilesSyncOp] {+ guard let data = try? Data(contentsOf: URL(fileURLWithPath: R.Path.FilesSyncPending)),+ let decoded = try? JSONDecoder().decode(FilesSyncPendingStore.self, from: data) else {+ Log.debug("[iCloud Sync] pending store empty")+ return [:]+ }+ Log.debug("[iCloud Sync] pending store loaded ops=\(decoded.ops.count)")+ return decoded.ops+ }++ static func savePending(_ ops: [String: FilesSyncOp]) {+ try? FileManager.default.createDirectory(atPath: R.Path.FilesSync, withIntermediateDirectories: true)+ let store = FilesSyncPendingStore(ops: ops)+ if ops.isEmpty {+ try? FileManager.default.removeItem(atPath: R.Path.FilesSyncPending)+ Log.debug("[iCloud Sync] pending store cleared")+ return+ }+ if let data = try? JSONEncoder().encode(store) {+ try? data.write(to: URL(fileURLWithPath: R.Path.FilesSyncPending), options: .atomic)+ Log.debug("[iCloud Sync] pending store saved ops=\(ops.count)")+ }+ }++ static var needsInitialScan: Bool {+ store.lastFullScan == nil+ }++ static func fingerprint(for url: URL, preferHash: Bool) -> FilesSyncFingerprint? {+ let values = try? url.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey])+ if values?.isDirectory == true { return nil }+ let size = Int64(values?.fileSize ?? 0)+ let mtime = values?.contentModificationDate?.timeIntervalSince1970 ?? 0+ var hash: String? = nil+ if preferHash, size > 0, size <= hashSizeLimit {+ hash = FileHashUtil.truncatedHash(url: url)+ }+ return FilesSyncFingerprint(size: size, mtime: mtime, hash: hash)+ }++ static func recordSynced(relativePath: String, fingerprint: FilesSyncFingerprint, generation: Int? = nil) {+ modify {+ $0.files[relativePath] = FilesSyncLedgerEntry(fingerprint: fingerprint, lastSyncedAt: Date().timeIntervalSince1970)+ if let generation {+ $0.appliedGenerations[relativePath] = generation+ }+ }+ }++ static func appliedGeneration(for relativePath: String) -> Int {+ store.appliedGenerations[relativePath] ?? 0+ }++ static func setAppliedGeneration(_ relativePath: String, _ generation: Int) {+ modify { $0.appliedGenerations[relativePath] = generation }+ }++ static func removeFile(_ relativePath: String) {+ modify { $0.files[relativePath] = nil }+ }++ static func markFullScan() {+ modify { $0.lastFullScan = Date().timeIntervalSince1970 }+ }++ static func backupLoser(localURL: URL, relativePath: String) {+ try? FileManager.default.createDirectory(atPath: R.Path.FilesSyncConflicts, withIntermediateDirectories: true)+ let stamp = Int(Date().timeIntervalSince1970)+ let dest = URL(fileURLWithPath: R.Path.FilesSyncConflicts)+ .appendingPathComponent("\(stamp)_\(relativePath.replacingOccurrences(of: "/", with: "_"))")+ try? FileManager.safeCopyItem(at: localURL, to: dest, shouldReplace: true)+ Log.debug("[iCloud Sync] Conflict backup: \(relativePath) -> \(dest.lastPathComponent)")+ }++ static func conflictSiblingURL(for url: URL) -> URL {+ let device = Device.version().rawValue+ .replacingOccurrences(of: "/", with: "-")+ .replacingOccurrences(of: " ", with: "-")+ let stamp = Int(Date().timeIntervalSince1970)+ let ext = url.pathExtension+ let base = url.deletingPathExtension().lastPathComponent+ let name: String+ if ext.isEmpty {+ name = "\(base).conflict.\(device).\(stamp)"+ } else {+ name = "\(base).conflict.\(device).\(stamp).\(ext)"+ }+ return url.deletingLastPathComponent().appendingPathComponent(name)+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncManager.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncManager.swiftnew file mode 100644index 00000000..6bc56256--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncManager.swift@@ -0,0 +1,409 @@+//+// FilesSyncManager.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation+import CloudKit+import Network+import RealmSwift++struct FilesSyncProgress {+ enum Phase: String {+ case idle+ case scanning+ case syncing+ case paused+ case unavailable+ }++ var phase: Phase = .idle+ var completedCount: Int = 0+ var totalCount: Int = 0+ var bytesTransferred: Int64 = 0+ var bytesTotal: Int64 = 0+ var currentFileName: String?++ var fraction: Float {+ if totalCount <= 0 {+ return phase == .idle ? 1 : 0+ }+ return min(1, Float(completedCount) / Float(totalCount))+ }++ var isBusy: Bool {+ phase == .scanning || phase == .syncing+ }+}++struct FilesSyncRepairStats {+ var uploads: Int = 0+ var downloads: Int = 0+ var deletes: Int = 0++ var queued: Int { uploads + downloads + deletes }+}++enum FilesSyncROMAvailability {+ case local+ case syncing+ case excluded+ case missing+}++enum FilesSyncRepairEvent {+ case alreadyRunning+ case notStarted+ case scanFinished(FilesSyncRepairStats)+ case completed(uploaded: Int, downloaded: Int, remaining: Int)+}++final class FilesSyncManager {+ static let shared = FilesSyncManager()++ private let engine = FilesSyncEngine()+ private let watchers = FilesSyncWatchers()+ private var startPlayToken: Any?+ private var stopPlayToken: Any?+ private var accountToken: Any?+ private var pathMonitor: NWPathMonitor?+ private var networkSatisfied = false+ private var intentToken: NotificationToken?++ private(set) var progress = FilesSyncProgress()++ var hasDownloadTask: Bool { engine.hasDownloadTask }++ var syncState: SyncManager.SyncState {+ switch progress.phase {+ case .idle, .paused:+ return .idle+ case .scanning, .syncing:+ return .syncing+ case .unavailable:+ return .undefine+ }+ }++ private init() {+ engine.onProgress = { [weak self] progress in+ self?.progress = progress+ }+ watchers.onCloudInventory = { [weak self] inventory in+ self?.engine.applyCloudInventory(inventory)+ }+ }++ func start() {+#if SIDE_LOAD+ return+#else+ guard Settings.iCloudSyncEnableValue else {+ Log.debug("[iCloud Sync] Manager.start skipped (disabled) main=\(Thread.isMainThread)")+ return+ }+ Log.debug("[iCloud Sync] Manager.start main=\(Thread.isMainThread)")+ observeLifecycleIfNeeded()+ watchers.start()+ engine.start()+ startPathMonitor()+ observeIntentRecords()+#endif+ }++ func stop() {+ Log.debug("[iCloud Sync] Manager.stop main=\(Thread.isMainThread)")+ stopPathMonitor()+ watchers.stop()+ engine.stop()+ intentToken = nil+ progress = FilesSyncProgress()+ NotificationCenter.default.post(name: R.NotificationName.iCloudDriveSyncChange, object: progress)+ }++ func noteLocalChange(at url: URL) {+#if SIDE_LOAD+ return+#else+ guard Settings.iCloudSyncEnableValue else {+ Log.debug("[iCloud Sync] noteLocalChange skipped (disabled): \(url.path)")+ return+ }+ Log.debug("[iCloud Sync] Manager.noteLocalChange \(url.path)")+ engine.noteLocalChange(at: url)+#endif+ }++ func noteLocalChange(path: String) {+ noteLocalChange(at: URL(fileURLWithPath: path))+ }++ func noteLocalRemoval(at url: URL) {+#if SIDE_LOAD+ return+#else+ guard Settings.iCloudSyncEnableValue else { return }+ engine.noteLocalRemoval(at: url)+#endif+ }++ func noteLocalRemoval(path: String) {+ noteLocalRemoval(at: URL(fileURLWithPath: path))+ }++ /// Drop Drive copies when the user deletes a game, even if ROM sync is off+ /// and the cloud file was kept.+ func noteGameROMRemoval(for game: Game) {+#if SIDE_LOAD+ return+#else+ guard FilesSyncPolicy.isDriveSyncAvailable else { return }+ let urls = game.iCloudROMFileURLs+ Log.debug("[iCloud Sync] noteGameROMRemoval game=\(game.name) count=\(urls.count)")+ for url in urls {+ noteLocalRemoval(at: url)+ }+#endif+ }++ func romAvailability(for game: Game) -> FilesSyncROMAvailability {+ if game.isRomExtsts {+ return .local+ }+#if SIDE_LOAD+ return .missing+#else+ if !Settings.iCloudSyncEnableValue {+ return .missing+ }+ if !FilesSyncPolicy.shouldSyncROM(game) {+ return .excluded+ }+ for url in game.iCloudROMFileURLs {+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: url) else { continue }+ if FileManager.default.fileExists(atPath: url.path) { continue }+ if FilesSyncIntentStore.hasPresentIntent(relativePath: relative, isDirectory: true) {+ return .syncing+ }+ }+ return .missing+#endif+ }++ func ensureROM(for game: Game, completion: ((Error?) -> Void)? = nil) {+#if SIDE_LOAD+ completion?(NSError(domain: "FilesSync", code: 1, userInfo: [NSLocalizedDescriptionKey: "ROM sync disabled"]))+ return+#else+ if !FilesSyncPolicy.shouldSyncROM(game) {+ completion?(NSError(domain: "FilesSync", code: 1, userInfo: [NSLocalizedDescriptionKey: "ROM sync disabled"]))+ return+ }+ let urls = game.iCloudROMFileURLs+ Log.debug("[iCloud Sync] ensureROM game=\(game.name) urls=\(urls.map(\.lastPathComponent).joined(separator: ","))")+ Task.detached {+ var lastError: Error?+ for url in urls {+ if FileManager.default.fileExists(atPath: url.path) {+ Log.debug("[iCloud Sync] ensureROM already local: \(url.lastPathComponent)")+ continue+ }+ if let error = await self.engine.ensureLocal(at: url) {+ lastError = error+ }+ }+ let errorToReport = lastError+ await MainActor.run {+ completion?(errorToReport)+ }+ }+#endif+ }++ func ensureLocal(at url: URL, completion: ((Error?) -> Void)? = nil) {+#if SIDE_LOAD+ completion?(nil)+ return+#else+ Task.detached {+ let error = await self.engine.ensureLocal(at: url)+ await MainActor.run {+ completion?(error)+ }+ }+#endif+ }++ func cloudFileExists(localFilePath: String, completion: ((Bool) -> Void)? = nil) {+ guard let relative = FilesSyncPolicy.documentsRelativePath(from: localFilePath) else {+ completion?(false)+ return+ }+ Task.detached {+ let exists = await self.engine.cloudFileExists(relativePath: relative)+ await MainActor.run {+ completion?(exists)+ }+ }+ }++ func reconcile() {+#if SIDE_LOAD+ return+#else+ guard Settings.iCloudSyncEnableValue else { return }+ Log.debug("[iCloud Sync] Manager.reconcile requested")+ engine.requestReconcile(full: false)+#endif+ }++ func repair(_ handler: @escaping (FilesSyncRepairEvent) -> Void) -> Bool {+#if SIDE_LOAD+ DispatchQueue.main.async { handler(.notStarted) }+ return false+#else+ guard Settings.iCloudSyncEnableValue else {+ Log.debug("[iCloud Sync] Manager.repair skipped (disabled)")+ DispatchQueue.main.async { handler(.notStarted) }+ return false+ }+ Log.debug("[iCloud Sync] Manager.repair requested")+ return engine.requestRepair(handler)+#endif+ }++ func excludeCloudROMs(for games: [Game]) {+#if SIDE_LOAD+ return+#else+ guard FilesSyncPolicy.isDriveSyncAvailable else { return }+ var urls: [URL] = []+ for game in games {+ urls.append(contentsOf: game.iCloudROMFileURLs)+ }+ engine.excludeCloudCopies(urls: urls)+#endif+ }++ /// Upload or evict Drive copies after the user assigns or changes GameType.+ func applyROMSyncAfterGameTypeChange(for games: [Game]) {+#if SIDE_LOAD+ return+#else+ guard FilesSyncPolicy.isDriveSyncAvailable, !games.isEmpty else { return }+ var evict: [Game] = []+ for game in games {+ if FilesSyncPolicy.shouldSyncROM(game) {+ uploadROMFiles(for: game)+ } else {+ evict.append(game)+ }+ }+ if !evict.isEmpty {+ excludeCloudROMs(for: evict)+ }+#endif+ }++ func uploadROMFiles(for game: Game, extraFiles: [URL] = []) {+#if SIDE_LOAD+ return+#else+ guard FilesSyncPolicy.isDriveSyncAvailable else {+ Log.debug("[iCloud Sync] uploadROMFiles skipped (iCloud unavailable): \(game.name)")+ return+ }+ guard FilesSyncPolicy.shouldSyncROM(game) else {+ Log.debug("[iCloud Sync] uploadROMFiles skipped (ROM sync disabled): \(game.name)")+ return+ }+ var urls = game.iCloudROMFileURLs+ urls.append(contentsOf: extraFiles)+ Log.debug("[iCloud Sync] uploadROMFiles game=\(game.name) count=\(Set(urls).count) files=\(Set(urls).map(\.lastPathComponent).joined(separator: ","))")+ for url in Set(urls) {+ noteLocalChange(at: url)+ }+#endif+ }++ func handleDidBecomeActive() {+ Log.debug("[iCloud Sync] Manager.handleDidBecomeActive main=\(Thread.isMainThread)")+ engine.handleDidBecomeActive()+ }++ func handleAccountChange() {+ guard Settings.iCloudSyncEnableValue else { return }+ stop()+ start()+ }++ private func observeLifecycleIfNeeded() {+ if startPlayToken == nil {+ startPlayToken = NotificationCenter.default.addObserver(forName: R.NotificationName.StartPlayGame, object: nil, queue: .main) { [weak self] _ in+ self?.engine.setPausedForGameplay(true)+ }+ }+ if stopPlayToken == nil {+ stopPlayToken = NotificationCenter.default.addObserver(forName: R.NotificationName.StopPlayGame, object: nil, queue: .main) { [weak self] _ in+ self?.engine.setPausedForGameplay(false)+ }+ }+ if accountToken == nil {+ accountToken = NotificationCenter.default.addObserver(forName: .CKAccountChanged, object: nil, queue: .main) { [weak self] _ in+ self?.handleAccountChange()+ }+ }+ }++ private func startPathMonitor() {+ guard pathMonitor == nil else { return }+ let monitor = NWPathMonitor()+ pathMonitor = monitor+ monitor.pathUpdateHandler = { [weak self] path in+ guard let self else { return }+ let satisfied = path.status == .satisfied+ let becameSatisfied = satisfied && !self.networkSatisfied+ self.networkSatisfied = satisfied+ if becameSatisfied {+ Log.debug("[iCloud Sync] network became satisfied")+ self.engine.handleNetworkSatisfied()+ } else if !satisfied {+ Log.debug("[iCloud Sync] network unsatisfied")+ }+ }+ monitor.start(queue: DispatchQueue.global(qos: .utility))+ Log.debug("[iCloud Sync] network path monitor started")+ }++ private func stopPathMonitor() {+ pathMonitor?.cancel()+ pathMonitor = nil+ networkSatisfied = false+ Log.debug("[iCloud Sync] network path monitor stopped")+ }++ private func observeIntentRecords() {+#if SIDE_LOAD+ return+#else+ intentToken = Database.realm.objects(FilesSyncRecord.self).where { !$0.isDeleted }.observe { [weak self] changes in+ guard let self else { return }+ switch changes {+ case .initial:+ break+ case .update(let collection, _, let insertions, let modifications):+ var paths: [String] = []+ for index in insertions + modifications where index < collection.count {+ paths.append(collection[index].path)+ }+ self.engine.handleIntentPaths(paths)+ case .error(let error):+ Log.debug("[iCloud Sync] intent observe error: \(error)")+ }+ }+#endif+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncPolicy.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncPolicy.swiftnew file mode 100644index 00000000..39897053--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncPolicy.swift@@ -0,0 +1,345 @@+//+// FilesSyncPolicy.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation+import RealmSwift++struct FilesSyncROMExclusion {+ var files: Set<String> = []+ var prefixes: Set<String> = []++ func contains(_ relativePath: String) -> Bool {+ if files.contains(relativePath) { return true }+ for prefix in prefixes {+ if relativePath == prefix || relativePath.hasPrefix(prefix + "/") {+ return true+ }+ }+ return false+ }+}++enum FilesSyncPolicy {+ private static let neverSyncPrefixes = [+ "wpkdata",+ "SYSTEM/CACHE",+ ".manic-sync",+ "cream_assets",+ "IceCream",+ "IceCreamAssets",+ "cream"+ ]++ static func documentsRelativePath(from url: URL) -> String? {+ documentsRelativePath(from: url.path)+ }++ static func documentsRelativePath(from path: String) -> String? {+ let document = R.Path.Document+ if path.hasPrefix(document) {+ var relative = String(path.dropFirst(document.count))+ if relative.hasPrefix("/") {+ relative.removeFirst()+ }+ return relative.isEmpty ? nil : relative+ }+ if let range = path.range(of: "/Documents/") {+ return String(path[range.upperBound...])+ }+ return nil+ }++ static func localURL(relativePath: String) -> URL {+ URL(fileURLWithPath: R.Path.Document.appendingPathComponent(relativePath))+ }++ static func cloudRootPath(relativePath: String) -> String {+ "Documents/\(relativePath)"+ }++ static func shouldNeverSync(relativePath: String) -> Bool {+ let last = (relativePath as NSString).lastPathComponent+ if last.hasPrefix(".") {+ return true+ }+ for prefix in neverSyncPrefixes {+ if relativePath == prefix || relativePath.hasPrefix(prefix + "/") {+ return true+ }+ }+ return false+ }++ static func isROMContentTree(relativePath: String) -> Bool {+ relativePath == "Datas"+ || relativePath.hasPrefix("Datas/")+ || relativePath == "PPSSPP/PSP/GAME"+ || relativePath.hasPrefix("PPSSPP/PSP/GAME/")+ }++ static func isInstalled3DSContent(relativePath: String) -> Bool {+ relativePath.contains("/title/") && (relativePath.contains("/content/") || relativePath.hasSuffix("/content"))+ }++ static func isImmutableResource(relativePath: String) -> Bool {+ isROMContentTree(relativePath: relativePath) || relativePath == "BIOS" || relativePath.hasPrefix("BIOS/")+ }++ static func shouldSkipOnSaveScan(relativePath: String) -> Bool {+ isROMContentTree(relativePath: relativePath) || isInstalled3DSContent(relativePath: relativePath)+ }++ static func configurableROMGameTypes() -> [GameType] {+ System.allGameTypes.filter { $0 != .symbian && !$0.externalType }+ }++ /// Settings for the calling thread. `Settings.defalut` is confined to the thread that first loaded it.+ private static func threadLocalSettings() -> Settings? {+ Database.realm.object(ofType: Settings.self, forPrimaryKey: Settings.defaultName)+ }++ /// iCloud Drive file sync is on and the user can use it.+ static var isDriveSyncAvailable: Bool {+#if SIDE_LOAD+ return false+#else+ return Settings.iCloudSyncEnableValue && PurchaseManager.isMember+#endif+ }++ static func isPlatformROMSyncEnabled(_ gameType: GameType) -> Bool {+#if SIDE_LOAD+ return false+#else+ if gameType == .unknown || gameType == .notSupport { return false }+ if gameType == .symbian { return true }+ let key = gameType.localizedShortName+ guard let raw = threadLocalSettings()?.getExtra(key: ExtraKey.iCloudSyncROMPlatforms.rawValue) else {+ return true+ }+ if let dict = raw as? [String: Bool] {+ return dict[key] ?? true+ }+ if let dict = raw as? [String: Any] {+ if let value = dict[key] as? Bool { return value }+ if let number = dict[key] as? NSNumber { return number.boolValue }+ }+ return true+#endif+ }++ static func setPlatformROMSyncEnabled(_ gameType: GameType, enabled: Bool) {+#if SIDE_LOAD+ return+#else+ guard let settings = threadLocalSettings() else { return }+ var map: [String: Bool] = [:]+ if let raw = settings.getExtra(key: ExtraKey.iCloudSyncROMPlatforms.rawValue) as? [String: Bool] {+ map = raw+ } else if let raw = settings.getExtra(key: ExtraKey.iCloudSyncROMPlatforms.rawValue) as? [String: Any] {+ for (key, value) in raw {+ if let flag = value as? Bool {+ map[key] = flag+ } else if let number = value as? NSNumber {+ map[key] = number.boolValue+ }+ }+ }+ map[gameType.localizedShortName] = enabled+ settings.updateExtra(key: ExtraKey.iCloudSyncROMPlatforms.rawValue, value: map)+#endif+ }++ static func shouldSyncROM(_ game: Game) -> Bool {+#if SIDE_LOAD+ return false+#else+ if game.gameType == .unknown || game.gameType == .notSupport { return false }+ if game.gameType == .symbian { return true }+ if game.isAzaharArticBase { return false }+ if let explicit = explicitROMSyncFlag(game) {+ return explicit+ }+ return isPlatformROMSyncEnabled(game.gameType)+#endif+ }++ static func explicitROMSyncFlag(_ game: Game) -> Bool? {+ if let explicit = game.getExtraBool(key: ExtraKey.iCloudSyncROM.rawValue) {+ return explicit+ }+ if let number = game.getExtra(key: ExtraKey.iCloudSyncROM.rawValue) as? NSNumber {+ return number.boolValue+ }+ return nil+ }++ static func setGameROMSyncEnabled(_ game: Game, enabled: Bool) {+ if let extras = game.extras,+ let data = Game.updateExtra(extras: extras, key: ExtraKey.iCloudSyncROM.rawValue, value: enabled) {+ game.extras = data+ } else {+ game.extras = [ExtraKey.iCloudSyncROM.rawValue: enabled].jsonData()+ }+ }++ static func applyDefaultROMSyncFlag(to game: Game) {+ setGameROMSyncEnabled(game, enabled: isPlatformROMSyncEnabled(game.gameType))+ }++ static func isROMExcluded(relativePath: String) -> Bool {+ romExclusionSnapshot().contains(relativePath)+ }++ /// Opens Realm on the calling thread and copies ROM paths into a value type.+ static func romExclusionSnapshot() -> FilesSyncROMExclusion {+ var snapshot = FilesSyncROMExclusion()+#if SIDE_LOAD+ return snapshot+#else+ let games = Database.realm.objects(Game.self).where { !$0.isDeleted }+ for game in games {+ guard !shouldSyncROM(game) else { continue }+ collectROMPaths(game: game, files: &snapshot.files, prefixes: &snapshot.prefixes)+ }+ Log.debug("[iCloud Sync] ROM exclusion snapshot games=\(games.count) files=\(snapshot.files.count) prefixes=\(snapshot.prefixes.count)")+ return snapshot+#endif+ }++ static func collectROMPaths(game: Game, files: inout Set<String>, prefixes: inout Set<String>) {+ for url in game.iCloudROMFileURLs {+ guard let relative = documentsRelativePath(from: url) else { continue }+ var isDirectory: ObjCBool = false+ if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), isDirectory.boolValue {+ prefixes.insert(relative)+ } else if url.hasDirectoryPath {+ prefixes.insert(relative)+ } else {+ files.insert(relative)+ }+ }+ }+}++extension Game {+ /// Local ROM files/directories that belong to this game for iCloud Drive include/exclude.+ var iCloudROMFileURLs: [URL] {+ if isAzaharArticBase || gameType == .symbian {+ return []+ }+ let url = romUrl+ guard url.isFileURL else { return [] }++ if gameType == ._3ds, fileExtension.lowercased() == "app", let range = url.path.range(of: "/content/") {+ let gamePath = String(url.path[...range.lowerBound])+ let updatePath = gamePath.replacingOccurrences(of: "/00040000/", with: "/0004000e/")+ let dlcPath = gamePath.replacingOccurrences(of: "/00040000/", with: "/0004008c/")+ return [gamePath, updatePath, dlcPath].map { URL(fileURLWithPath: $0, isDirectory: true) }+ }++ if isPSPPBPGame {+ return [URL(fileURLWithPath: url.deletingLastPathComponent().path, isDirectory: true)]+ }++ if isMultiFileGame {+ let parsed = Self.parseMultiFileROMURLs(playlist: url)+ if parsed.isEmpty {+ Log.debug("[iCloud Sync] Failed to parse multi-file ROM playlist, falling back to parent directory: \(url.lastPathComponent)")+ return [url.deletingLastPathComponent()]+ }+ return parsed+ }++ if gameType == .ps1, fileExtension.lowercased() == "bin" {+ let binUrl = URL(fileURLWithPath: R.Path.Data.appendingPathComponent(fileName))+ let cueUrl = binUrl.deletingPathExtension().appendingPathExtension("cue")+ var urls = [binUrl]+ if FileManager.default.fileExists(atPath: cueUrl.path) {+ urls.append(cueUrl)+ }+ return urls+ }++ return [url]+ }++ private static func parseMultiFileROMURLs(playlist: URL) -> [URL] {+ let directory = playlist.deletingLastPathComponent()+ guard let text = try? String(contentsOf: playlist, encoding: .utf8) else {+ return []+ }+ let ext = playlist.pathExtension.lowercased()+ var names: [String] = []+ if ext == "m3u" {+ names = text.components(separatedBy: .newlines).compactMap { line in+ let trimmed = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if trimmed.isEmpty || trimmed.hasPrefix("#") { return nil }+ return trimmed+ }+ } else if ext == "cue" {+ names = cueFileNames(in: text)+ } else if ext == "gdi" {+ names = gdiFileNames(in: text)+ }++ var urls: [URL] = [playlist]+ var seen = Set([playlist.lastPathComponent.lowercased()])+ for name in names {+ let fileURL = directory.appendingPathComponent(name)+ let key = fileURL.lastPathComponent.lowercased()+ if seen.insert(key).inserted {+ urls.append(fileURL)+ }+ if fileURL.pathExtension.lowercased() == "cue", fileURL != playlist,+ let nested = try? String(contentsOf: fileURL, encoding: .utf8) {+ for nestedName in cueFileNames(in: nested) {+ let nestedURL = fileURL.deletingLastPathComponent().appendingPathComponent(nestedName)+ let nestedKey = nestedURL.lastPathComponent.lowercased()+ if seen.insert(nestedKey).inserted {+ urls.append(nestedURL)+ }+ }+ }+ }+ return urls+ }++ private static func cueFileNames(in text: String) -> [String] {+ var names: [String] = []+ let quoted = try? NSRegularExpression(pattern: #"FILE\s+"([^"]+)""#, options: [.caseInsensitive])+ let unquoted = try? NSRegularExpression(pattern: #"FILE\s+(\S+)"#, options: [.caseInsensitive])+ let nsText = text as NSString+ let range = NSRange(location: 0, length: nsText.length)+ quoted?.matches(in: text, range: range).forEach { match in+ if match.numberOfRanges > 1 {+ names.append(nsText.substring(with: match.range(at: 1)))+ }+ }+ if names.isEmpty {+ unquoted?.matches(in: text, range: range).forEach { match in+ if match.numberOfRanges > 1 {+ names.append(nsText.substring(with: match.range(at: 1)))+ }+ }+ }+ return names+ }++ private static func gdiFileNames(in text: String) -> [String] {+ var names: [String] = []+ let quoted = try? NSRegularExpression(pattern: #""([^"]+)""#)+ let nsText = text as NSString+ quoted?.matches(in: text, range: NSRange(location: 0, length: nsText.length)).forEach { match in+ if match.numberOfRanges > 1 {+ names.append(nsText.substring(with: match.range(at: 1)))+ }+ }+ return names+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncRecord.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncRecord.swiftnew file mode 100644index 00000000..38696c30--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncRecord.swift@@ -0,0 +1,199 @@+//+// FilesSyncRecord.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/11.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation+import RealmSwift+import IceCream+import Device++/// CloudKit-synced intent for one Documents-relative file. The row stays when the+/// file is deleted (`intent == .deleted`); IceCream `isDeleted` is only for pruning.+enum FilesSyncIntentKind: Int, PersistableEnum {+ case present = 0+ case deleted = 1+ case excluded = 2++ var debugLabel: String {+ switch self {+ case .present: return "present"+ case .deleted: return "deleted"+ case .excluded: return "excluded"+ }+ }+}++extension FilesSyncRecord: CKRecordConvertible & CKRecordRecoverable {}++class FilesSyncRecord: Object, ObjectUpdatable {+ /// SHA-256 of `path` so the CloudKit record name stays ASCII and under 255 characters.+ @Persisted(primaryKey: true) var id: String+ @Persisted var path: String+ @Persisted var generation: Int+ @Persisted var size: Int64 = 0+ @Persisted var intent: FilesSyncIntentKind+ @Persisted var updatedAt: Date+ @Persisted var device: String = Device.version().rawValue+ /// IceCream tombstone for this row. Do not use for file deletion.+ @Persisted var isDeleted: Bool = false+ @Persisted var extras: Data?++ static func objectId(forPath path: String) -> String {+ path.sha256()+ }++ func getExtra(key: String) -> Any? {+ if let extras {+ return Self.getExtra(extras: extras, key: key)+ }+ return nil+ }++ func updateExtra(key: String, value: Any?) {+ if let extras, let data = Self.updateExtra(extras: extras, key: key, value: value) {+ Self.change { realm in+ self.extras = data+ }+ } else if let data = [key: value].jsonData() {+ Self.change { realm in+ self.extras = data+ }+ }+ }+}++struct FilesSyncIntentSnapshot {+ var path: String+ var generation: Int+ var size: Int64+ var intent: FilesSyncIntentKind+ var updatedAt: Date+}++enum FilesSyncIntentStore {+ private static let pruneAfter: TimeInterval = 90 * 24 * 60 * 60++ static func snapshot(relativePath: String) -> FilesSyncIntentSnapshot? {+ let realm = Database.realm+ let id = FilesSyncRecord.objectId(forPath: relativePath)+ guard let record = realm.object(ofType: FilesSyncRecord.self, forPrimaryKey: id),+ !record.isDeleted else { return nil }+ return snapshot(record)+ }++ static func allActive() -> [String: FilesSyncIntentSnapshot] {+ let records = Database.realm.objects(FilesSyncRecord.self).where { !$0.isDeleted }+ var result: [String: FilesSyncIntentSnapshot] = [:]+ result.reserveCapacity(records.count)+ for record in records {+ result[record.path] = snapshot(record)+ }+ return result+ }++ static func paths(matchingPrefix prefix: String) -> [String] {+ let records = Database.realm.objects(FilesSyncRecord.self).where { !$0.isDeleted }+ return records.compactMap { record in+ if record.path == prefix || record.path.hasPrefix(prefix + "/") {+ return record.path+ }+ return nil+ }+ }++ static func hasPresentIntent(relativePath: String, isDirectory: Bool) -> Bool {+ if let item = snapshot(relativePath: relativePath), item.intent == .present {+ return true+ }+ guard isDirectory else { return false }+ return allActive().contains { path, item in+ item.intent == .present && (path == relativePath || path.hasPrefix(relativePath + "/"))+ }+ }++ /// Creates or bumps the row after a successful upload.+ @discardableResult+ static func markPresent(relativePath: String, size: Int64) -> Int {+ write(relativePath: relativePath, intent: .present, size: size, bump: true)+ }++ /// Writes a delete intent before removing the Drive copy.+ @discardableResult+ static func markDeleted(relativePath: String) -> Int {+ write(relativePath: relativePath, intent: .deleted, size: 0, bump: true)+ }++ @discardableResult+ static func markExcluded(relativePath: String) -> Int {+ write(relativePath: relativePath, intent: .excluded, size: 0, bump: true)+ }++ static func pruneExpiredDeleted() {+ let cutoff = Date().addingTimeInterval(-pruneAfter)+ let realm = Database.realm+ let expired = realm.objects(FilesSyncRecord.self).where {+ !$0.isDeleted && $0.intent == .deleted && $0.updatedAt < cutoff+ }+ guard !expired.isEmpty else { return }+ let count = expired.count+ try? realm.write {+ for record in expired {+ record.isDeleted = true+ }+ }+ Log.debug("[iCloud Sync] pruned \(count) expired delete intents")+ }++ private static func write(relativePath: String, intent: FilesSyncIntentKind, size: Int64, bump: Bool) -> Int {+ let id = FilesSyncRecord.objectId(forPath: relativePath)+ let realm = Database.realm+ var generation = 1+ try? realm.write {+ if let existing = realm.object(ofType: FilesSyncRecord.self, forPrimaryKey: id), !existing.isDeleted {+ generation = bump ? existing.generation + 1 : max(existing.generation, 1)+ existing.generation = generation+ existing.intent = intent+ existing.size = size+ existing.updatedAt = Date()+ existing.device = Device.version().rawValue+ existing.path = relativePath+ } else {+ let record = FilesSyncRecord()+ record.id = id+ record.path = relativePath+ record.generation = 1+ record.size = size+ record.intent = intent+ record.updatedAt = Date()+ record.device = Device.version().rawValue+ record.isDeleted = false+ realm.add(record, update: .modified)+ generation = 1+ }+ }+ Log.debug("[iCloud Sync] intent \(intentLabel(intent)) gen=\(generation) size=\(size) \(relativePath)")+ return generation+ }++ private static func snapshot(_ record: FilesSyncRecord) -> FilesSyncIntentSnapshot {+ FilesSyncIntentSnapshot(+ path: record.path,+ generation: record.generation,+ size: record.size,+ intent: record.intent,+ updatedAt: record.updatedAt+ )+ }++ private static func intentLabel(_ intent: FilesSyncIntentKind) -> String {+ switch intent {+ case .present: return "present"+ case .deleted: return "deleted"+ case .excluded: return "excluded"+ }+ }+}diff --git a/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncWatchers.swift b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncWatchers.swiftnew file mode 100644index 00000000..a6192295--- /dev/null+++ b/ManicEmu/ManicEmu/Sources/Tools/Sync/FilesSyncWatchers.swift@@ -0,0 +1,126 @@+//+// FilesSyncWatchers.swift+// ManicEmu+//+// Created by Daiuno on 2026/9/10.+// Copyright © 2026 Manic EMU. All rights reserved.+//++import Foundation++struct FilesSyncCloudInventory {+ var files: [String: FilesSyncFingerprint] = [:]+ var uploading: Set<String> = []+ var downloading: Set<String> = []+ var notDownloaded: Set<String> = []+ var bytesTransferred: Int64 = 0+ var bytesTotal: Int64 = 0+}++final class FilesSyncWatchers: NSObject {+ private let metadataQuery = NSMetadataQuery()+ private var tokens: [NSObjectProtocol] = []+ private var isRunning = false+ var onCloudInventory: ((FilesSyncCloudInventory) -> Void)?++ func start() {+ guard !isRunning else { return }+ guard FileManager.default.ubiquityIdentityToken != nil else {+ Log.debug("[iCloud Sync] No iCloud account, skip metadata query")+ return+ }+ isRunning = true+ Log.debug("[iCloud Sync] metadata query start main=\(Thread.isMainThread)")+ DispatchQueue.main.async { [weak self] in+ self?.configureIfNeeded()+ self?.metadataQuery.enableUpdates()+ self?.metadataQuery.start()+ }+ }++ func stop() {+ isRunning = false+ Log.debug("[iCloud Sync] metadata query stop")+ DispatchQueue.main.async { [weak self] in+ self?.metadataQuery.stop()+ self?.metadataQuery.disableUpdates()+ }+ }++ deinit {+ tokens.forEach { NotificationCenter.default.removeObserver($0) }+ }++ private func configureIfNeeded() {+ guard tokens.isEmpty else { return }+ metadataQuery.searchScopes = [NSMetadataQueryUbiquitousDocumentsScope]+ metadataQuery.predicate = NSPredicate(value: true)+ metadataQuery.notificationBatchingInterval = 0.5++ let center = NotificationCenter.default+ let finish = center.addObserver(forName: .NSMetadataQueryDidFinishGathering, object: metadataQuery, queue: .main) { [weak self] _ in+ self?.metadataQuery.disableUpdates()+ self?.emitInventory()+ self?.metadataQuery.enableUpdates()+ }+ let update = center.addObserver(forName: .NSMetadataQueryDidUpdate, object: metadataQuery, queue: .main) { [weak self] _ in+ self?.emitInventory()+ }+ tokens = [finish, update]+ }++ private func emitInventory() {+ guard isRunning else { return }+ let startedAt = Date()+ var inventory = FilesSyncCloudInventory()+ for case let item as NSMetadataItem in metadataQuery.results {+ guard let fileURL = item.value(forAttribute: NSMetadataItemURLKey) as? URL,+ let relative = FilesSyncPolicy.documentsRelativePath(from: fileURL) else { continue }+ if FilesSyncPolicy.shouldNeverSync(relativePath: relative) { continue }+ if fileURL.path.hasSuffix("/") { continue }+ if let contentType = item.value(forAttribute: NSMetadataItemContentTypeKey) as? String,+ contentType == "public.directory" || contentType == "public.folder" {+ continue+ }++ let size = (item.value(forAttribute: NSMetadataItemFSSizeKey) as? NSNumber)?.int64Value ?? 0+ let mtime = (item.value(forAttribute: NSMetadataItemFSContentChangeDateKey) as? Date)?.timeIntervalSince1970 ?? 0+ inventory.files[relative] = FilesSyncFingerprint(size: size, mtime: mtime, hash: nil)++ let status = item.value(forAttribute: NSMetadataUbiquitousItemDownloadingStatusKey) as? String+ if status == NSMetadataUbiquitousItemDownloadingStatusNotDownloaded {+ inventory.notDownloaded.insert(relative)+ }++ let uploadPercent = (item.value(forAttribute: NSMetadataUbiquitousItemPercentUploadedKey) as? NSNumber)?.doubleValue+ let downloadPercent = (item.value(forAttribute: NSMetadataUbiquitousItemPercentDownloadedKey) as? NSNumber)?.doubleValue+ if (item.value(forAttribute: NSMetadataUbiquitousItemIsUploadingKey) as? Bool) == true {+ inventory.uploading.insert(relative)+ } else if let percent = uploadPercent, percent > 0, percent < 100 {+ inventory.uploading.insert(relative)+ }+ if (item.value(forAttribute: NSMetadataUbiquitousItemIsDownloadingKey) as? Bool) == true {+ inventory.downloading.insert(relative)+ } else if let percent = downloadPercent, percent > 0, percent < 100 {+ inventory.downloading.insert(relative)+ }++ if size > 0 {+ inventory.bytesTotal += size+ let percent: Double+ if inventory.uploading.contains(relative), let uploadPercent {+ percent = uploadPercent+ } else if inventory.downloading.contains(relative), let downloadPercent {+ percent = downloadPercent+ } else if status == NSMetadataUbiquitousItemDownloadingStatusNotDownloaded {+ percent = 0+ } else {+ percent = 100+ }+ inventory.bytesTransferred += Int64(Double(size) * min(max(percent, 0), 100) / 100)+ }+ }+ Log.debug("[iCloud Sync] metadata emit files=\(inventory.files.count) uploading=\(inventory.uploading.count) downloading=\(inventory.downloading.count) notDownloaded=\(inventory.notDownloaded.count) elapsed=\(String(format: "%.2f", Date().timeIntervalSince(startedAt)))s main=\(Thread.isMainThread)")+ onCloudInventory?(inventory)+ }+}