diff --git a/Nasa.xcodeproj/project.pbxproj b/Nasa.xcodeproj/project.pbxproj new file mode 100644 index 0000000..7d5e298 --- /dev/null +++ b/Nasa.xcodeproj/project.pbxproj @@ -0,0 +1,873 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + objects = { + +/* Begin PBXBuildFile section */ + 0B1A18B337E24B517456213D /* Pods_Nasa_NasaUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = A3BB08599CF1B0E5388EC2CC /* Pods_Nasa_NasaUITests.framework */; }; + C824FE6DC2F7D8B4C23197C6 /* Pods_Nasa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4BFACCEACC6A106AA3045EC7 /* Pods_Nasa.framework */; }; + FD87ECB7274A705800EFBF0C /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECB6274A705800EFBF0C /* AppDelegate.swift */; }; + FD87ECC3274A705B00EFBF0C /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = FD87ECC2274A705B00EFBF0C /* Assets.xcassets */; }; + FD87ECC6274A705B00EFBF0C /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = FD87ECC4274A705B00EFBF0C /* LaunchScreen.storyboard */; }; + FD87ECD1274A705B00EFBF0C /* NasaTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECD0274A705B00EFBF0C /* NasaTests.swift */; }; + FD87ECDB274A705C00EFBF0C /* NasaUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECDA274A705C00EFBF0C /* NasaUITests.swift */; }; + FD87ECDD274A705C00EFBF0C /* NasaUITestsLaunchTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECDC274A705C00EFBF0C /* NasaUITestsLaunchTests.swift */; }; + FD87ECEA274A95D900EFBF0C /* ImagesCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECE9274A95D900EFBF0C /* ImagesCell.swift */; }; + FD87ECEC274A964300EFBF0C /* ImageCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD87ECEB274A964300EFBF0C /* ImageCell.xib */; }; + FD87ECEE274A9A2900EFBF0C /* ImagesListViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECED274A9A2900EFBF0C /* ImagesListViewController.swift */; }; + FD87ECF0274A9A4600EFBF0C /* ImagesListViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD87ECEF274A9A4600EFBF0C /* ImagesListViewController.xib */; }; + FD87ECF4274A9AE700EFBF0C /* ImagesListViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECF3274A9AE700EFBF0C /* ImagesListViewModel.swift */; }; + FD87ECF6274A9B2100EFBF0C /* BaseViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECF5274A9B2100EFBF0C /* BaseViewModel.swift */; }; + FD87ECF8274A9B2C00EFBF0C /* BaseViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECF7274A9B2C00EFBF0C /* BaseViewController.swift */; }; + FD87ECFA274A9C4600EFBF0C /* ControllerIds.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECF9274A9C4600EFBF0C /* ControllerIds.swift */; }; + FD87ECFC274A9CD000EFBF0C /* ImageDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECFB274A9CD000EFBF0C /* ImageDetailViewController.swift */; }; + FD87ED00274A9D0400EFBF0C /* ImageDetailViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ECFF274A9D0400EFBF0C /* ImageDetailViewModel.swift */; }; + FD87ED02274A9D3400EFBF0C /* ImageDetailViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = FD87ED01274A9D3400EFBF0C /* ImageDetailViewController.xib */; }; + FD87ED05274AA55900EFBF0C /* APIClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED04274AA55900EFBF0C /* APIClient.swift */; }; + FD87ED08274AA59800EFBF0C /* NasaErrors.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED07274AA59800EFBF0C /* NasaErrors.swift */; }; + FD87ED0C274AA61A00EFBF0C /* NasaResponseModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED0B274AA61A00EFBF0C /* NasaResponseModel.swift */; }; + FD87ED0E274AA64C00EFBF0C /* NasaUIModels.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED0D274AA64C00EFBF0C /* NasaUIModels.swift */; }; + FD87ED10274AAD8400EFBF0C /* APIEndpoint.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED0F274AAD8400EFBF0C /* APIEndpoint.swift */; }; + FD87ED12274AAD9900EFBF0C /* APIMethod.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED11274AAD9900EFBF0C /* APIMethod.swift */; }; + FD87ED14274AADA600EFBF0C /* RemoteDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED13274AADA600EFBF0C /* RemoteDataSource.swift */; }; + FD87ED16274AADBB00EFBF0C /* URLRequest+Nasa.swift in Sources */ = {isa = PBXBuildFile; fileRef = FD87ED15274AADBB00EFBF0C /* URLRequest+Nasa.swift */; }; + FDC37A2CD0F98B9F4A264947 /* Pods_NasaTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AB39B745A907CC601D420558 /* Pods_NasaTests.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + FD87ECCD274A705B00EFBF0C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FD87ECAB274A705800EFBF0C /* Project object */; + proxyType = 1; + remoteGlobalIDString = FD87ECB2274A705800EFBF0C; + remoteInfo = Nasa; + }; + FD87ECD7274A705C00EFBF0C /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = FD87ECAB274A705800EFBF0C /* Project object */; + proxyType = 1; + remoteGlobalIDString = FD87ECB2274A705800EFBF0C; + remoteInfo = Nasa; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 2392C0E92E40470D966DB1BF /* Pods-NasaTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NasaTests.release.xcconfig"; path = "Target Support Files/Pods-NasaTests/Pods-NasaTests.release.xcconfig"; sourceTree = ""; }; + 4BFACCEACC6A106AA3045EC7 /* Pods_Nasa.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Nasa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 61124340F09366D74B14459A /* Pods-Nasa-NasaUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Nasa-NasaUITests.release.xcconfig"; path = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests.release.xcconfig"; sourceTree = ""; }; + 7733EF76FB3026737A209208 /* Pods-Nasa-NasaUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Nasa-NasaUITests.debug.xcconfig"; path = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests.debug.xcconfig"; sourceTree = ""; }; + 95144BEB1A614BC4ED845F39 /* Pods-NasaTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-NasaTests.debug.xcconfig"; path = "Target Support Files/Pods-NasaTests/Pods-NasaTests.debug.xcconfig"; sourceTree = ""; }; + A3BB08599CF1B0E5388EC2CC /* Pods_Nasa_NasaUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Nasa_NasaUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AB39B745A907CC601D420558 /* Pods_NasaTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_NasaTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AB8A3A81D547DA7B2F814D7E /* Pods-Nasa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Nasa.debug.xcconfig"; path = "Target Support Files/Pods-Nasa/Pods-Nasa.debug.xcconfig"; sourceTree = ""; }; + F13D26036D15EEBA0E09BCCE /* Pods-Nasa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Nasa.release.xcconfig"; path = "Target Support Files/Pods-Nasa/Pods-Nasa.release.xcconfig"; sourceTree = ""; }; + FD87ECB3274A705800EFBF0C /* Nasa.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Nasa.app; sourceTree = BUILT_PRODUCTS_DIR; }; + FD87ECB6274A705800EFBF0C /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + FD87ECC2274A705B00EFBF0C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + FD87ECC5274A705B00EFBF0C /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + FD87ECC7274A705B00EFBF0C /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + FD87ECCC274A705B00EFBF0C /* NasaTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NasaTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FD87ECD0274A705B00EFBF0C /* NasaTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaTests.swift; sourceTree = ""; }; + FD87ECD6274A705C00EFBF0C /* NasaUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = NasaUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + FD87ECDA274A705C00EFBF0C /* NasaUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaUITests.swift; sourceTree = ""; }; + FD87ECDC274A705C00EFBF0C /* NasaUITestsLaunchTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaUITestsLaunchTests.swift; sourceTree = ""; }; + FD87ECE9274A95D900EFBF0C /* ImagesCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagesCell.swift; sourceTree = ""; }; + FD87ECEB274A964300EFBF0C /* ImageCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ImageCell.xib; sourceTree = ""; }; + FD87ECED274A9A2900EFBF0C /* ImagesListViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagesListViewController.swift; sourceTree = ""; }; + FD87ECEF274A9A4600EFBF0C /* ImagesListViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ImagesListViewController.xib; sourceTree = ""; }; + FD87ECF3274A9AE700EFBF0C /* ImagesListViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImagesListViewModel.swift; sourceTree = ""; }; + FD87ECF5274A9B2100EFBF0C /* BaseViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseViewModel.swift; sourceTree = ""; }; + FD87ECF7274A9B2C00EFBF0C /* BaseViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BaseViewController.swift; sourceTree = ""; }; + FD87ECF9274A9C4600EFBF0C /* ControllerIds.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ControllerIds.swift; sourceTree = ""; }; + FD87ECFB274A9CD000EFBF0C /* ImageDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDetailViewController.swift; sourceTree = ""; }; + FD87ECFF274A9D0400EFBF0C /* ImageDetailViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ImageDetailViewModel.swift; sourceTree = ""; }; + FD87ED01274A9D3400EFBF0C /* ImageDetailViewController.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = ImageDetailViewController.xib; sourceTree = ""; }; + FD87ED04274AA55900EFBF0C /* APIClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIClient.swift; sourceTree = ""; }; + FD87ED07274AA59800EFBF0C /* NasaErrors.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaErrors.swift; sourceTree = ""; }; + FD87ED0B274AA61A00EFBF0C /* NasaResponseModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaResponseModel.swift; sourceTree = ""; }; + FD87ED0D274AA64C00EFBF0C /* NasaUIModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NasaUIModels.swift; sourceTree = ""; }; + FD87ED0F274AAD8400EFBF0C /* APIEndpoint.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIEndpoint.swift; sourceTree = ""; }; + FD87ED11274AAD9900EFBF0C /* APIMethod.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = APIMethod.swift; sourceTree = ""; }; + FD87ED13274AADA600EFBF0C /* RemoteDataSource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RemoteDataSource.swift; sourceTree = ""; }; + FD87ED15274AADBB00EFBF0C /* URLRequest+Nasa.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "URLRequest+Nasa.swift"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + FD87ECB0274A705800EFBF0C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C824FE6DC2F7D8B4C23197C6 /* Pods_Nasa.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECC9274A705B00EFBF0C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + FDC37A2CD0F98B9F4A264947 /* Pods_NasaTests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECD3274A705C00EFBF0C /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0B1A18B337E24B517456213D /* Pods_Nasa_NasaUITests.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 1DFCA58A6E31EBF1B783E380 /* Pods */ = { + isa = PBXGroup; + children = ( + AB8A3A81D547DA7B2F814D7E /* Pods-Nasa.debug.xcconfig */, + F13D26036D15EEBA0E09BCCE /* Pods-Nasa.release.xcconfig */, + 7733EF76FB3026737A209208 /* Pods-Nasa-NasaUITests.debug.xcconfig */, + 61124340F09366D74B14459A /* Pods-Nasa-NasaUITests.release.xcconfig */, + 95144BEB1A614BC4ED845F39 /* Pods-NasaTests.debug.xcconfig */, + 2392C0E92E40470D966DB1BF /* Pods-NasaTests.release.xcconfig */, + ); + path = Pods; + sourceTree = ""; + }; + 4A5D102889481FA4F402424C /* Frameworks */ = { + isa = PBXGroup; + children = ( + 4BFACCEACC6A106AA3045EC7 /* Pods_Nasa.framework */, + A3BB08599CF1B0E5388EC2CC /* Pods_Nasa_NasaUITests.framework */, + AB39B745A907CC601D420558 /* Pods_NasaTests.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + FD87ECAA274A705800EFBF0C = { + isa = PBXGroup; + children = ( + FD87ECB5274A705800EFBF0C /* Nasa */, + FD87ECCF274A705B00EFBF0C /* NasaTests */, + FD87ECD9274A705C00EFBF0C /* NasaUITests */, + FD87ECB4274A705800EFBF0C /* Products */, + 1DFCA58A6E31EBF1B783E380 /* Pods */, + 4A5D102889481FA4F402424C /* Frameworks */, + ); + sourceTree = ""; + }; + FD87ECB4274A705800EFBF0C /* Products */ = { + isa = PBXGroup; + children = ( + FD87ECB3274A705800EFBF0C /* Nasa.app */, + FD87ECCC274A705B00EFBF0C /* NasaTests.xctest */, + FD87ECD6274A705C00EFBF0C /* NasaUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + FD87ECB5274A705800EFBF0C /* Nasa */ = { + isa = PBXGroup; + children = ( + FD87ED06274AA58300EFBF0C /* Models */, + FD87ED03274AA1B800EFBF0C /* Networking */, + FD87ECFD274A9CE100EFBF0C /* ImageDetail */, + FD87ECF1274A9A8300EFBF0C /* ImagesList */, + FD87ECB6274A705800EFBF0C /* AppDelegate.swift */, + FD87ECC2274A705B00EFBF0C /* Assets.xcassets */, + FD87ECC4274A705B00EFBF0C /* LaunchScreen.storyboard */, + FD87ECC7274A705B00EFBF0C /* Info.plist */, + FD87ECF5274A9B2100EFBF0C /* BaseViewModel.swift */, + FD87ECF7274A9B2C00EFBF0C /* BaseViewController.swift */, + FD87ECF9274A9C4600EFBF0C /* ControllerIds.swift */, + ); + path = Nasa; + sourceTree = ""; + }; + FD87ECCF274A705B00EFBF0C /* NasaTests */ = { + isa = PBXGroup; + children = ( + FD87ECD0274A705B00EFBF0C /* NasaTests.swift */, + ); + path = NasaTests; + sourceTree = ""; + }; + FD87ECD9274A705C00EFBF0C /* NasaUITests */ = { + isa = PBXGroup; + children = ( + FD87ECDA274A705C00EFBF0C /* NasaUITests.swift */, + FD87ECDC274A705C00EFBF0C /* NasaUITestsLaunchTests.swift */, + ); + path = NasaUITests; + sourceTree = ""; + }; + FD87ECF1274A9A8300EFBF0C /* ImagesList */ = { + isa = PBXGroup; + children = ( + FD87ECF2274A9A8D00EFBF0C /* Views */, + FD87ECED274A9A2900EFBF0C /* ImagesListViewController.swift */, + FD87ECEF274A9A4600EFBF0C /* ImagesListViewController.xib */, + FD87ECF3274A9AE700EFBF0C /* ImagesListViewModel.swift */, + ); + path = ImagesList; + sourceTree = ""; + }; + FD87ECF2274A9A8D00EFBF0C /* Views */ = { + isa = PBXGroup; + children = ( + FD87ECE9274A95D900EFBF0C /* ImagesCell.swift */, + FD87ECEB274A964300EFBF0C /* ImageCell.xib */, + ); + path = Views; + sourceTree = ""; + }; + FD87ECFD274A9CE100EFBF0C /* ImageDetail */ = { + isa = PBXGroup; + children = ( + FD87ECFF274A9D0400EFBF0C /* ImageDetailViewModel.swift */, + FD87ECFB274A9CD000EFBF0C /* ImageDetailViewController.swift */, + FD87ED01274A9D3400EFBF0C /* ImageDetailViewController.xib */, + ); + path = ImageDetail; + sourceTree = ""; + }; + FD87ED03274AA1B800EFBF0C /* Networking */ = { + isa = PBXGroup; + children = ( + FD87ED04274AA55900EFBF0C /* APIClient.swift */, + FD87ED0F274AAD8400EFBF0C /* APIEndpoint.swift */, + FD87ED11274AAD9900EFBF0C /* APIMethod.swift */, + FD87ED13274AADA600EFBF0C /* RemoteDataSource.swift */, + FD87ED15274AADBB00EFBF0C /* URLRequest+Nasa.swift */, + ); + path = "Networking "; + sourceTree = ""; + }; + FD87ED06274AA58300EFBF0C /* Models */ = { + isa = PBXGroup; + children = ( + FD87ED07274AA59800EFBF0C /* NasaErrors.swift */, + FD87ED0B274AA61A00EFBF0C /* NasaResponseModel.swift */, + FD87ED0D274AA64C00EFBF0C /* NasaUIModels.swift */, + ); + path = Models; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + FD87ECB2274A705800EFBF0C /* Nasa */ = { + isa = PBXNativeTarget; + buildConfigurationList = FD87ECE0274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "Nasa" */; + buildPhases = ( + 08DF0F63654831A77ABB5501 /* [CP] Check Pods Manifest.lock */, + FD87ECAF274A705800EFBF0C /* Sources */, + FD87ECB0274A705800EFBF0C /* Frameworks */, + FD87ECB1274A705800EFBF0C /* Resources */, + 21402FC7E9C2804BDFC65D7B /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Nasa; + productName = Nasa; + productReference = FD87ECB3274A705800EFBF0C /* Nasa.app */; + productType = "com.apple.product-type.application"; + }; + FD87ECCB274A705B00EFBF0C /* NasaTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FD87ECE3274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "NasaTests" */; + buildPhases = ( + 479B8B58B75EE93D781B5456 /* [CP] Check Pods Manifest.lock */, + FD87ECC8274A705B00EFBF0C /* Sources */, + FD87ECC9274A705B00EFBF0C /* Frameworks */, + FD87ECCA274A705B00EFBF0C /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + FD87ECCE274A705B00EFBF0C /* PBXTargetDependency */, + ); + name = NasaTests; + productName = NasaTests; + productReference = FD87ECCC274A705B00EFBF0C /* NasaTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + FD87ECD5274A705C00EFBF0C /* NasaUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = FD87ECE6274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "NasaUITests" */; + buildPhases = ( + BE51B18447E6318F9E6ED32D /* [CP] Check Pods Manifest.lock */, + FD87ECD2274A705C00EFBF0C /* Sources */, + FD87ECD3274A705C00EFBF0C /* Frameworks */, + FD87ECD4274A705C00EFBF0C /* Resources */, + 08238C2FEB4CB9641A1C88A8 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + FD87ECD8274A705C00EFBF0C /* PBXTargetDependency */, + ); + name = NasaUITests; + productName = NasaUITests; + productReference = FD87ECD6274A705C00EFBF0C /* NasaUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + FD87ECAB274A705800EFBF0C /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 1300; + LastUpgradeCheck = 1300; + TargetAttributes = { + FD87ECB2274A705800EFBF0C = { + CreatedOnToolsVersion = 13.0; + }; + FD87ECCB274A705B00EFBF0C = { + CreatedOnToolsVersion = 13.0; + TestTargetID = FD87ECB2274A705800EFBF0C; + }; + FD87ECD5274A705C00EFBF0C = { + CreatedOnToolsVersion = 13.0; + TestTargetID = FD87ECB2274A705800EFBF0C; + }; + }; + }; + buildConfigurationList = FD87ECAE274A705800EFBF0C /* Build configuration list for PBXProject "Nasa" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = FD87ECAA274A705800EFBF0C; + productRefGroup = FD87ECB4274A705800EFBF0C /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + FD87ECB2274A705800EFBF0C /* Nasa */, + FD87ECCB274A705B00EFBF0C /* NasaTests */, + FD87ECD5274A705C00EFBF0C /* NasaUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + FD87ECB1274A705800EFBF0C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FD87ED02274A9D3400EFBF0C /* ImageDetailViewController.xib in Resources */, + FD87ECF0274A9A4600EFBF0C /* ImagesListViewController.xib in Resources */, + FD87ECC6274A705B00EFBF0C /* LaunchScreen.storyboard in Resources */, + FD87ECEC274A964300EFBF0C /* ImageCell.xib in Resources */, + FD87ECC3274A705B00EFBF0C /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECCA274A705B00EFBF0C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECD4274A705C00EFBF0C /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 08238C2FEB4CB9641A1C88A8 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 08DF0F63654831A77ABB5501 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Nasa-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 21402FC7E9C2804BDFC65D7B /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Nasa/Pods-Nasa-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Nasa/Pods-Nasa-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Nasa/Pods-Nasa-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 479B8B58B75EE93D781B5456 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-NasaTests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + BE51B18447E6318F9E6ED32D /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Nasa-NasaUITests-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + FD87ECAF274A705800EFBF0C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FD87ED00274A9D0400EFBF0C /* ImageDetailViewModel.swift in Sources */, + FD87ED16274AADBB00EFBF0C /* URLRequest+Nasa.swift in Sources */, + FD87ECEE274A9A2900EFBF0C /* ImagesListViewController.swift in Sources */, + FD87ED08274AA59800EFBF0C /* NasaErrors.swift in Sources */, + FD87ECF6274A9B2100EFBF0C /* BaseViewModel.swift in Sources */, + FD87ED05274AA55900EFBF0C /* APIClient.swift in Sources */, + FD87ECFA274A9C4600EFBF0C /* ControllerIds.swift in Sources */, + FD87ECEA274A95D900EFBF0C /* ImagesCell.swift in Sources */, + FD87ED10274AAD8400EFBF0C /* APIEndpoint.swift in Sources */, + FD87ED14274AADA600EFBF0C /* RemoteDataSource.swift in Sources */, + FD87ECF4274A9AE700EFBF0C /* ImagesListViewModel.swift in Sources */, + FD87ECB7274A705800EFBF0C /* AppDelegate.swift in Sources */, + FD87ED0C274AA61A00EFBF0C /* NasaResponseModel.swift in Sources */, + FD87ED12274AAD9900EFBF0C /* APIMethod.swift in Sources */, + FD87ECF8274A9B2C00EFBF0C /* BaseViewController.swift in Sources */, + FD87ED0E274AA64C00EFBF0C /* NasaUIModels.swift in Sources */, + FD87ECFC274A9CD000EFBF0C /* ImageDetailViewController.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECC8274A705B00EFBF0C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FD87ECD1274A705B00EFBF0C /* NasaTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + FD87ECD2274A705C00EFBF0C /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FD87ECDB274A705C00EFBF0C /* NasaUITests.swift in Sources */, + FD87ECDD274A705C00EFBF0C /* NasaUITestsLaunchTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + FD87ECCE274A705B00EFBF0C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FD87ECB2274A705800EFBF0C /* Nasa */; + targetProxy = FD87ECCD274A705B00EFBF0C /* PBXContainerItemProxy */; + }; + FD87ECD8274A705C00EFBF0C /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = FD87ECB2274A705800EFBF0C /* Nasa */; + targetProxy = FD87ECD7274A705C00EFBF0C /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + FD87ECC4274A705B00EFBF0C /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + FD87ECC5274A705B00EFBF0C /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + FD87ECDE274A705C00EFBF0C /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + FD87ECDF274A705C00EFBF0C /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++17"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + FD87ECE1274A705C00EFBF0C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = AB8A3A81D547DA7B2F814D7E /* Pods-Nasa.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Nasa/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.Nasa; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + FD87ECE2274A705C00EFBF0C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F13D26036D15EEBA0E09BCCE /* Pods-Nasa.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = Nasa/Info.plist; + INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; + INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen; + INFOPLIST_KEY_UIMainStoryboardFile = Main; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.Nasa; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; + FD87ECE4274A705C00EFBF0C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 95144BEB1A614BC4ED845F39 /* Pods-NasaTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.NasaTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Nasa.app/Nasa"; + }; + name = Debug; + }; + FD87ECE5274A705C00EFBF0C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 2392C0E92E40470D966DB1BF /* Pods-NasaTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.NasaTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Nasa.app/Nasa"; + }; + name = Release; + }; + FD87ECE7274A705C00EFBF0C /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7733EF76FB3026737A209208 /* Pods-Nasa-NasaUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.NasaUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Nasa; + }; + name = Debug; + }; + FD87ECE8274A705C00EFBF0C /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 61124340F09366D74B14459A /* Pods-Nasa-NasaUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = nnn.NasaUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_TARGET_NAME = Nasa; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + FD87ECAE274A705800EFBF0C /* Build configuration list for PBXProject "Nasa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FD87ECDE274A705C00EFBF0C /* Debug */, + FD87ECDF274A705C00EFBF0C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FD87ECE0274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "Nasa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FD87ECE1274A705C00EFBF0C /* Debug */, + FD87ECE2274A705C00EFBF0C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FD87ECE3274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "NasaTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FD87ECE4274A705C00EFBF0C /* Debug */, + FD87ECE5274A705C00EFBF0C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + FD87ECE6274A705C00EFBF0C /* Build configuration list for PBXNativeTarget "NasaUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + FD87ECE7274A705C00EFBF0C /* Debug */, + FD87ECE8274A705C00EFBF0C /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = FD87ECAB274A705800EFBF0C /* Project object */; +} diff --git a/Nasa.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Nasa.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/Nasa.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Nasa.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Nasa.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/Nasa.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Nasa.xcodeproj/project.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate b/Nasa.xcodeproj/project.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..dba42a3 Binary files /dev/null and b/Nasa.xcodeproj/project.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Nasa.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist b/Nasa.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..0b88f8f --- /dev/null +++ b/Nasa.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,14 @@ + + + + + SchemeUserState + + Nasa.xcscheme_^#shared#^_ + + orderHint + 7 + + + + diff --git a/Nasa.xcworkspace/contents.xcworkspacedata b/Nasa.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..36c4f08 --- /dev/null +++ b/Nasa.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/Nasa.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/Nasa.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/Nasa.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/Nasa.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate b/Nasa.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000..87406d5 Binary files /dev/null and b/Nasa.xcworkspace/xcuserdata/Angie.xcuserdatad/UserInterfaceState.xcuserstate differ diff --git a/Nasa/AppDelegate.swift b/Nasa/AppDelegate.swift new file mode 100644 index 0000000..200110f --- /dev/null +++ b/Nasa/AppDelegate.swift @@ -0,0 +1,81 @@ +// +// AppDelegate.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import UIKit +import CoreData + +@main +class AppDelegate: UIResponder, UIApplicationDelegate { + + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + // MARK: UISceneSession Lifecycle + + func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration { + // Called when a new scene session is being created. + // Use this method to select a configuration to create the new scene with. + return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) + } + + func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set) { + // Called when the user discards a scene session. + // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions. + // Use this method to release any resources that were specific to the discarded scenes, as they will not return. + } + + // MARK: - Core Data stack + + lazy var persistentContainer: NSPersistentContainer = { + /* + The persistent container for the application. This implementation + creates and returns a container, having loaded the store for the + application to it. This property is optional since there are legitimate + error conditions that could cause the creation of the store to fail. + */ + let container = NSPersistentContainer(name: "Nasa") + container.loadPersistentStores(completionHandler: { (storeDescription, error) in + if let error = error as NSError? { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + + /* + Typical reasons for an error here include: + * The parent directory does not exist, cannot be created, or disallows writing. + * The persistent store is not accessible, due to permissions or data protection when the device is locked. + * The device is out of space. + * The store could not be migrated to the current model version. + Check the error message to determine what the actual problem was. + */ + fatalError("Unresolved error \(error), \(error.userInfo)") + } + }) + return container + }() + + // MARK: - Core Data Saving support + + func saveContext () { + let context = persistentContainer.viewContext + if context.hasChanges { + do { + try context.save() + } catch { + // Replace this implementation with code to handle the error appropriately. + // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. + let nserror = error as NSError + fatalError("Unresolved error \(nserror), \(nserror.userInfo)") + } + } + } + +} + diff --git a/Nasa/Assets.xcassets/AccentColor.colorset/Contents.json b/Nasa/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..eb87897 --- /dev/null +++ b/Nasa/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Nasa/Assets.xcassets/AppIcon.appiconset/Contents.json b/Nasa/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..9221b9b --- /dev/null +++ b/Nasa/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,98 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Nasa/Assets.xcassets/Contents.json b/Nasa/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Nasa/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Nasa/Base.lproj/LaunchScreen.storyboard b/Nasa/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..865e932 --- /dev/null +++ b/Nasa/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Nasa/BaseViewController.swift b/Nasa/BaseViewController.swift new file mode 100644 index 0000000..489ff59 --- /dev/null +++ b/Nasa/BaseViewController.swift @@ -0,0 +1,29 @@ +// +// BaseViewController.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation +import UIKit + +class BaseViewController: UIViewController { + + override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + @available(*, unavailable) + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + } + + func showError(_ error: Error, _ handler: ()-> Void) { + + } + + func showLoading(_ show: Bool) { + + } +} diff --git a/Nasa/BaseViewModel.swift b/Nasa/BaseViewModel.swift new file mode 100644 index 0000000..f6104f8 --- /dev/null +++ b/Nasa/BaseViewModel.swift @@ -0,0 +1,12 @@ +// +// BaseViewModel.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +class BaseViewModel { + +} diff --git a/Nasa/ControllerIds.swift b/Nasa/ControllerIds.swift new file mode 100644 index 0000000..66cfd75 --- /dev/null +++ b/Nasa/ControllerIds.swift @@ -0,0 +1,17 @@ +// +// ControllerIds.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +enum ControllerIds: String { + case imagesListViewController = "ImagesListViewController" + case imageDetailViewModel = "ImageDetailViewModel" +} + +enum ViewIds: String { + case imageCellIdentifier = "ImageCellIdentifier" +} diff --git a/Nasa/ImageDetail/ImageDetailViewController.swift b/Nasa/ImageDetail/ImageDetailViewController.swift new file mode 100644 index 0000000..fe6968f --- /dev/null +++ b/Nasa/ImageDetail/ImageDetailViewController.swift @@ -0,0 +1,25 @@ +// +// ImageDetailViewController.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import UIKit + +final class ImageDetailViewController: BaseViewController { + private let viewModel: ImageDetailViewModel + + init(_ viewModel: ImageDetailViewModel) { + self.viewModel = viewModel + super.init(nibName: ControllerIds.imageDetailViewModel.rawValue, bundle: Bundle.main) + } + + override func viewDidLoad() { + super.viewDidLoad() + } + + func setup() { + + } +} diff --git a/Nasa/ImageDetail/ImageDetailViewController.xib b/Nasa/ImageDetail/ImageDetailViewController.xib new file mode 100644 index 0000000..864a043 --- /dev/null +++ b/Nasa/ImageDetail/ImageDetailViewController.xib @@ -0,0 +1,93 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Nasa/ImageDetail/ImageDetailViewModel.swift b/Nasa/ImageDetail/ImageDetailViewModel.swift new file mode 100644 index 0000000..70f4bca --- /dev/null +++ b/Nasa/ImageDetail/ImageDetailViewModel.swift @@ -0,0 +1,12 @@ +// +// ImageDetailViewModel.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +class ImageDetailViewModel: BaseViewModel { + +} diff --git a/Nasa/ImagesList/ImagesListViewController.swift b/Nasa/ImagesList/ImagesListViewController.swift new file mode 100644 index 0000000..1e22e95 --- /dev/null +++ b/Nasa/ImagesList/ImagesListViewController.swift @@ -0,0 +1,23 @@ +// +// ImagesListViewController.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation +import UIKit + +final class ImagesListViewController: BaseViewController { + private let viewModel: ImagesListViewModel + + init(_ viewModel: ImagesListViewModel) { + self.viewModel = viewModel + super.init(nibName: ControllerIds.imagesListViewController.rawValue, bundle: Bundle.main) + } + + override func viewDidLoad() { + super.viewDidLoad() + } + +} diff --git a/Nasa/ImagesList/ImagesListViewController.xib b/Nasa/ImagesList/ImagesListViewController.xib new file mode 100644 index 0000000..44f932d --- /dev/null +++ b/Nasa/ImagesList/ImagesListViewController.xib @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Nasa/ImagesList/ImagesListViewModel.swift b/Nasa/ImagesList/ImagesListViewModel.swift new file mode 100644 index 0000000..65f389e --- /dev/null +++ b/Nasa/ImagesList/ImagesListViewModel.swift @@ -0,0 +1,12 @@ +// +// ImagesListViewModel.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +class ImagesListViewModel { + +} diff --git a/Nasa/ImagesList/Views/ImageCell.xib b/Nasa/ImagesList/Views/ImageCell.xib new file mode 100644 index 0000000..cbe765c --- /dev/null +++ b/Nasa/ImagesList/Views/ImageCell.xib @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Nasa/ImagesList/Views/ImagesCell.swift b/Nasa/ImagesList/Views/ImagesCell.swift new file mode 100644 index 0000000..a3c8046 --- /dev/null +++ b/Nasa/ImagesList/Views/ImagesCell.swift @@ -0,0 +1,18 @@ +// +// ImageCell.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import UIKit + +final class ImageCell: UITableViewCell { + @IBOutlet private weak var titleLabel: UILabel! + @IBOutlet private weak var descLabel: UILabel! + + func configure() { + titleLabel.text = "ARC-2002-ACD02-0056-22" + descLabel.text = "Tom Trower | 20 Mar, 2002" + } +} diff --git a/Nasa/Info.plist b/Nasa/Info.plist new file mode 100644 index 0000000..dd3c9af --- /dev/null +++ b/Nasa/Info.plist @@ -0,0 +1,25 @@ + + + + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneConfigurationName + Default Configuration + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + + diff --git a/Nasa/Models/NasaErrors.swift b/Nasa/Models/NasaErrors.swift new file mode 100644 index 0000000..77d923d --- /dev/null +++ b/Nasa/Models/NasaErrors.swift @@ -0,0 +1,12 @@ +// +// NasaErrors.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +public enum NasaErrors: Error { + case timeout +} diff --git a/Nasa/Models/NasaResponseModel.swift b/Nasa/Models/NasaResponseModel.swift new file mode 100644 index 0000000..6132d4f --- /dev/null +++ b/Nasa/Models/NasaResponseModel.swift @@ -0,0 +1,44 @@ +// +// NasaResponseModel.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +struct SearchResponse: Codable { + let collection: collectionResponse +} + +struct collectionResponse: Codable { + let items: [itemsResponse] + + func computeSubtitle(_ photographer: String, _ dateCreated: String) -> String { + return "\(photographer) | \(dateCreated)" + } + + func toListUIModel() -> UIModel { + return UIModel(imageUrl: items.first?.links.first?.href ?? "", + title: items.first?.data.first?.title ?? "", + subtitle: computeSubtitle( items.first?.data.first?.photographer ?? "", + items.first?.data.first?.dateCreated ?? ""), + description: items.first?.data.first?.description ?? "") + } +} + +struct itemsResponse: Codable { + let data: [dataResponse] + let links: [linksResponse] +} + +struct dataResponse: Codable { + let title: String + let photographer: String + let dateCreated: String + let description: String +} + +struct linksResponse: Codable { + let href: String +} diff --git a/Nasa/Models/NasaUIModels.swift b/Nasa/Models/NasaUIModels.swift new file mode 100644 index 0000000..ab1293f --- /dev/null +++ b/Nasa/Models/NasaUIModels.swift @@ -0,0 +1,15 @@ +// +// NasaUIModels.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +struct UIModel { + let imageUrl: String + let title: String + let subtitle: String + let description: String +} diff --git a/Nasa/Nasa.xcdatamodeld/.xccurrentversion b/Nasa/Nasa.xcdatamodeld/.xccurrentversion new file mode 100644 index 0000000..0c67376 --- /dev/null +++ b/Nasa/Nasa.xcdatamodeld/.xccurrentversion @@ -0,0 +1,5 @@ + + + + + diff --git a/Nasa/Nasa.xcdatamodeld/Nasa.xcdatamodel/contents b/Nasa/Nasa.xcdatamodeld/Nasa.xcdatamodel/contents new file mode 100644 index 0000000..50d2514 --- /dev/null +++ b/Nasa/Nasa.xcdatamodeld/Nasa.xcdatamodel/contents @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Nasa/Networking /APIClient.swift b/Nasa/Networking /APIClient.swift new file mode 100644 index 0000000..26ae09c --- /dev/null +++ b/Nasa/Networking /APIClient.swift @@ -0,0 +1,60 @@ +// +// APIClient.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation +import RxSwift +import RxCocoa + +public protocol APIClientProtocol { + func request(_ urlRequest: URLRequest) -> Single<(T)> +} + +final class APIClient: APIClientProtocol { + func request(_ urlRequest: URLRequest) -> Single<(T)> { + return Single.create(subscribe: { [unowned self] (observer) -> Disposable in + return self.request(urlRequest, { (response) in + observer(.success(response)) + }, { (error) in + observer(.failure(error)) + }) + }) + } + + private func request(_ urlRequest: URLRequest, + _ responseHandler: @escaping (T) -> Void, + _ errorHandler: @escaping ((_ error: NasaErrors) -> Void)) -> Disposable { + return URLSession + .shared + .rx + .response(request: urlRequest) + .asSingle() + .timeout(RxTimeInterval.seconds(30), + scheduler: MainScheduler.instance) + .subscribe(onSuccess: { [weak self] (response) in + guard let self = self else { return } + let statusCode = response.response.statusCode + if 200..<300 ~= statusCode { + self.decodeResponse(response.response, response.data, responseHandler) + } else { + print("This is the error: \(statusCode)") + } + }, onFailure: { _ in + errorHandler(.timeOut) + }) + } + + private func decodeResponse(_ response: HTTPURLResponse, + _ data: Data, + _ responseHandler: @escaping (T) -> Void) { + do { + let decoder = JSONDecoder() + responseHandler(try decoder.decode(T.self, from: data)) + } catch { + print("This is the error: \(error), \(T.self)") + } + } +} diff --git a/Nasa/Networking /APIEndpoint.swift b/Nasa/Networking /APIEndpoint.swift new file mode 100644 index 0000000..d5fb27f --- /dev/null +++ b/Nasa/Networking /APIEndpoint.swift @@ -0,0 +1,12 @@ +// +// APIEndpoint.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +public enum APIEndpoint: String { + case search = "" +} diff --git a/Nasa/Networking /APIMethod.swift b/Nasa/Networking /APIMethod.swift new file mode 100644 index 0000000..f60cc8c --- /dev/null +++ b/Nasa/Networking /APIMethod.swift @@ -0,0 +1,12 @@ +// +// APIMethod.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +enum APIMethod: String { + case get = "GET" +} diff --git a/Nasa/Networking /RemoteDataSource.swift b/Nasa/Networking /RemoteDataSource.swift new file mode 100644 index 0000000..e516754 --- /dev/null +++ b/Nasa/Networking /RemoteDataSource.swift @@ -0,0 +1,8 @@ +// +// RemoteDataSource.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation diff --git a/Nasa/Networking /URLRequest+Nasa.swift b/Nasa/Networking /URLRequest+Nasa.swift new file mode 100644 index 0000000..efd6610 --- /dev/null +++ b/Nasa/Networking /URLRequest+Nasa.swift @@ -0,0 +1,40 @@ +// +// URLRequest+Nasa.swift +// Nasa +// +// Created by Angie Mugo on 21/11/2021. +// + +import Foundation + +extension URLRequest { + init(_ endpoint: APIEndpoint, _ method: APIMethod = .get, _ parameters: [String: Any?]? = nil) { + let baseURL = URL(string: "https://swapi.dev/")! + let path = String(format: endpoint.rawValue) + let urlString = "\(baseURL)\(path)" + let url = URL(string: urlString)! + self.init(url: url) + httpMethod = method.rawValue + processGetParameters(parameters) + } + + private mutating func processGetParameters(_ parameters: [String: Any?]? = nil) { + guard let parameters = parameters, !parameters.isEmpty else { return } + let queryParameters = parameters.reduce("?") { (result, element) -> String in + guard let value = element.value else { return result } + guard value as? String != "" else { return result } + if result.count > 1 { + return "\(result)&\(element.key)=\(value)" + } + return "\(result)\(element.key)=\(value)" + } + var queryCharSet = NSCharacterSet.urlQueryAllowed + queryCharSet.remove(charactersIn: "+") + if let url = self.url?.absoluteString, + let urlQueryParameters = queryParameters.addingPercentEncoding(withAllowedCharacters: queryCharSet) { + let urlWithParameters = "\(url)\(urlQueryParameters)" + self.url = URL(string: urlWithParameters)! + } + } + +} diff --git a/NasaTests/NasaTests.swift b/NasaTests/NasaTests.swift new file mode 100644 index 0000000..821be3a --- /dev/null +++ b/NasaTests/NasaTests.swift @@ -0,0 +1,33 @@ +// +// NasaTests.swift +// NasaTests +// +// Created by Angie Mugo on 21/11/2021. +// + +import XCTest +@testable import Nasa + +class NasaTests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() throws { + // This is an example of a performance test case. + self.measure { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/NasaUITests/NasaUITests.swift b/NasaUITests/NasaUITests.swift new file mode 100644 index 0000000..76617a1 --- /dev/null +++ b/NasaUITests/NasaUITests.swift @@ -0,0 +1,42 @@ +// +// NasaUITests.swift +// NasaUITests +// +// Created by Angie Mugo on 21/11/2021. +// + +import XCTest + +class NasaUITests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + func testExample() throws { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testLaunchPerformance() throws { + if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 7.0, *) { + // This measures how long it takes to launch your application. + measure(metrics: [XCTApplicationLaunchMetric()]) { + XCUIApplication().launch() + } + } + } +} diff --git a/NasaUITests/NasaUITestsLaunchTests.swift b/NasaUITests/NasaUITestsLaunchTests.swift new file mode 100644 index 0000000..38c5af9 --- /dev/null +++ b/NasaUITests/NasaUITestsLaunchTests.swift @@ -0,0 +1,32 @@ +// +// NasaUITestsLaunchTests.swift +// NasaUITests +// +// Created by Angie Mugo on 21/11/2021. +// + +import XCTest + +class NasaUITestsLaunchTests: XCTestCase { + + override class var runsForEachTargetApplicationUIConfiguration: Bool { + true + } + + override func setUpWithError() throws { + continueAfterFailure = false + } + + func testLaunch() throws { + let app = XCUIApplication() + app.launch() + + // Insert steps here to perform after app launch but before taking a screenshot, + // such as logging into a test account or navigating somewhere in the app + + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = "Launch Screen" + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/Podfile b/Podfile new file mode 100644 index 0000000..6eba09b --- /dev/null +++ b/Podfile @@ -0,0 +1,22 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'Nasa' do + # Comment the next line if you don't want to use dynamic frameworks + use_frameworks! + + # Pods for Nasa + pod 'RxSwift', '6.2.0' + pod 'RxCocoa', '6.2.0' + pod 'Kingfisher', '~> 7.0' + + target 'NasaTests' do + inherit! :search_paths + # Pods for testing + end + + target 'NasaUITests' do + # Pods for testing + end + +end diff --git a/Podfile.lock b/Podfile.lock new file mode 100644 index 0000000..e7c7436 --- /dev/null +++ b/Podfile.lock @@ -0,0 +1,30 @@ +PODS: + - Kingfisher (7.1.1) + - RxCocoa (6.2.0): + - RxRelay (= 6.2.0) + - RxSwift (= 6.2.0) + - RxRelay (6.2.0): + - RxSwift (= 6.2.0) + - RxSwift (6.2.0) + +DEPENDENCIES: + - Kingfisher (~> 7.0) + - RxCocoa (= 6.2.0) + - RxSwift (= 6.2.0) + +SPEC REPOS: + trunk: + - Kingfisher + - RxCocoa + - RxRelay + - RxSwift + +SPEC CHECKSUMS: + Kingfisher: f738f9c4a3415823b8e2985d10aa2d6a9f37bc4d + RxCocoa: 4baf94bb35f2c0ab31bc0cb9f1900155f646ba42 + RxRelay: e72dbfd157807478401ef1982e1c61c945c94b2f + RxSwift: d356ab7bee873611322f134c5f9ef379fa183d8f + +PODFILE CHECKSUM: 9e4406f25ebfec3e20e49b98c0644cffd32405b1 + +COCOAPODS: 1.11.2 diff --git a/Pods/Kingfisher/LICENSE b/Pods/Kingfisher/LICENSE new file mode 100644 index 0000000..80888ba --- /dev/null +++ b/Pods/Kingfisher/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2019 Wei Wang + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/Pods/Kingfisher/README.md b/Pods/Kingfisher/README.md new file mode 100644 index 0000000..43476d2 --- /dev/null +++ b/Pods/Kingfisher/README.md @@ -0,0 +1,254 @@ +

+Kingfisher +

+ +

+ + + + + +
+ + +

+ +Kingfisher is a powerful, pure-Swift library for downloading and caching images from the web. It provides you a chance to use a pure-Swift way to work with remote images in your next app. + +## Features + +- [x] Asynchronous image downloading and caching. +- [x] Loading image from either `URLSession`-based networking or local provided data. +- [x] Useful image processors and filters provided. +- [x] Multiple-layer hybrid cache for both memory and disk. +- [x] Fine control on cache behavior. Customizable expiration date and size limit. +- [x] Cancelable downloading and auto-reusing previous downloaded content to improve performance. +- [x] Independent components. Use the downloader, caching system, and image processors separately as you need. +- [x] Prefetching images and showing them from the cache to boost your app. +- [x] View extensions for `UIImageView`, `NSImageView`, `NSButton` and `UIButton` to directly set an image from a URL. +- [x] Built-in transition animation when setting images. +- [x] Customizable placeholder and indicator while loading images. +- [x] Extensible image processing and image format easily. +- [x] Low Data Mode support. +- [x] SwiftUI support. + +### Kingfisher 101 + +The simplest use-case is setting an image to an image view with the `UIImageView` extension: + +```swift +import Kingfisher + +let url = URL(string: "https://example.com/image.png") +imageView.kf.setImage(with: url) +``` + +Kingfisher will download the image from `url`, send it to both memory cache and disk cache, and display it in `imageView`. +When you set with the same URL later, the image will be retrieved from the cache and shown immediately. + +It also works if you use SwiftUI: + +```swift +var body: some View { + KFImage(URL(string: "https://example.com/image.png")!) +} +``` + +### A More Advanced Example + +With the powerful options, you can do hard tasks with Kingfisher in a simple way. For example, the code below: + +1. Downloads a high-resolution image. +2. Downsamples it to match the image view size. +3. Makes it round cornered with a given radius. +4. Shows a system indicator and a placeholder image while downloading. +5. When prepared, it animates the small thumbnail image with a "fade in" effect. +6. The original large image is also cached to disk for later use, to get rid of downloading it again in a detail view. +7. A console log is printed when the task finishes, either for success or failure. + +```swift +let url = URL(string: "https://example.com/high_resolution_image.png") +let processor = DownsamplingImageProcessor(size: imageView.bounds.size) + |> RoundCornerImageProcessor(cornerRadius: 20) +imageView.kf.indicatorType = .activity +imageView.kf.setImage( + with: url, + placeholder: UIImage(named: "placeholderImage"), + options: [ + .processor(processor), + .scaleFactor(UIScreen.main.scale), + .transition(.fade(1)), + .cacheOriginalImage + ]) +{ + result in + switch result { + case .success(let value): + print("Task done for: \(value.source.url?.absoluteString ?? "")") + case .failure(let error): + print("Job failed: \(error.localizedDescription)") + } +} +``` + +It is a common situation I can meet in my daily work. Think about how many lines you need to write without +Kingfisher! + +### Method Chaining + +If you are not a fan of the `kf` extension, you can also prefer to use the `KF` builder and chained the method +invocations. The code below is doing the same thing: + +```swift +// Use `kf` extension +imageView.kf.setImage( + with: url, + placeholder: placeholderImage, + options: [ + .processor(processor), + .loadDiskFileSynchronously, + .cacheOriginalImage, + .transition(.fade(0.25)), + .lowDataMode(.network(lowResolutionURL)) + ], + progressBlock: { receivedSize, totalSize in + // Progress updated + }, + completionHandler: { result in + // Done + } +) + +// Use `KF` builder +KF.url(url) + .placeholder(placeholderImage) + .setProcessor(processor) + .loadDiskFileSynchronously() + .cacheMemoryOnly() + .fade(duration: 0.25) + .lowDataModeSource(.network(lowResolutionURL)) + .onProgress { receivedSize, totalSize in } + .onSuccess { result in } + .onFailure { error in } + .set(to: imageView) +``` + +And even better, if later you want to switch to SwiftUI, just change the `KF` above to `KFImage`, and you've done: + +```swift +struct ContentView: View { + var body: some View { + KFImage.url(url) + .placeholder(placeholderImage) + .setProcessor(processor) + .loadDiskFileSynchronously() + .cacheMemoryOnly() + .fade(duration: 0.25) + .lowDataModeSource(.network(lowResolutionURL)) + .onProgress { receivedSize, totalSize in } + .onSuccess { result in } + .onFailure { error in } + } +} +``` + +### Learn More + +To learn the use of Kingfisher by more examples, take a look at the well-prepared [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet). T +here we summarized the most common tasks in Kingfisher, you can get a better idea of what this framework can do. +There are also some performance tips, remember to check them too. + +## Requirements + +- iOS 12.0+ / macOS 10.14+ / tvOS 12.0+ / watchOS 5.0+ (if you use only UIKit/AppKit) +- iOS 14.0+ / macOS 11.0+ / tvOS 14.0+ / watchOS 7.0+ (if you use it in SwiftUI) +- Swift 5.0+ + +> If you need to support from iOS 10 (UIKit/AppKit) or iOS 13 (SwiftUI), use Kingfisher version 6.x. But it won't work +> with Xcode 13 [#1802](https://github.com/onevcat/Kingfisher/issues/1802). +> +> If you need to use Xcode 13 but cannot upgrade to v7, use the `version6-xcode13` branch. However, you have to drop +> iOS 10 support due to an Xcode 13 bug. +> +> | UIKit | SwiftUI | Xcode | Kingfisher | +> |---|---|---|---| +> | iOS 10+ | iOS 13+ | 12 | ~> 6.3.1 | +> | iOS 11+ | iOS 13+ | 13 | `version6-xcode13` | +> | iOS 12+ | iOS 14+ | 13 | ~> 7.0 | + +### Installation + +A detailed guide for installation can be found in [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide). + +#### Swift Package Manager + +- File > Swift Packages > Add Package Dependency +- Add `https://github.com/onevcat/Kingfisher.git` +- Select "Up to Next Major" with "7.0.0" + +#### CocoaPods + +```ruby +source 'https://github.com/CocoaPods/Specs.git' +platform :ios, '12.0' +use_frameworks! + +target 'MyApp' do + pod 'Kingfisher', '~> 7.0' +end +``` + +#### Carthage + +``` +github "onevcat/Kingfisher" ~> 7.0 +``` + + +### Migrating + +[Kingfisher 7.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) - Kingfisher 7.x is NOT fully compatible with the previous version. However, changes should be trivial or not required at all. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-7.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project. + +If you are using an even earlier version, see the guides below to know the steps for migrating. + +> - [Kingfisher 6.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) - Kingfisher 6.x is NOT fully compatible with the previous version. However, the migration is not difficult. Depending on your use cases, it may take no effect or several minutes to modify your existing code for the new version. Please follow the [migration guide](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-6.0-Migration-Guide) when you prepare to upgrade Kingfisher in your project. +> - [Kingfisher 5.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-5.0-Migration-Guide) - If you are upgrading to Kingfisher 5.x from 4.x, please read this for more information. +> - Kingfisher 4.0 Migration - Kingfisher 3.x should be source compatible to Kingfisher 4. The reason for a major update is that we need to specify the Swift version explicitly for Xcode. All deprecated methods in Kingfisher 3 were removed, so please ensure you have no warning left before you migrate from Kingfisher 3 to Kingfisher 4. If you have any trouble when migrating, please open an issue to discuss. +> - [Kingfisher 3.0 Migration](https://github.com/onevcat/Kingfisher/wiki/Kingfisher-3.0-Migration-Guide) - If you are upgrading to Kingfisher 3.x from an earlier version, please read this for more information. + +## Next Steps + +We prepared a [wiki page](https://github.com/onevcat/Kingfisher/wiki). You can find tons of useful things there. + +* [Installation Guide](https://github.com/onevcat/Kingfisher/wiki/Installation-Guide) - Follow it to integrate Kingfisher into your project. +* [Cheat Sheet](https://github.com/onevcat/Kingfisher/wiki/Cheat-Sheet)- Curious about what Kingfisher could do and how would it look like when used in your project? See this page for useful code snippets. If you are already familiar with Kingfisher, you could also learn new tricks to improve the way you use Kingfisher! +* [API Reference](https://kingfisher.onevcat.com/) - Lastly, please remember to read the full whenever you may need a more detailed reference. + +## Other + +### Future of Kingfisher + +I want to keep Kingfisher lightweight. This framework focuses on providing a simple solution for downloading and caching images. This doesn’t mean the framework can’t be improved. Kingfisher is far from perfect, so necessary and useful updates will be made to make it better. + +### Developments and Tests + +Any contributing and pull requests are warmly welcome. However, before you plan to implement some features or try to fix an uncertain issue, it is recommended to open a discussion first. It would be appreciated if your pull requests could build and with all tests green. :) + +### About the logo + +The logo of Kingfisher is inspired by [Tangram (七巧板)](http://en.wikipedia.org/wiki/Tangram), a dissection puzzle consisting of seven flat shapes from China. I believe she's a kingfisher bird instead of a swift, but someone insists that she is a pigeon. I guess I should give her a name. Hi, guys, do you have any suggestions? + +### Contact + +Follow and contact me on [Twitter](http://twitter.com/onevcat) or [Sina Weibo](http://weibo.com/onevcat). If you find an issue, [open a ticket](https://github.com/onevcat/Kingfisher/issues/new). Pull requests are warmly welcome as well. + +## Backers & Sponsors + +Open-source projects cannot live long without your help. If you find Kingfisher is useful, please consider supporting this +project by becoming a sponsor. Your user icon or company logo shows up [on my blog](https://onevcat.com/tabs/about/) with a link to your home page. + +Become a sponsor through [GitHub Sponsors](https://github.com/sponsors/onevcat) or [Open Collective](https://opencollective.com/kingfisher#sponsor). :heart: + +### License + +Kingfisher is released under the MIT license. See LICENSE for details. diff --git a/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift new file mode 100644 index 0000000..8cb09f2 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/CacheSerializer.swift @@ -0,0 +1,117 @@ +// +// CacheSerializer.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/02. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +/// An `CacheSerializer` is used to convert some data to an image object after +/// retrieving it from disk storage, and vice versa, to convert an image to data object +/// for storing to the disk storage. +public protocol CacheSerializer { + + /// Gets the serialized data from a provided image + /// and optional original data for caching to disk. + /// + /// - Parameters: + /// - image: The image needed to be serialized. + /// - original: The original data which is just downloaded. + /// If the image is retrieved from cache instead of + /// downloaded, it will be `nil`. + /// - Returns: The data object for storing to disk, or `nil` when no valid + /// data could be serialized. + func data(with image: KFCrossPlatformImage, original: Data?) -> Data? + + /// Gets an image from provided serialized data. + /// + /// - Parameters: + /// - data: The data from which an image should be deserialized. + /// - options: The parsed options for deserialization. + /// - Returns: An image deserialized or `nil` when no valid image + /// could be deserialized. + func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? +} + +/// Represents a basic and default `CacheSerializer` used in Kingfisher disk cache system. +/// It could serialize and deserialize images in PNG, JPEG and GIF format. For +/// image other than these formats, a normalized `pngRepresentation` will be used. +public struct DefaultCacheSerializer: CacheSerializer { + + /// The default general cache serializer used across Kingfisher's cache. + public static let `default` = DefaultCacheSerializer() + + /// The compression quality when converting image to a lossy format data. Default is 1.0. + public var compressionQuality: CGFloat = 1.0 + + /// Whether the original data should be preferred when serializing the image. + /// If `true`, the input original data will be checked first and used unless the data is `nil`. + /// In that case, the serialization will fall back to creating data from image. + public var preferCacheOriginalData: Bool = false + + /// Creates a cache serializer that serialize and deserialize images in PNG, JPEG and GIF format. + /// + /// - Note: + /// Use `DefaultCacheSerializer.default` unless you need to specify your own properties. + /// + public init() { } + + /// - Parameters: + /// - image: The image needed to be serialized. + /// - original: The original data which is just downloaded. + /// If the image is retrieved from cache instead of + /// downloaded, it will be `nil`. + /// - Returns: The data object for storing to disk, or `nil` when no valid + /// data could be serialized. + /// + /// - Note: + /// Only when `original` contains valid PNG, JPEG and GIF format data, the `image` will be + /// converted to the corresponding data type. Otherwise, if the `original` is provided but it is not + /// If `original` is `nil`, the input `image` will be encoded as PNG data. + public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? { + if preferCacheOriginalData { + return original ?? + image.kf.data( + format: original?.kf.imageFormat ?? .unknown, + compressionQuality: compressionQuality + ) + } else { + return image.kf.data( + format: original?.kf.imageFormat ?? .unknown, + compressionQuality: compressionQuality + ) + } + } + + /// Gets an image deserialized from provided data. + /// + /// - Parameters: + /// - data: The data from which an image should be deserialized. + /// - options: Options for deserialization. + /// - Returns: An image deserialized or `nil` when no valid image + /// could be deserialized. + public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } +} diff --git a/Pods/Kingfisher/Sources/Cache/DiskStorage.swift b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift new file mode 100644 index 0000000..debe7f4 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/DiskStorage.swift @@ -0,0 +1,586 @@ +// +// DiskStorage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + + +/// Represents a set of conception related to storage which stores a certain type of value in disk. +/// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the +/// storage. See these composed types for more information. +public enum DiskStorage { + + /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data + /// and stored as file in the file system under a specified location. + /// + /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value. + /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep + /// track of a file for its expiration or size limitation. + public class Backend { + /// The config used for this disk storage. + public var config: Config + + // The final storage URL on disk, with `name` and `cachePathBlock` considered. + public let directoryURL: URL + + let metaChangingQueue: DispatchQueue + + var maybeCached : Set? + let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue") + + // `false` if the storage initialized with an error. This prevents unexpected forcibly crash when creating + // storage in the default cache. + private var storageReady: Bool = true + + /// Creates a disk storage with the given `DiskStorage.Config`. + /// + /// - Parameter config: The config used for this disk storage. + /// - Throws: An error if the folder for storage cannot be got or created. + public convenience init(config: Config) throws { + self.init(noThrowConfig: config, creatingDirectory: false) + try prepareDirectory() + } + + // If `creatingDirectory` is `false`, the directory preparation will be skipped. + // We need to call `prepareDirectory` manually after this returns. + init(noThrowConfig config: Config, creatingDirectory: Bool) { + var config = config + + let creation = Creation(config) + self.directoryURL = creation.directoryURL + + // Break any possible retain cycle set by outside. + config.cachePathBlock = nil + self.config = config + + metaChangingQueue = DispatchQueue(label: creation.cacheName) + setupCacheChecking() + + if creatingDirectory { + try? prepareDirectory() + } + } + + private func setupCacheChecking() { + maybeCachedCheckingQueue.async { + do { + self.maybeCached = Set() + try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in + self.maybeCached?.insert(fileName) + } + } catch { + // Just disable the functionality if we fail to initialize it properly. This will just revert to + // the behavior which is to check file existence on disk directly. + self.maybeCached = nil + } + } + } + + // Creates the storage folder. + private func prepareDirectory() throws { + let fileManager = config.fileManager + let path = directoryURL.path + + guard !fileManager.fileExists(atPath: path) else { return } + + do { + try fileManager.createDirectory( + atPath: path, + withIntermediateDirectories: true, + attributes: nil) + } catch { + self.storageReady = false + throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error)) + } + } + + /// Stores a value to the storage under the specified key and expiration policy. + /// - Parameters: + /// - value: The value to be stored. + /// - key: The key to which the `value` will be stored. If there is already a value under the key, + /// the old value will be overwritten by `value`. + /// - expiration: The expiration policy used by this store action. + /// - writeOptions: Data writing options used the new files. + /// - Throws: An error during converting the value to a data format or during writing it to disk. + public func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil, + writeOptions: Data.WritingOptions = []) throws + { + guard storageReady else { + throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL)) + } + + let expiration = expiration ?? config.expiration + // The expiration indicates that already expired, no need to store. + guard !expiration.isExpired else { return } + + let data: Data + do { + data = try value.toData() + } catch { + throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error)) + } + + let fileURL = cacheFileURL(forKey: key) + do { + try data.write(to: fileURL, options: writeOptions) + } catch { + throw KingfisherError.cacheError( + reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error) + ) + } + + let now = Date() + let attributes: [FileAttributeKey : Any] = [ + // The last access date. + .creationDate: now.fileAttributeDate, + // The estimated expiration date. + .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate + ] + do { + try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path) + } catch { + try? config.fileManager.removeItem(at: fileURL) + throw KingfisherError.cacheError( + reason: .cannotSetCacheFileAttribute( + filePath: fileURL.path, + attributes: attributes, + error: error + ) + ) + } + + maybeCachedCheckingQueue.async { + self.maybeCached?.insert(fileURL.lastPathComponent) + } + } + + /// Gets a value from the storage. + /// - Parameters: + /// - key: The cache key of value. + /// - extendingExpiration: The expiration policy used by this getting action. + /// - Throws: An error during converting the data to a value or during operation of disk files. + /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`. + public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? { + return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration) + } + + func value( + forKey key: String, + referenceDate: Date, + actuallyLoad: Bool, + extendingExpiration: ExpirationExtending) throws -> T? + { + guard storageReady else { + throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL)) + } + + let fileManager = config.fileManager + let fileURL = cacheFileURL(forKey: key) + let filePath = fileURL.path + + let fileMaybeCached = maybeCachedCheckingQueue.sync { + return maybeCached?.contains(fileURL.lastPathComponent) ?? true + } + guard fileMaybeCached else { + return nil + } + guard fileManager.fileExists(atPath: filePath) else { + return nil + } + + let meta: FileMeta + do { + let resourceKeys: Set = [.contentModificationDateKey, .creationDateKey] + meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys) + } catch { + throw KingfisherError.cacheError( + reason: .invalidURLResource(error: error, key: key, url: fileURL)) + } + + if meta.expired(referenceDate: referenceDate) { + return nil + } + if !actuallyLoad { return T.empty } + + do { + let data = try Data(contentsOf: fileURL) + let obj = try T.fromData(data) + metaChangingQueue.async { + meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration) + } + return obj + } catch { + throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error)) + } + } + + /// Whether there is valid cached data under a given key. + /// - Parameter key: The cache key of value. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + /// + /// - Note: + /// This method does not actually load the data from disk, so it is faster than directly loading the cached value + /// by checking the nullability of `value(forKey:extendingExpiration:)` method. + /// + public func isCached(forKey key: String) -> Bool { + return isCached(forKey: key, referenceDate: Date()) + } + + /// Whether there is valid cached data under a given key and a reference date. + /// - Parameters: + /// - key: The cache key of value. + /// - referenceDate: A reference date to check whether the cache is still valid. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + /// + /// - Note: + /// If you pass `Date()` to `referenceDate`, this method is identical to `isCached(forKey:)`. Use the + /// `referenceDate` to determine whether the cache is still valid for a future date. + public func isCached(forKey key: String, referenceDate: Date) -> Bool { + do { + let result = try value( + forKey: key, + referenceDate: referenceDate, + actuallyLoad: false, + extendingExpiration: .none + ) + return result != nil + } catch { + return false + } + } + + /// Removes a value from a specified key. + /// - Parameter key: The cache key of value. + /// - Throws: An error during removing the value. + public func remove(forKey key: String) throws { + let fileURL = cacheFileURL(forKey: key) + try removeFile(at: fileURL) + } + + func removeFile(at url: URL) throws { + try config.fileManager.removeItem(at: url) + } + + /// Removes all values in this storage. + /// - Throws: An error during removing the values. + public func removeAll() throws { + try removeAll(skipCreatingDirectory: false) + } + + func removeAll(skipCreatingDirectory: Bool) throws { + try config.fileManager.removeItem(at: directoryURL) + if !skipCreatingDirectory { + try prepareDirectory() + } + } + + /// The URL of the cached file with a given computed `key`. + /// + /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not + /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered. + /// + /// - Note: + /// This method does not guarantee there is an image already cached in the returned URL. It just gives your + /// the URL that the image should be if it exists in disk storage, with the give key. + /// + public func cacheFileURL(forKey key: String) -> URL { + let fileName = cacheFileName(forKey: key) + return directoryURL.appendingPathComponent(fileName, isDirectory: false) + } + + func cacheFileName(forKey key: String) -> String { + if config.usesHashedFileName { + let hashedKey = key.kf.md5 + if let ext = config.pathExtension { + return "\(hashedKey).\(ext)" + } else if config.autoExtAfterHashedFileName, + let ext = key.kf.ext { + return "\(hashedKey).\(ext)" + } + return hashedKey + } else { + if let ext = config.pathExtension { + return "\(key).\(ext)" + } + return key + } + } + + func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] { + let fileManager = config.fileManager + + guard let directoryEnumerator = fileManager.enumerator( + at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else + { + throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL)) + } + + guard let urls = directoryEnumerator.allObjects as? [URL] else { + throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL)) + } + return urls + } + + /// Removes all expired values from this storage. + /// - Throws: A file manager error during removing the file. + /// - Returns: The URLs for removed files. + public func removeExpiredValues() throws -> [URL] { + return try removeExpiredValues(referenceDate: Date()) + } + + func removeExpiredValues(referenceDate: Date) throws -> [URL] { + let propertyKeys: [URLResourceKey] = [ + .isDirectoryKey, + .contentModificationDateKey + ] + + let urls = try allFileURLs(for: propertyKeys) + let keys = Set(propertyKeys) + let expiredFiles = urls.filter { fileURL in + do { + let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys) + if meta.isDirectory { + return false + } + return meta.expired(referenceDate: referenceDate) + } catch { + return true + } + } + try expiredFiles.forEach { url in + try removeFile(at: url) + } + return expiredFiles + } + + /// Removes all size exceeded values from this storage. + /// - Throws: A file manager error during removing the file. + /// - Returns: The URLs for removed files. + /// + /// - Note: This method checks `config.sizeLimit` and remove cached files in an LRU (Least Recently Used) way. + func removeSizeExceededValues() throws -> [URL] { + + if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit. + + var size = try totalSize() + if size < config.sizeLimit { return [] } + + let propertyKeys: [URLResourceKey] = [ + .isDirectoryKey, + .creationDateKey, + .fileSizeKey + ] + let keys = Set(propertyKeys) + + let urls = try allFileURLs(for: propertyKeys) + var pendings: [FileMeta] = urls.compactMap { fileURL in + guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else { + return nil + } + return meta + } + // Sort by last access date. Most recent file first. + pendings.sort(by: FileMeta.lastAccessDate) + + var removed: [URL] = [] + let target = config.sizeLimit / 2 + while size > target, let meta = pendings.popLast() { + size -= UInt(meta.fileSize) + try removeFile(at: meta.url) + removed.append(meta.url) + } + return removed + } + + /// Gets the total file size of the folder in bytes. + public func totalSize() throws -> UInt { + let propertyKeys: [URLResourceKey] = [.fileSizeKey] + let urls = try allFileURLs(for: propertyKeys) + let keys = Set(propertyKeys) + let totalSize: UInt = urls.reduce(0) { size, fileURL in + do { + let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys) + return size + UInt(meta.fileSize) + } catch { + return size + } + } + return totalSize + } + } +} + +extension DiskStorage { + /// Represents the config used in a `DiskStorage`. + public struct Config { + + /// The file size limit on disk of the storage in bytes. 0 means no limit. + public var sizeLimit: UInt + + /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`, + /// means that the disk cache would expire in one week. + public var expiration: StorageExpiration = .days(7) + + /// The preferred extension of cache item. It will be appended to the file name as its extension. + /// Default is `nil`, means that the cache file does not contain a file extension. + public var pathExtension: String? = nil + + /// Default is `true`, means that the cache file name will be hashed before storing. + public var usesHashedFileName = true + + /// Default is `false` + /// If set to `true`, image extension will be extracted from original file name and append to + /// the hased file name and used as the cache key on disk. + public var autoExtAfterHashedFileName = false + + let name: String + let fileManager: FileManager + let directory: URL? + + var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = { + (directory, cacheName) in + return directory.appendingPathComponent(cacheName, isDirectory: true) + } + + /// Creates a config value based on given parameters. + /// + /// - Parameters: + /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk + /// storage. Two storages with the same `name` would share the same folder in disk, and it should + /// be prevented. + /// - sizeLimit: The size limit in bytes for all existing files in the disk storage. + /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`. + /// - directory: The URL where the disk storage should live. The storage will use this as the root folder, + /// and append a path which is constructed by input `name`. Default is `nil`, indicates that + /// the cache directory under user domain mask will be used. + public init( + name: String, + sizeLimit: UInt, + fileManager: FileManager = .default, + directory: URL? = nil) + { + self.name = name + self.fileManager = fileManager + self.directory = directory + self.sizeLimit = sizeLimit + } + } +} + +extension DiskStorage { + struct FileMeta { + + let url: URL + + let lastAccessDate: Date? + let estimatedExpirationDate: Date? + let isDirectory: Bool + let fileSize: Int + + static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool { + return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast + } + + init(fileURL: URL, resourceKeys: Set) throws { + let meta = try fileURL.resourceValues(forKeys: resourceKeys) + self.init( + fileURL: fileURL, + lastAccessDate: meta.creationDate, + estimatedExpirationDate: meta.contentModificationDate, + isDirectory: meta.isDirectory ?? false, + fileSize: meta.fileSize ?? 0) + } + + init( + fileURL: URL, + lastAccessDate: Date?, + estimatedExpirationDate: Date?, + isDirectory: Bool, + fileSize: Int) + { + self.url = fileURL + self.lastAccessDate = lastAccessDate + self.estimatedExpirationDate = estimatedExpirationDate + self.isDirectory = isDirectory + self.fileSize = fileSize + } + + func expired(referenceDate: Date) -> Bool { + return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true + } + + func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) { + guard let lastAccessDate = lastAccessDate, + let lastEstimatedExpiration = estimatedExpirationDate else + { + return + } + + let attributes: [FileAttributeKey : Any] + + switch extendingExpiration { + case .none: + // not extending expiration time here + return + case .cacheTime: + let originalExpiration: StorageExpiration = + .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate)) + attributes = [ + .creationDate: Date().fileAttributeDate, + .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate + ] + case .expirationTime(let expirationTime): + attributes = [ + .creationDate: Date().fileAttributeDate, + .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate + ] + } + + try? fileManager.setAttributes(attributes, ofItemAtPath: url.path) + } + } +} + +extension DiskStorage { + struct Creation { + let directoryURL: URL + let cacheName: String + + init(_ config: Config) { + let url: URL + if let directory = config.directory { + url = directory + } else { + url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + } + + cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)" + directoryURL = config.cachePathBlock(url, cacheName) + } + } +} diff --git a/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift new file mode 100644 index 0000000..cdfb7c3 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/FormatIndicatedCacheSerializer.swift @@ -0,0 +1,118 @@ +// +// RequestModifier.swift +// Kingfisher +// +// Created by Junyu Kuang on 5/28/17. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +/// `FormatIndicatedCacheSerializer` lets you indicate an image format for serialized caches. +/// +/// It could serialize and deserialize PNG, JPEG and GIF images. For +/// image other than these formats, a normalized `pngRepresentation` will be used. +/// +/// Example: +/// ```` +/// let profileImageSize = CGSize(width: 44, height: 44) +/// +/// // A round corner image. +/// let imageProcessor = RoundCornerImageProcessor( +/// cornerRadius: profileImageSize.width / 2, targetSize: profileImageSize) +/// +/// let optionsInfo: KingfisherOptionsInfo = [ +/// .cacheSerializer(FormatIndicatedCacheSerializer.png), +/// .processor(imageProcessor)] +/// +/// A URL pointing to a JPEG image. +/// let url = URL(string: "https://example.com/image.jpg")! +/// +/// // Image will be always cached as PNG format to preserve alpha channel for round rectangle. +/// // So when you load it from cache again later, it will be still round cornered. +/// // Otherwise, the corner part would be filled by white color (since JPEG does not contain an alpha channel). +/// imageView.kf.setImage(with: url, options: optionsInfo) +/// ```` +public struct FormatIndicatedCacheSerializer: CacheSerializer { + + /// A `FormatIndicatedCacheSerializer` which converts image from and to PNG format. If the image cannot be + /// represented by PNG format, it will fallback to its real format which is determined by `original` data. + public static let png = FormatIndicatedCacheSerializer(imageFormat: .PNG, jpegCompressionQuality: nil) + + /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format. If the image cannot be + /// represented by JPEG format, it will fallback to its real format which is determined by `original` data. + /// The compression quality is 1.0 when using this serializer. If you need to set a customized compression quality, + /// use `jpeg(compressionQuality:)`. + public static let jpeg = FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: 1.0) + + /// A `FormatIndicatedCacheSerializer` which converts image from and to JPEG format with a settable compression + /// quality. If the image cannot be represented by JPEG format, it will fallback to its real format which is + /// determined by `original` data. + /// - Parameter compressionQuality: The compression quality when converting image to JPEG data. + public static func jpeg(compressionQuality: CGFloat) -> FormatIndicatedCacheSerializer { + return FormatIndicatedCacheSerializer(imageFormat: .JPEG, jpegCompressionQuality: compressionQuality) + } + + /// A `FormatIndicatedCacheSerializer` which converts image from and to GIF format. If the image cannot be + /// represented by GIF format, it will fallback to its real format which is determined by `original` data. + public static let gif = FormatIndicatedCacheSerializer(imageFormat: .GIF, jpegCompressionQuality: nil) + + /// The indicated image format. + private let imageFormat: ImageFormat + + /// The compression quality used for loss image format (like JPEG). + private let jpegCompressionQuality: CGFloat? + + /// Creates data which represents the given `image` under a format. + public func data(with image: KFCrossPlatformImage, original: Data?) -> Data? { + + func imageData(withFormat imageFormat: ImageFormat) -> Data? { + return autoreleasepool { () -> Data? in + switch imageFormat { + case .PNG: return image.kf.pngRepresentation() + case .JPEG: return image.kf.jpegRepresentation(compressionQuality: jpegCompressionQuality ?? 1.0) + case .GIF: return image.kf.gifRepresentation() + case .unknown: return nil + } + } + } + + // generate data with indicated image format + if let data = imageData(withFormat: imageFormat) { + return data + } + + let originalFormat = original?.kf.imageFormat ?? .unknown + + // generate data with original image's format + if originalFormat != imageFormat, let data = imageData(withFormat: originalFormat) { + return data + } + + return original ?? image.kf.normalized.kf.pngRepresentation() + } + + /// Same implementation as `DefaultCacheSerializer`. + public func image(with data: Data, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } +} diff --git a/Pods/Kingfisher/Sources/Cache/ImageCache.swift b/Pods/Kingfisher/Sources/Cache/ImageCache.swift new file mode 100644 index 0000000..7d36654 --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/ImageCache.swift @@ -0,0 +1,875 @@ +// +// ImageCache.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension Notification.Name { + /// This notification will be sent when the disk cache got cleaned either there are cached files expired or the + /// total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger + /// this notification. + /// + /// The `object` of this notification is the `ImageCache` object which sends the notification. + /// A list of removed hashes (files) could be retrieved by accessing the array under + /// `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. + /// By checking the array, you could know the hash codes of files are removed. + public static let KingfisherDidCleanDiskCache = + Notification.Name("com.onevcat.Kingfisher.KingfisherDidCleanDiskCache") +} + +/// Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`. +public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash" + +/// Cache type of a cached image. +/// - none: The image is not cached yet when retrieving it. +/// - memory: The image is cached in memory. +/// - disk: The image is cached in disk. +public enum CacheType { + /// The image is not cached yet when retrieving it. + case none + /// The image is cached in memory. + case memory + /// The image is cached in disk. + case disk + + /// Whether the cache type represents the image is already cached or not. + public var cached: Bool { + switch self { + case .memory, .disk: return true + case .none: return false + } + } +} + +/// Represents the caching operation result. +public struct CacheStoreResult { + + /// The cache result for memory cache. Caching an image to memory will never fail. + public let memoryCacheResult: Result<(), Never> + + /// The cache result for disk cache. If an error happens during caching operation, + /// you can get it from `.failure` case of this `diskCacheResult`. + public let diskCacheResult: Result<(), KingfisherError> +} + +extension KFCrossPlatformImage: CacheCostCalculable { + /// Cost of an image + public var cacheCost: Int { return kf.cost } +} + +extension Data: DataTransformable { + public func toData() throws -> Data { + return self + } + + public static func fromData(_ data: Data) throws -> Data { + return data + } + + public static let empty = Data() +} + + +/// Represents the getting image operation from the cache. +/// +/// - disk: The image can be retrieved from disk cache. +/// - memory: The image can be retrieved memory cache. +/// - none: The image does not exist in the cache. +public enum ImageCacheResult { + + /// The image can be retrieved from disk cache. + case disk(KFCrossPlatformImage) + + /// The image can be retrieved memory cache. + case memory(KFCrossPlatformImage) + + /// The image does not exist in the cache. + case none + + /// Extracts the image from cache result. It returns the associated `Image` value for + /// `.disk` and `.memory` case. For `.none` case, `nil` is returned. + public var image: KFCrossPlatformImage? { + switch self { + case .disk(let image): return image + case .memory(let image): return image + case .none: return nil + } + } + + /// Returns the corresponding `CacheType` value based on the result type of `self`. + public var cacheType: CacheType { + switch self { + case .disk: return .disk + case .memory: return .memory + case .none: return .none + } + } +} + +/// Represents a hybrid caching system which is composed by a `MemoryStorage.Backend` and a `DiskStorage.Backend`. +/// `ImageCache` is a high level abstract for storing an image as well as its data to disk memory and disk, and +/// retrieving them back. +/// +/// While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create +/// your own cache object and configure its storages as your need. This class also provide an interface for you to set +/// the memory and disk storage config. +open class ImageCache { + + // MARK: Singleton + /// The default `ImageCache` object. Kingfisher will use this cache for its related methods if there is no + /// other cache specified. The `name` of this default cache is "default", and you should not use this name + /// for any of your customize cache. + public static let `default` = ImageCache(name: "default") + + + // MARK: Public Properties + /// The `MemoryStorage.Backend` object used in this cache. This storage holds loaded images in memory with a + /// reasonable expire duration and a maximum memory usage. To modify the configuration of a storage, just set + /// the storage `config` and its properties. + public let memoryStorage: MemoryStorage.Backend + + /// The `DiskStorage.Backend` object used in this cache. This storage stores loaded images in disk with a + /// reasonable expire duration and a maximum disk usage. To modify the configuration of a storage, just set + /// the storage `config` and its properties. + public let diskStorage: DiskStorage.Backend + + private let ioQueue: DispatchQueue + + /// Closure that defines the disk cache path from a given path and cacheName. + public typealias DiskCachePathClosure = (URL, String) -> URL + + // MARK: Initializers + + /// Creates an `ImageCache` from a customized `MemoryStorage` and `DiskStorage`. + /// + /// - Parameters: + /// - memoryStorage: The `MemoryStorage.Backend` object to use in the image cache. + /// - diskStorage: The `DiskStorage.Backend` object to use in the image cache. + public init( + memoryStorage: MemoryStorage.Backend, + diskStorage: DiskStorage.Backend) + { + self.memoryStorage = memoryStorage + self.diskStorage = diskStorage + let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue.\(UUID().uuidString)" + ioQueue = DispatchQueue(label: ioQueueName) + + let notifications: [(Notification.Name, Selector)] + #if !os(macOS) && !os(watchOS) + notifications = [ + (UIApplication.didReceiveMemoryWarningNotification, #selector(clearMemoryCache)), + (UIApplication.willTerminateNotification, #selector(cleanExpiredDiskCache)), + (UIApplication.didEnterBackgroundNotification, #selector(backgroundCleanExpiredDiskCache)) + ] + #elseif os(macOS) + notifications = [ + (NSApplication.willResignActiveNotification, #selector(cleanExpiredDiskCache)), + ] + #else + notifications = [] + #endif + notifications.forEach { + NotificationCenter.default.addObserver(self, selector: $0.1, name: $0.0, object: nil) + } + } + + /// Creates an `ImageCache` with a given `name`. Both `MemoryStorage` and `DiskStorage` will be created + /// with a default config based on the `name`. + /// + /// - Parameter name: The name of cache object. It is used to setup disk cache directories and IO queue. + /// You should not use the same `name` for different caches, otherwise, the disk storage would + /// be conflicting to each other. The `name` should not be an empty string. + public convenience init(name: String) { + self.init(noThrowName: name, cacheDirectoryURL: nil, diskCachePathClosure: nil) + } + + /// Creates an `ImageCache` with a given `name`, cache directory `path` + /// and a closure to modify the cache directory. + /// + /// - Parameters: + /// - name: The name of cache object. It is used to setup disk cache directories and IO queue. + /// You should not use the same `name` for different caches, otherwise, the disk storage would + /// be conflicting to each other. + /// - cacheDirectoryURL: Location of cache directory URL on disk. It will be internally pass to the + /// initializer of `DiskStorage` as the disk cache directory. If `nil`, the cache + /// directory under user domain mask will be used. + /// - diskCachePathClosure: Closure that takes in an optional initial path string and generates + /// the final disk cache path. You could use it to fully customize your cache path. + /// - Throws: An error that happens during image cache creating, such as unable to create a directory at the given + /// path. + public convenience init( + name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? = nil + ) throws + { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") + } + + let memoryStorage = ImageCache.createMemoryStorage() + + let config = ImageCache.createConfig( + name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure + ) + let diskStorage = try DiskStorage.Backend(config: config) + self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) + } + + convenience init( + noThrowName name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? + ) + { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.") + } + + let memoryStorage = ImageCache.createMemoryStorage() + + let config = ImageCache.createConfig( + name: name, cacheDirectoryURL: cacheDirectoryURL, diskCachePathClosure: diskCachePathClosure + ) + let diskStorage = DiskStorage.Backend(noThrowConfig: config, creatingDirectory: true) + self.init(memoryStorage: memoryStorage, diskStorage: diskStorage) + } + + private static func createMemoryStorage() -> MemoryStorage.Backend { + let totalMemory = ProcessInfo.processInfo.physicalMemory + let costLimit = totalMemory / 4 + let memoryStorage = MemoryStorage.Backend(config: + .init(totalCostLimit: (costLimit > Int.max) ? Int.max : Int(costLimit))) + return memoryStorage + } + + private static func createConfig( + name: String, + cacheDirectoryURL: URL?, + diskCachePathClosure: DiskCachePathClosure? = nil + ) -> DiskStorage.Config + { + var diskConfig = DiskStorage.Config( + name: name, + sizeLimit: 0, + directory: cacheDirectoryURL + ) + if let closure = diskCachePathClosure { + diskConfig.cachePathBlock = closure + } + return diskConfig + } + + deinit { + NotificationCenter.default.removeObserver(self) + } + + // MARK: Storing Images + + open func store(_ image: KFCrossPlatformImage, + original: Data? = nil, + forKey key: String, + options: KingfisherParsedOptionsInfo, + toDisk: Bool = true, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + let identifier = options.processor.identifier + let callbackQueue = options.callbackQueue + + let computedKey = key.computedKey(with: identifier) + // Memory storage should not throw. + memoryStorage.storeNoThrow(value: image, forKey: computedKey, expiration: options.memoryCacheExpiration) + + guard toDisk else { + if let completionHandler = completionHandler { + let result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) + callbackQueue.execute { completionHandler(result) } + } + return + } + + ioQueue.async { + let serializer = options.cacheSerializer + if let data = serializer.data(with: image, original: original) { + self.syncStoreToDisk( + data, + forKey: key, + processorIdentifier: identifier, + callbackQueue: callbackQueue, + expiration: options.diskCacheExpiration, + writeOptions: options.diskStoreWriteOptions, + completionHandler: completionHandler) + } else { + guard let completionHandler = completionHandler else { return } + + let diskError = KingfisherError.cacheError( + reason: .cannotSerializeImage(image: image, original: original, serializer: serializer)) + let result = CacheStoreResult( + memoryCacheResult: .success(()), + diskCacheResult: .failure(diskError)) + callbackQueue.execute { completionHandler(result) } + } + } + } + + /// Stores an image to the cache. + /// + /// - Parameters: + /// - image: The image to be stored. + /// - original: The original data of the image. This value will be forwarded to the provided `serializer` for + /// further use. By default, Kingfisher uses a `DefaultCacheSerializer` to serialize the image to + /// data for caching in disk, it checks the image format based on `original` data to determine in + /// which image format should be used. For other types of `serializer`, it depends on their + /// implementation detail on how to use this original data. + /// - key: The key used for caching the image. + /// - identifier: The identifier of processor being used for caching. If you are using a processor for the + /// image, pass the identifier of processor to this parameter. + /// - serializer: The `CacheSerializer` + /// - toDisk: Whether this image should be cached to disk or not. If `false`, the image is only cached in memory. + /// Otherwise, it is cached in both memory storage and disk storage. Default is `true`. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. For case + /// that `toDisk` is `false`, a `.untouch` queue means `callbackQueue` will be invoked from the + /// caller queue of this method. If `toDisk` is `true`, the `completionHandler` will be called + /// from an internal file IO queue. To change this behavior, specify another `CallbackQueue` + /// value. + /// - completionHandler: A closure which is invoked when the cache operation finishes. + open func store(_ image: KFCrossPlatformImage, + original: Data? = nil, + forKey key: String, + processorIdentifier identifier: String = "", + cacheSerializer serializer: CacheSerializer = DefaultCacheSerializer.default, + toDisk: Bool = true, + callbackQueue: CallbackQueue = .untouch, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + struct TempProcessor: ImageProcessor { + let identifier: String + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return nil + } + } + + let options = KingfisherParsedOptionsInfo([ + .processor(TempProcessor(identifier: identifier)), + .cacheSerializer(serializer), + .callbackQueue(callbackQueue) + ]) + store(image, original: original, forKey: key, options: options, + toDisk: toDisk, completionHandler: completionHandler) + } + + open func storeToDisk( + _ data: Data, + forKey key: String, + processorIdentifier identifier: String = "", + expiration: StorageExpiration? = nil, + callbackQueue: CallbackQueue = .untouch, + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + ioQueue.async { + self.syncStoreToDisk( + data, + forKey: key, + processorIdentifier: identifier, + callbackQueue: callbackQueue, + expiration: expiration, + completionHandler: completionHandler) + } + } + + private func syncStoreToDisk( + _ data: Data, + forKey key: String, + processorIdentifier identifier: String = "", + callbackQueue: CallbackQueue = .untouch, + expiration: StorageExpiration? = nil, + writeOptions: Data.WritingOptions = [], + completionHandler: ((CacheStoreResult) -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + let result: CacheStoreResult + do { + try self.diskStorage.store(value: data, forKey: computedKey, expiration: expiration, writeOptions: writeOptions) + result = CacheStoreResult(memoryCacheResult: .success(()), diskCacheResult: .success(())) + } catch { + let diskError: KingfisherError + if let error = error as? KingfisherError { + diskError = error + } else { + diskError = .cacheError(reason: .cannotConvertToData(object: data, error: error)) + } + + result = CacheStoreResult( + memoryCacheResult: .success(()), + diskCacheResult: .failure(diskError) + ) + } + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler(result) } + } + } + + // MARK: Removing Images + + /// Removes the image for the given key from the cache. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: The identifier of processor being used for caching. If you are using a processor for the + /// image, pass the identifier of processor to this parameter. + /// - fromMemory: Whether this image should be removed from memory storage or not. + /// If `false`, the image won't be removed from the memory storage. Default is `true`. + /// - fromDisk: Whether this image should be removed from disk storage or not. + /// If `false`, the image won't be removed from the disk storage. Default is `true`. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. + /// - completionHandler: A closure which is invoked when the cache removing operation finishes. + open func removeImage(forKey key: String, + processorIdentifier identifier: String = "", + fromMemory: Bool = true, + fromDisk: Bool = true, + callbackQueue: CallbackQueue = .untouch, + completionHandler: (() -> Void)? = nil) + { + let computedKey = key.computedKey(with: identifier) + + if fromMemory { + memoryStorage.remove(forKey: computedKey) + } + + if fromDisk { + ioQueue.async{ + try? self.diskStorage.remove(forKey: computedKey) + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler() } + } + } + } else { + if let completionHandler = completionHandler { + callbackQueue.execute { completionHandler() } + } + } + } + + // MARK: Getting Images + + /// Gets an image for a given key from the cache, either from memory storage or disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. + /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the + /// image retrieving operation finishes without problem, an `ImageCacheResult` value + /// will be sent to this closure as result. Otherwise, a `KingfisherError` result + /// with detail failing reason will be sent. + open func retrieveImage( + forKey key: String, + options: KingfisherParsedOptionsInfo, + callbackQueue: CallbackQueue = .mainCurrentOrAsync, + completionHandler: ((Result) -> Void)?) + { + // No completion handler. No need to start working and early return. + guard let completionHandler = completionHandler else { return } + + // Try to check the image from memory cache first. + if let image = retrieveImageInMemoryCache(forKey: key, options: options) { + callbackQueue.execute { completionHandler(.success(.memory(image))) } + } else if options.fromMemoryCacheOrRefresh { + callbackQueue.execute { completionHandler(.success(.none)) } + } else { + + // Begin to disk search. + self.retrieveImageInDiskCache(forKey: key, options: options, callbackQueue: callbackQueue) { + result in + switch result { + case .success(let image): + + guard let image = image else { + // No image found in disk storage. + callbackQueue.execute { completionHandler(.success(.none)) } + return + } + + // Cache the disk image to memory. + // We are passing `false` to `toDisk`, the memory cache does not change + // callback queue, we can call `completionHandler` without another dispatch. + var cacheOptions = options + cacheOptions.callbackQueue = .untouch + self.store( + image, + forKey: key, + options: cacheOptions, + toDisk: false) + { + _ in + callbackQueue.execute { completionHandler(.success(.disk(image))) } + } + case .failure(let error): + callbackQueue.execute { completionHandler(.failure(error)) } + } + } + } + } + + /// Gets an image for a given key from the cache, either from memory storage or disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.mainCurrentOrAsync`. + /// - completionHandler: A closure which is invoked when the image getting operation finishes. If the + /// image retrieving operation finishes without problem, an `ImageCacheResult` value + /// will be sent to this closure as result. Otherwise, a `KingfisherError` result + /// with detail failing reason will be sent. + /// + /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override + /// the version receives `KingfisherParsedOptionsInfo` instead. + open func retrieveImage(forKey key: String, + options: KingfisherOptionsInfo? = nil, + callbackQueue: CallbackQueue = .mainCurrentOrAsync, + completionHandler: ((Result) -> Void)?) + { + retrieveImage( + forKey: key, + options: KingfisherParsedOptionsInfo(options), + callbackQueue: callbackQueue, + completionHandler: completionHandler) + } + + /// Gets an image for a given key from the memory storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherParsedOptionsInfo` options setting used for retrieving the image. + /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or + /// has already expired, `nil` is returned. + open func retrieveImageInMemoryCache( + forKey key: String, + options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? + { + let computedKey = key.computedKey(with: options.processor.identifier) + return memoryStorage.value(forKey: computedKey, extendingExpiration: options.memoryCacheAccessExtendingExpiration) + } + + /// Gets an image for a given key from the memory storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - Returns: The image stored in memory cache, if exists and valid. Otherwise, if the image does not exist or + /// has already expired, `nil` is returned. + /// + /// Note: This method is marked as `open` for only compatible purpose. Do not overide this method. Instead, override + /// the version receives `KingfisherParsedOptionsInfo` instead. + open func retrieveImageInMemoryCache( + forKey key: String, + options: KingfisherOptionsInfo? = nil) -> KFCrossPlatformImage? + { + return retrieveImageInMemoryCache(forKey: key, options: KingfisherParsedOptionsInfo(options)) + } + + func retrieveImageInDiskCache( + forKey key: String, + options: KingfisherParsedOptionsInfo, + callbackQueue: CallbackQueue = .untouch, + completionHandler: @escaping (Result) -> Void) + { + let computedKey = key.computedKey(with: options.processor.identifier) + let loadingQueue: CallbackQueue = options.loadDiskFileSynchronously ? .untouch : .dispatch(ioQueue) + loadingQueue.execute { + do { + var image: KFCrossPlatformImage? = nil + if let data = try self.diskStorage.value(forKey: computedKey, extendingExpiration: options.diskCacheAccessExtendingExpiration) { + image = options.cacheSerializer.image(with: data, options: options) + } + callbackQueue.execute { completionHandler(.success(image)) } + } catch { + if let error = error as? KingfisherError { + callbackQueue.execute { completionHandler(.failure(error)) } + } else { + assertionFailure("The internal thrown error should be a `KingfisherError`.") + } + } + } + } + + /// Gets an image for a given key from the disk storage. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - options: The `KingfisherOptionsInfo` options setting used for retrieving the image. + /// - callbackQueue: The callback queue on which `completionHandler` is invoked. Default is `.untouch`. + /// - completionHandler: A closure which is invoked when the operation finishes. + open func retrieveImageInDiskCache( + forKey key: String, + options: KingfisherOptionsInfo? = nil, + callbackQueue: CallbackQueue = .untouch, + completionHandler: @escaping (Result) -> Void) + { + retrieveImageInDiskCache( + forKey: key, + options: KingfisherParsedOptionsInfo(options), + callbackQueue: callbackQueue, + completionHandler: completionHandler) + } + + // MARK: Cleaning + /// Clears the memory & disk storage of this cache. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + public func clearCache(completion handler: (() -> Void)? = nil) { + clearMemoryCache() + clearDiskCache(completion: handler) + } + + /// Clears the memory storage of this cache. + @objc public func clearMemoryCache() { + memoryStorage.removeAll() + } + + /// Clears the disk storage of this cache. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + open func clearDiskCache(completion handler: (() -> Void)? = nil) { + ioQueue.async { + do { + try self.diskStorage.removeAll() + } catch _ { } + if let handler = handler { + DispatchQueue.main.async { handler() } + } + } + } + + /// Clears the expired images from memory & disk storage. This is an async operation. + open func cleanExpiredCache(completion handler: (() -> Void)? = nil) { + cleanExpiredMemoryCache() + cleanExpiredDiskCache(completion: handler) + } + + /// Clears the expired images from disk storage. + open func cleanExpiredMemoryCache() { + memoryStorage.removeExpired() + } + + /// Clears the expired images from disk storage. This is an async operation. + @objc func cleanExpiredDiskCache() { + cleanExpiredDiskCache(completion: nil) + } + + /// Clears the expired images from disk storage. This is an async operation. + /// + /// - Parameter handler: A closure which is invoked when the cache clearing operation finishes. + /// This `handler` will be called from the main queue. + open func cleanExpiredDiskCache(completion handler: (() -> Void)? = nil) { + ioQueue.async { + do { + var removed: [URL] = [] + let removedExpired = try self.diskStorage.removeExpiredValues() + removed.append(contentsOf: removedExpired) + + let removedSizeExceeded = try self.diskStorage.removeSizeExceededValues() + removed.append(contentsOf: removedSizeExceeded) + + if !removed.isEmpty { + DispatchQueue.main.async { + let cleanedHashes = removed.map { $0.lastPathComponent } + NotificationCenter.default.post( + name: .KingfisherDidCleanDiskCache, + object: self, + userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes]) + } + } + + if let handler = handler { + DispatchQueue.main.async { handler() } + } + } catch {} + } + } + +#if !os(macOS) && !os(watchOS) + /// Clears the expired images from disk storage when app is in background. This is an async operation. + /// In most cases, you should not call this method explicitly. + /// It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received. + @objc public func backgroundCleanExpiredDiskCache() { + // if 'sharedApplication()' is unavailable, then return + guard let sharedApplication = KingfisherWrapper.shared else { return } + + func endBackgroundTask(_ task: inout UIBackgroundTaskIdentifier) { + sharedApplication.endBackgroundTask(task) + task = UIBackgroundTaskIdentifier.invalid + } + + var backgroundTask: UIBackgroundTaskIdentifier! + backgroundTask = sharedApplication.beginBackgroundTask { + endBackgroundTask(&backgroundTask!) + } + + cleanExpiredDiskCache { + endBackgroundTask(&backgroundTask!) + } + } +#endif + + // MARK: Image Cache State + + /// Returns the cache type for a given `key` and `identifier` combination. + /// This method is used for checking whether an image is cached in current cache. + /// It also provides information on which kind of cache can it be found in the return value. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: A `CacheType` instance which indicates the cache status. + /// `.none` means the image is not in cache or it is already expired. + open func imageCachedType( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> CacheType + { + let computedKey = key.computedKey(with: identifier) + if memoryStorage.isCached(forKey: computedKey) { return .memory } + if diskStorage.isCached(forKey: computedKey) { return .disk } + return .none + } + + /// Returns whether the file exists in cache for a given `key` and `identifier` combination. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: A `Bool` which indicates whether a cache could match the given `key` and `identifier` combination. + /// + /// - Note: + /// The return value does not contain information about from which kind of storage the cache matches. + /// To get the information about cache type according `CacheType`, + /// use `imageCachedType(forKey:processorIdentifier:)` instead. + public func isCached( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> Bool + { + return imageCachedType(forKey: key, processorIdentifier: identifier).cached + } + + /// Gets the hash used as cache file name for the key. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: The hash which is used as the cache file name. + /// + /// - Note: + /// By default, for a given combination of `key` and `identifier`, `ImageCache` will use the value + /// returned by this method as the cache file name. You can use this value to check and match cache file + /// if you need. + open func hash( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String + { + let computedKey = key.computedKey(with: identifier) + return diskStorage.cacheFileName(forKey: computedKey) + } + + /// Calculates the size taken by the disk storage. + /// It is the total file size of all cached files in the `diskStorage` on disk in bytes. + /// + /// - Parameter handler: Called with the size calculating finishes. This closure is invoked from the main queue. + open func calculateDiskStorageSize(completion handler: @escaping ((Result) -> Void)) { + ioQueue.async { + do { + let size = try self.diskStorage.totalSize() + DispatchQueue.main.async { handler(.success(size)) } + } catch { + if let error = error as? KingfisherError { + DispatchQueue.main.async { handler(.failure(error)) } + } else { + assertionFailure("The internal thrown error should be a `KingfisherError`.") + } + + } + } + } + + /// Gets the cache path for the key. + /// It is useful for projects with web view or anyone that needs access to the local file path. + /// + /// i.e. Replacing the `` tag in your HTML. + /// + /// - Parameters: + /// - key: The key used for caching the image. + /// - identifier: Processor identifier which used for this image. Default is the `identifier` of + /// `DefaultImageProcessor.default`. + /// - Returns: The disk path of cached image under the given `key` and `identifier`. + /// + /// - Note: + /// This method does not guarantee there is an image already cached in the returned path. It just gives your + /// the path that the image should be, if it exists in disk storage. + /// + /// You could use `isCached(forKey:)` method to check whether the image is cached under that key in disk. + open func cachePath( + forKey key: String, + processorIdentifier identifier: String = DefaultImageProcessor.default.identifier) -> String + { + let computedKey = key.computedKey(with: identifier) + return diskStorage.cacheFileURL(forKey: computedKey).path + } +} + +extension Dictionary { + func keysSortedByValue(_ isOrderedBefore: (Value, Value) -> Bool) -> [Key] { + return Array(self).sorted{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 } + } +} + +#if !os(macOS) && !os(watchOS) +// MARK: - For App Extensions +extension UIApplication: KingfisherCompatible { } +extension KingfisherWrapper where Base: UIApplication { + public static var shared: UIApplication? { + let selector = NSSelectorFromString("sharedApplication") + guard Base.responds(to: selector) else { return nil } + return Base.perform(selector).takeUnretainedValue() as? UIApplication + } +} +#endif + +extension String { + func computedKey(with identifier: String) -> String { + if identifier.isEmpty { + return self + } else { + return appending("@\(identifier)") + } + } +} diff --git a/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift new file mode 100644 index 0000000..f74220b --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/MemoryStorage.swift @@ -0,0 +1,244 @@ +// +// MemoryStorage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a set of conception related to storage which stores a certain type of value in memory. +/// This is a namespace for the memory storage types. A `Backend` with a certain `Config` will be used to describe the +/// storage. See these composed types for more information. +public enum MemoryStorage { + + /// Represents a storage which stores a certain type of value in memory. It provides fast access, + /// but limited storing size. The stored value type needs to conform to `CacheCostCalculable`, + /// and its `cacheCost` will be used to determine the cost of size for the cache item. + /// + /// You can config a `MemoryStorage.Backend` in its initializer by passing a `MemoryStorage.Config` value. + /// or modifying the `config` property after it being created. The backend of `MemoryStorage` has + /// upper limitation on cost size in memory and item count. All items in the storage has an expiration + /// date. When retrieved, if the target item is already expired, it will be recognized as it does not + /// exist in the storage. The `MemoryStorage` also contains a scheduled self clean task, to evict expired + /// items from memory. + public class Backend { + let storage = NSCache>() + + // Keys trackes the objects once inside the storage. For object removing triggered by user, the corresponding + // key would be also removed. However, for the object removing triggered by cache rule/policy of system, the + // key will be remained there until next `removeExpired` happens. + // + // Breaking the strict tracking could save additional locking behaviors. + // See https://github.com/onevcat/Kingfisher/issues/1233 + var keys = Set() + + private var cleanTimer: Timer? = nil + private let lock = NSLock() + + /// The config used in this storage. It is a value you can set and + /// use to config the storage in air. + public var config: Config { + didSet { + storage.totalCostLimit = config.totalCostLimit + storage.countLimit = config.countLimit + } + } + + /// Creates a `MemoryStorage` with a given `config`. + /// + /// - Parameter config: The config used to create the storage. It determines the max size limitation, + /// default expiration setting and more. + public init(config: Config) { + self.config = config + storage.totalCostLimit = config.totalCostLimit + storage.countLimit = config.countLimit + + cleanTimer = .scheduledTimer(withTimeInterval: config.cleanInterval, repeats: true) { [weak self] _ in + guard let self = self else { return } + self.removeExpired() + } + } + + /// Removes the expired values from the storage. + public func removeExpired() { + lock.lock() + defer { lock.unlock() } + for key in keys { + let nsKey = key as NSString + guard let object = storage.object(forKey: nsKey) else { + // This could happen if the object is moved by cache `totalCostLimit` or `countLimit` rule. + // We didn't remove the key yet until now, since we do not want to introduce additional lock. + // See https://github.com/onevcat/Kingfisher/issues/1233 + keys.remove(key) + continue + } + if object.estimatedExpiration.isPast { + storage.removeObject(forKey: nsKey) + keys.remove(key) + } + } + } + + /// Stores a value to the storage under the specified key and expiration policy. + /// - Parameters: + /// - value: The value to be stored. + /// - key: The key to which the `value` will be stored. + /// - expiration: The expiration policy used by this store action. + /// - Throws: No error will + public func store( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) + { + storeNoThrow(value: value, forKey: key, expiration: expiration) + } + + // The no throw version for storing value in cache. Kingfisher knows the detail so it + // could use this version to make syntax simpler internally. + func storeNoThrow( + value: T, + forKey key: String, + expiration: StorageExpiration? = nil) + { + lock.lock() + defer { lock.unlock() } + let expiration = expiration ?? config.expiration + // The expiration indicates that already expired, no need to store. + guard !expiration.isExpired else { return } + + let object = StorageObject(value, key: key, expiration: expiration) + storage.setObject(object, forKey: key as NSString, cost: value.cacheCost) + keys.insert(key) + } + + /// Gets a value from the storage. + /// + /// - Parameters: + /// - key: The cache key of value. + /// - extendingExpiration: The expiration policy used by this getting action. + /// - Returns: The value under `key` if it is valid and found in the storage. Otherwise, `nil`. + public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) -> T? { + guard let object = storage.object(forKey: key as NSString) else { + return nil + } + if object.expired { + return nil + } + object.extendExpiration(extendingExpiration) + return object.value + } + + /// Whether there is valid cached data under a given key. + /// - Parameter key: The cache key of value. + /// - Returns: If there is valid data under the key, `true`. Otherwise, `false`. + public func isCached(forKey key: String) -> Bool { + guard let _ = value(forKey: key, extendingExpiration: .none) else { + return false + } + return true + } + + /// Removes a value from a specified key. + /// - Parameter key: The cache key of value. + public func remove(forKey key: String) { + lock.lock() + defer { lock.unlock() } + storage.removeObject(forKey: key as NSString) + keys.remove(key) + } + + /// Removes all values in this storage. + public func removeAll() { + lock.lock() + defer { lock.unlock() } + storage.removeAllObjects() + keys.removeAll() + } + } +} + +extension MemoryStorage { + /// Represents the config used in a `MemoryStorage`. + public struct Config { + + /// Total cost limit of the storage in bytes. + public var totalCostLimit: Int + + /// The item count limit of the memory storage. + public var countLimit: Int = .max + + /// The `StorageExpiration` used in this memory storage. Default is `.seconds(300)`, + /// means that the memory cache would expire in 5 minutes. + public var expiration: StorageExpiration = .seconds(300) + + /// The time interval between the storage do clean work for swiping expired items. + public let cleanInterval: TimeInterval + + /// Creates a config from a given `totalCostLimit` value. + /// + /// - Parameters: + /// - totalCostLimit: Total cost limit of the storage in bytes. + /// - cleanInterval: The time interval between the storage do clean work for swiping expired items. + /// Default is 120, means the auto eviction happens once per two minutes. + /// + /// - Note: + /// Other members of `MemoryStorage.Config` will use their default values when created. + public init(totalCostLimit: Int, cleanInterval: TimeInterval = 120) { + self.totalCostLimit = totalCostLimit + self.cleanInterval = cleanInterval + } + } +} + +extension MemoryStorage { + class StorageObject { + let value: T + let expiration: StorageExpiration + let key: String + + private(set) var estimatedExpiration: Date + + init(_ value: T, key: String, expiration: StorageExpiration) { + self.value = value + self.key = key + self.expiration = expiration + + self.estimatedExpiration = expiration.estimatedExpirationSinceNow + } + + func extendExpiration(_ extendingExpiration: ExpirationExtending = .cacheTime) { + switch extendingExpiration { + case .none: + return + case .cacheTime: + self.estimatedExpiration = expiration.estimatedExpirationSinceNow + case .expirationTime(let expirationTime): + self.estimatedExpiration = expirationTime.estimatedExpirationSinceNow + } + } + + var expired: Bool { + return estimatedExpiration.isPast + } + } +} diff --git a/Pods/Kingfisher/Sources/Cache/Storage.swift b/Pods/Kingfisher/Sources/Cache/Storage.swift new file mode 100644 index 0000000..ca0f8bb --- /dev/null +++ b/Pods/Kingfisher/Sources/Cache/Storage.swift @@ -0,0 +1,113 @@ +// +// Storage.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Constants for some time intervals +struct TimeConstants { + static let secondsInOneMinute = 60 + static let minutesInOneHour = 60 + static let hoursInOneDay = 24 + static let secondsInOneDay = 86_400 +} + +/// Represents the expiration strategy used in storage. +/// +/// - never: The item never expires. +/// - seconds: The item expires after a time duration of given seconds from now. +/// - days: The item expires after a time duration of given days from now. +/// - date: The item expires after a given date. +public enum StorageExpiration { + /// The item never expires. + case never + /// The item expires after a time duration of given seconds from now. + case seconds(TimeInterval) + /// The item expires after a time duration of given days from now. + case days(Int) + /// The item expires after a given date. + case date(Date) + /// Indicates the item is already expired. Use this to skip cache. + case expired + + func estimatedExpirationSince(_ date: Date) -> Date { + switch self { + case .never: return .distantFuture + case .seconds(let seconds): + return date.addingTimeInterval(seconds) + case .days(let days): + let duration: TimeInterval = TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days) + return date.addingTimeInterval(duration) + case .date(let ref): + return ref + case .expired: + return .distantPast + } + } + + var estimatedExpirationSinceNow: Date { + return estimatedExpirationSince(Date()) + } + + var isExpired: Bool { + return timeInterval <= 0 + } + + var timeInterval: TimeInterval { + switch self { + case .never: return .infinity + case .seconds(let seconds): return seconds + case .days(let days): return TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days) + case .date(let ref): return ref.timeIntervalSinceNow + case .expired: return -(.infinity) + } + } +} + +/// Represents the expiration extending strategy used in storage to after access. +/// +/// - none: The item expires after the original time, without extending after access. +/// - cacheTime: The item expiration extends by the original cache time after each access. +/// - expirationTime: The item expiration extends by the provided time after each access. +public enum ExpirationExtending { + /// The item expires after the original time, without extending after access. + case none + /// The item expiration extends by the original cache time after each access. + case cacheTime + /// The item expiration extends by the provided time after each access. + case expirationTime(_ expiration: StorageExpiration) +} + +/// Represents types which cost in memory can be calculated. +public protocol CacheCostCalculable { + var cacheCost: Int { get } +} + +/// Represents types which can be converted to and from data. +public protocol DataTransformable { + func toData() throws -> Data + static func fromData(_ data: Data) throws -> Self + static var empty: Self { get } +} diff --git a/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift new file mode 100644 index 0000000..f0b7946 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/CPListItem+Kingfisher.swift @@ -0,0 +1,258 @@ + +// +// CPListItem+Kingfisher.swift +// Kingfisher +// +// Created by Wayne Hartman on 2021-08-29. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(CarPlay) +import CarPlay + +@available(iOS 14.0, *) +extension KingfisherWrapper where Base: CPListItem { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? [])) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(placeholder) + #else + if let placeholder = placeholder { + self.base.setImage(placeholder) + } + #endif + + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(placeholder) + #else // Let older SDK users deal with the older behavior. + if let placeholder = placeholder { + self.base.setImage(placeholder) + } + #endif + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setImage(image) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.setImage(value.image) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + /** + * In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5 + * to allow `nil`. The compiler version 5.4 was introduced in this same SDK, + * which allows >=14.5 SDK to set a `nil` image. This compile check allows + * newer SDK users to set the image to `nil`, while still allowing older SDK + * users to compile the framework. + */ + #if compiler(>=5.4) + self.base.setImage(image) + #else // Let older SDK users deal with the older behavior. + if let unwrapped = image { + self.base.setImage(unwrapped) + } + #endif + + } else { + #if compiler(>=5.4) + self.base.setImage(nil) + #endif + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: CPListItem { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift new file mode 100644 index 0000000..79c33c0 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/ImageView+Kingfisher.swift @@ -0,0 +1,544 @@ +// +// ImageView+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + + // MARK: Setting Image + + /// Sets an image to the image view with a `Source`. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code + /// above is equivalent to: + /// + /// ``` + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage(with: source, placeholder: placeholder, parsedOptions: options, progressBlock: progressBlock, completionHandler: completionHandler) + } + + /// Sets an image to the image view with a `Source`. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from a source. Since all parameters + /// have a default value except the `source`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// // Set image from a network source. + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: .network(url)) + /// + /// // Or set image from a data provider. + /// let provider = LocalFileImageDataProvider(fileURL: fileURL) + /// imageView.kf.setImage(with: .provider(provider)) + /// ``` + /// + /// For both `.network` and `.provider` source, there are corresponding view extension methods. So the code + /// above is equivalent to: + /// + /// ``` + /// imageView.kf.setImage(with: url) + /// imageView.kf.setImage(with: provider) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: source, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters + /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// This is the easiest way to use Kingfisher to boost the image setting process from network. Since all parameters + /// have a default value except the `resource`, you can set an image from a certain URL to an image view like this: + /// + /// ``` + /// let url = URL(string: "https://example.com/image.png")! + /// imageView.kf.setImage(with: url) + /// ``` + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a data provider. + /// + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// Internally, this method will use `KingfisherManager` to get the image data, from either cache + /// or the data provider. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: provider.map { .provider($0) }, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Sets an image to the image view with a data provider. + /// + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// Internally, this method will use `KingfisherManager` to get the image data, from either cache + /// or the data provider. Since this method will perform UI changes, you must call it from the main thread. + /// The `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with provider: ImageDataProvider?, + placeholder: Placeholder? = nil, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: provider, + placeholder: placeholder, + options: options, + progressBlock: nil, + completionHandler: completionHandler + ) + } + + + func setImage( + with source: Source?, + placeholder: Placeholder? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + mutatingSelf.placeholder = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + + let isEmptyImage = base.image == nil && self.placeholder == nil + if !options.keepCurrentImageWhileLoading || isEmptyImage { + // Always set placeholder while there is no image/placeholder yet. + mutatingSelf.placeholder = placeholder + } + + let maybeIndicator = indicator + maybeIndicator?.startAnimatingView() + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if base.shouldPreloadAllAnimation() { + options.preloadAllAnimationData = true + } + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + maybeIndicator?.stopAnimatingView() + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + guard self.needsTransition(options: options, cacheType: value.cacheType) else { + mutatingSelf.placeholder = nil + self.base.image = value.image + completionHandler?(result) + return + } + + self.makeTransition(image: value.image, transition: options.transition) { + completionHandler?(result) + } + + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } + + private func needsTransition(options: KingfisherParsedOptionsInfo, cacheType: CacheType) -> Bool { + switch options.transition { + case .none: + return false + #if os(macOS) + case .fade: // Fade is only a placeholder for SwiftUI on macOS. + return false + #else + default: + if options.forceTransition { return true } + if cacheType == .none { return true } + return false + #endif + } + } + + private func makeTransition(image: KFCrossPlatformImage, transition: ImageTransition, done: @escaping () -> Void) { + #if !os(macOS) + // Force hiding the indicator without transition first. + UIView.transition( + with: self.base, + duration: 0.0, + options: [], + animations: { self.indicator?.stopAnimatingView() }, + completion: { _ in + var mutatingSelf = self + mutatingSelf.placeholder = nil + UIView.transition( + with: self.base, + duration: transition.duration, + options: [transition.animationOptions, .allowUserInteraction], + animations: { transition.animations?(self.base, image) }, + completion: { finished in + transition.completion?(finished) + done() + } + ) + } + ) + #else + done() + #endif + } +} + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var indicatorKey: Void? +private var indicatorTypeKey: Void? +private var placeholderKey: Void? +private var imageTaskKey: Void? + +extension KingfisherWrapper where Base: KFCrossPlatformImageView { + + // MARK: Properties + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + /// Holds which indicator type is going to be used. + /// Default is `.none`, means no indicator will be shown while downloading. + public var indicatorType: IndicatorType { + get { + return getAssociatedObject(base, &indicatorTypeKey) ?? .none + } + + set { + switch newValue { + case .none: indicator = nil + case .activity: indicator = ActivityIndicator() + case .image(let data): indicator = ImageIndicator(imageData: data) + case .custom(let anIndicator): indicator = anIndicator + } + + setRetainedAssociatedObject(base, &indicatorTypeKey, newValue) + } + } + + /// Holds any type that conforms to the protocol `Indicator`. + /// The protocol `Indicator` has a `view` property that will be shown when loading an image. + /// It will be `nil` if `indicatorType` is `.none`. + public private(set) var indicator: Indicator? { + get { + let box: Box? = getAssociatedObject(base, &indicatorKey) + return box?.value + } + + set { + // Remove previous + if let previousIndicator = indicator { + previousIndicator.view.removeFromSuperview() + } + + // Add new + if let newIndicator = newValue { + // Set default indicator layout + let view = newIndicator.view + + base.addSubview(view) + view.translatesAutoresizingMaskIntoConstraints = false + view.centerXAnchor.constraint( + equalTo: base.centerXAnchor, constant: newIndicator.centerOffset.x).isActive = true + view.centerYAnchor.constraint( + equalTo: base.centerYAnchor, constant: newIndicator.centerOffset.y).isActive = true + + switch newIndicator.sizeStrategy(in: base) { + case .intrinsicSize: + break + case .full: + view.heightAnchor.constraint(equalTo: base.heightAnchor, constant: 0).isActive = true + view.widthAnchor.constraint(equalTo: base.widthAnchor, constant: 0).isActive = true + case .size(let size): + view.heightAnchor.constraint(equalToConstant: size.height).isActive = true + view.widthAnchor.constraint(equalToConstant: size.width).isActive = true + } + + newIndicator.view.isHidden = true + } + + // Save in associated object + // Wrap newValue with Box to workaround an issue that Swift does not recognize + // and casting protocol for associate object correctly. https://github.com/onevcat/Kingfisher/issues/872 + setRetainedAssociatedObject(base, &indicatorKey, newValue.map(Box.init)) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } + + /// Represents the `Placeholder` used for this image view. A `Placeholder` will be shown in the view while + /// it is downloading an image. + public private(set) var placeholder: Placeholder? { + get { return getAssociatedObject(base, &placeholderKey) } + set { + if let previousPlaceholder = placeholder { + previousPlaceholder.remove(from: base) + } + + if let newPlaceholder = newValue { + newPlaceholder.add(to: base) + } else { + base.image = nil + } + setRetainedAssociatedObject(base, &placeholderKey, newValue) + } + } +} + + +extension KFCrossPlatformImageView { + @objc func shouldPreloadAllAnimation() -> Bool { return true } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift new file mode 100644 index 0000000..566eb1e --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/NSButton+Kingfisher.swift @@ -0,0 +1,370 @@ +// +// NSButton+Kingfisher.swift +// Kingfisher +// +// Created by Jie Zhang on 14/04/2016. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension KingfisherWrapper where Base: NSButton { + + // MARK: Setting Image + + /// Sets an image to the button with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about how to get the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source. + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the button with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelImageDownloadTask() { + imageTask?.cancel() + } + + // MARK: Setting Alternate Image + + @discardableResult + public func setAlternateImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setAlternateImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an alternate image to the button with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setAlternateImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setAlternateImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setAlternateImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.alternateImage = placeholder + mutatingSelf.alternateTaskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.alternateImage = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.alternateTaskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.alternateImage = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.alternateTaskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.alternateImageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.alternateTaskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.alternateImageTask = nil + mutatingSelf.alternateTaskIdentifier = nil + + switch result { + case .success(let value): + self.base.alternateImage = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.alternateImage = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.alternateImageTask = task + return task + } + + // MARK: Cancelling Alternate Image Downloading Task + + /// Cancels the alternate image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelAlternateImageDownloadTask() { + alternateImageTask?.cancel() + } +} + + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +private var alternateTaskIdentifierKey: Void? +private var alternateImageTaskKey: Void? + +extension KingfisherWrapper where Base: NSButton { + + // MARK: Properties + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } + + public private(set) var alternateTaskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &alternateTaskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &alternateTaskIdentifierKey, box) + } + } + + private var alternateImageTask: DownloadTask? { + get { return getAssociatedObject(base, &alternateImageTaskKey) } + set { setRetainedAssociatedObject(base, &alternateImageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift new file mode 100644 index 0000000..adb5490 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/NSTextAttachment+Kingfisher.swift @@ -0,0 +1,279 @@ +// +// NSTextAttachment+Kingfisher.swift +// Kingfisher +// +// Created by Benjamin Briggs on 22/07/2019. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +extension KingfisherWrapper where Base: NSTextAttachment { + + // MARK: Setting Image + + /// Sets an image to the text attachment with a source. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// + /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based + /// rendering, options related to view, such as `.transition`, are not supported. + /// + /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a + /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an + /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. + /// + /// Here is a typical use case: + /// + /// ```swift + /// let attributedText = NSMutableAttributedString(string: "Hello World") + /// let textAttachment = NSTextAttachment() + /// + /// textAttachment.kf.setImage( + /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, + /// attributedView: label, + /// options: [ + /// .processor( + /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) + /// |> RoundCornerImageProcessor(cornerRadius: 15)) + /// ] + /// ) + /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) + /// label.attributedText = attributedText + /// ``` + /// + @discardableResult + public func setImage( + with source: Source?, + attributedView: @autoclosure @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + attributedView: attributedView, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the text attachment with a source. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// + /// The retrieved image will be set to `NSTextAttachment.image` property. Because it is not an image view based + /// rendering, options related to view, such as `.transition`, are not supported. + /// + /// Kingfisher will call `setNeedsDisplay` on the `attributedView` when the image task done. It gives the view a + /// chance to render the attributed string again for displaying the downloaded image. For example, if you set an + /// attributed with this `NSTextAttachment` to a `UILabel` object, pass it as the `attributedView` parameter. + /// + /// Here is a typical use case: + /// + /// ```swift + /// let attributedText = NSMutableAttributedString(string: "Hello World") + /// let textAttachment = NSTextAttachment() + /// + /// textAttachment.kf.setImage( + /// with: URL(string: "https://onevcat.com/assets/images/avatar.jpg")!, + /// attributedView: label, + /// options: [ + /// .processor( + /// ResizingImageProcessor(referenceSize: .init(width: 30, height: 30)) + /// |> RoundCornerImageProcessor(cornerRadius: 15)) + /// ] + /// ) + /// attributedText.replaceCharacters(in: NSRange(), with: NSAttributedString(attachment: textAttachment)) + /// label.attributedText = attributedText + /// ``` + /// + @discardableResult + public func setImage( + with resource: Resource?, + attributedView: @autoclosure @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: resource.map { .network($0) }, + attributedView: attributedView, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + func setImage( + with source: Source?, + attributedView: @escaping () -> KFCrossPlatformView, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + let view = attributedView() + #if canImport(UIKit) + view.setNeedsDisplay() + #else + view.setNeedsDisplay(view.bounds) + #endif + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + } + completionHandler?(result) + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the text attachment if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: NSTextAttachment { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift new file mode 100644 index 0000000..8f0948c --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/TVMonogramView+Kingfisher.swift @@ -0,0 +1,217 @@ +// +// TVMonogramView+Kingfisher.swift +// Kingfisher +// +// Created by Marvin Nazari on 2020-12-07. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +#if canImport(TVUIKit) + +import TVUIKit + +@available(tvOS 12.0, *) +extension KingfisherWrapper where Base: TVMonogramView { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.image = placeholder + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.image = placeholder + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.image = image + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.image = value.image + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.image = image + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +@available(tvOS 12.0, *) +extension KingfisherWrapper where Base: TVMonogramView { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift new file mode 100644 index 0000000..e30fdd6 --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/UIButton+Kingfisher.swift @@ -0,0 +1,416 @@ +// +// UIButton+Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/13. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(UIKit) +import UIKit + +extension KingfisherWrapper where Base: UIButton { + + // MARK: Setting Image + /// Sets an image to the button for a specified state with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + for: state, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the button for a specified state with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + @discardableResult + public func setImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + guard let source = source else { + base.setImage(placeholder, for: state) + setTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder, for: state) + } + + var mutatingSelf = self + let issuedIdentifier = Source.Identifier.next() + setTaskIdentifier(issuedIdentifier, for: state) + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setImage(image, for: state) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier(for: state) } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier(for: state) else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.setTaskIdentifier(nil, for: state) + + switch result { + case .success(let value): + self.base.setImage(value.image, for: state) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setImage(image, for: state) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Downloading Task + + /// Cancels the image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelImageDownloadTask() { + imageTask?.cancel() + } + + // MARK: Setting Background Image + + /// Sets a background image to the button for a specified state with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setBackgroundImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setBackgroundImage( + with: source, + for: state, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets a background image to the button for a specified state with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the resource. + /// - state: The button state to which the image should be set. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setBackgroundImage( + with resource: Resource?, + for state: UIControl.State, + placeholder: UIImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setBackgroundImage( + with: resource?.convertToSource(), + for: state, + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setBackgroundImage( + with source: Source?, + for state: UIControl.State, + placeholder: UIImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + guard let source = source else { + base.setBackgroundImage(placeholder, for: state) + setBackgroundTaskIdentifier(nil, for: state) + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setBackgroundImage(placeholder, for: state) + } + + var mutatingSelf = self + let issuedIdentifier = Source.Identifier.next() + setBackgroundTaskIdentifier(issuedIdentifier, for: state) + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setBackgroundImage(image, for: state) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.backgroundTaskIdentifier(for: state) } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.backgroundImageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.backgroundTaskIdentifier(for: state) else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.backgroundImageTask = nil + mutatingSelf.setBackgroundTaskIdentifier(nil, for: state) + + switch result { + case .success(let value): + self.base.setBackgroundImage(value.image, for: state) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setBackgroundImage(image, for: state) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.backgroundImageTask = task + return task + } + + // MARK: Cancelling Background Downloading Task + + /// Cancels the background image download task of the button if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelBackgroundImageDownloadTask() { + backgroundImageTask?.cancel() + } +} + +// MARK: - Associated Object +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: UIButton { + + private typealias TaskIdentifier = Box<[UInt: Source.Identifier.Value]> + + public func taskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { + return taskIdentifierInfo.value[state.rawValue] + } + + private func setTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { + taskIdentifierInfo.value[state.rawValue] = identifier + } + + private var taskIdentifierInfo: TaskIdentifier { + return getAssociatedObject(base, &taskIdentifierKey) ?? { + setRetainedAssociatedObject(base, &taskIdentifierKey, $0) + return $0 + } (TaskIdentifier([:])) + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} + + +private var backgroundTaskIdentifierKey: Void? +private var backgroundImageTaskKey: Void? + +// MARK: Background Properties +extension KingfisherWrapper where Base: UIButton { + + public func backgroundTaskIdentifier(for state: UIControl.State) -> Source.Identifier.Value? { + return backgroundTaskIdentifierInfo.value[state.rawValue] + } + + private func setBackgroundTaskIdentifier(_ identifier: Source.Identifier.Value?, for state: UIControl.State) { + backgroundTaskIdentifierInfo.value[state.rawValue] = identifier + } + + private var backgroundTaskIdentifierInfo: TaskIdentifier { + return getAssociatedObject(base, &backgroundTaskIdentifierKey) ?? { + setRetainedAssociatedObject(base, &backgroundTaskIdentifierKey, $0) + return $0 + } (TaskIdentifier([:])) + } + + private var backgroundImageTask: DownloadTask? { + get { return getAssociatedObject(base, &backgroundImageTaskKey) } + mutating set { setRetainedAssociatedObject(base, &backgroundImageTaskKey, newValue) } + } +} +#endif + +#endif diff --git a/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift b/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift new file mode 100644 index 0000000..ce424de --- /dev/null +++ b/Pods/Kingfisher/Sources/Extensions/WKInterfaceImage+Kingfisher.swift @@ -0,0 +1,212 @@ +// +// WKInterfaceImage+Kingfisher.swift +// Kingfisher +// +// Created by Rodrigo Borges Soares on 04/05/18. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(WatchKit) + +import WatchKit + +extension KingfisherWrapper where Base: WKInterfaceImage { + + // MARK: Setting Image + + /// Sets an image to the image view with a source. + /// + /// - Parameters: + /// - source: The `Source` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested source + /// Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? .empty)) + return setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: completionHandler + ) + } + + /// Sets an image to the image view with a requested resource. + /// + /// - Parameters: + /// - resource: The `Resource` object contains information about the image. + /// - placeholder: A placeholder to show while retrieving the image from the given `resource`. + /// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. + /// - completionHandler: Called when the image retrieved and set finished. + /// - Returns: A task represents the image downloading. + /// + /// - Note: + /// + /// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache + /// or network. Since this method will perform UI changes, you must call it from the main thread. + /// Both `progressBlock` and `completionHandler` will be also executed in the main thread. + /// + @discardableResult + public func setImage( + with resource: Resource?, + placeholder: KFCrossPlatformImage? = nil, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + return setImage( + with: resource?.convertToSource(), + placeholder: placeholder, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + func setImage( + with source: Source?, + placeholder: KFCrossPlatformImage? = nil, + parsedOptions: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var mutatingSelf = self + guard let source = source else { + base.setImage(placeholder) + mutatingSelf.taskIdentifier = nil + completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource))) + return nil + } + + var options = parsedOptions + if !options.keepCurrentImageWhileLoading { + base.setImage(placeholder) + } + + let issuedIdentifier = Source.Identifier.next() + mutatingSelf.taskIdentifier = issuedIdentifier + + if let block = progressBlock { + options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + + if let provider = ImageProgressiveProvider(options, refresh: { image in + self.base.setImage(image) + }) { + options.onDataReceived = (options.onDataReceived ?? []) + [provider] + } + + options.onDataReceived?.forEach { + $0.onShouldApply = { issuedIdentifier == self.taskIdentifier } + } + + let task = KingfisherManager.shared.retrieveImage( + with: source, + options: options, + downloadTaskUpdated: { mutatingSelf.imageTask = $0 }, + completionHandler: { result in + CallbackQueue.mainCurrentOrAsync.execute { + guard issuedIdentifier == self.taskIdentifier else { + let reason: KingfisherError.ImageSettingErrorReason + do { + let value = try result.get() + reason = .notCurrentSourceTask(result: value, error: nil, source: source) + } catch { + reason = .notCurrentSourceTask(result: nil, error: error, source: source) + } + let error = KingfisherError.imageSettingError(reason: reason) + completionHandler?(.failure(error)) + return + } + + mutatingSelf.imageTask = nil + mutatingSelf.taskIdentifier = nil + + switch result { + case .success(let value): + self.base.setImage(value.image) + completionHandler?(result) + + case .failure: + if let image = options.onFailureImage { + self.base.setImage(image) + } + completionHandler?(result) + } + } + } + ) + + mutatingSelf.imageTask = task + return task + } + + // MARK: Cancelling Image + + /// Cancel the image download task bounded to the image view if it is running. + /// Nothing will happen if the downloading has already finished. + public func cancelDownloadTask() { + imageTask?.cancel() + } +} + +private var taskIdentifierKey: Void? +private var imageTaskKey: Void? + +// MARK: Properties +extension KingfisherWrapper where Base: WKInterfaceImage { + + public private(set) var taskIdentifier: Source.Identifier.Value? { + get { + let box: Box? = getAssociatedObject(base, &taskIdentifierKey) + return box?.value + } + set { + let box = newValue.map { Box($0) } + setRetainedAssociatedObject(base, &taskIdentifierKey, box) + } + } + + private var imageTask: DownloadTask? { + get { return getAssociatedObject(base, &imageTaskKey) } + set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)} + } +} +#endif diff --git a/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift b/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift new file mode 100644 index 0000000..db5e2b4 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/AVAssetImageDataProvider.swift @@ -0,0 +1,137 @@ +// +// AVAssetImageDataProvider.swift +// Kingfisher +// +// Created by onevcat on 2020/08/09. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +import Foundation +import AVKit + +#if canImport(MobileCoreServices) +import MobileCoreServices +#else +import CoreServices +#endif + +/// A data provider to provide thumbnail data from a given AVKit asset. +public struct AVAssetImageDataProvider: ImageDataProvider { + + /// The possible error might be caused by the `AVAssetImageDataProvider`. + /// - userCancelled: The data provider process is cancelled. + /// - invalidImage: The retrieved image is invalid. + public enum AVAssetImageDataProviderError: Error { + case userCancelled + case invalidImage(_ image: CGImage?) + } + + /// The asset image generator bound to `self`. + public let assetImageGenerator: AVAssetImageGenerator + + /// The time at which the image should be generate in the asset. + public let time: CMTime + + private var internalKey: String { + return (assetImageGenerator.asset as? AVURLAsset)?.url.absoluteString ?? UUID().uuidString + } + + /// The cache key used by `self`. + public var cacheKey: String { + return "\(internalKey)_\(time.seconds)" + } + + /// Creates an asset image data provider. + /// - Parameters: + /// - assetImageGenerator: The asset image generator controls data providing behaviors. + /// - time: At which time in the asset the image should be generated. + public init(assetImageGenerator: AVAssetImageGenerator, time: CMTime) { + self.assetImageGenerator = assetImageGenerator + self.time = time + } + + /// Creates an asset image data provider. + /// - Parameters: + /// - assetURL: The URL of asset for providing image data. + /// - time: At which time in the asset the image should be generated. + /// + /// This method uses `assetURL` to create an `AVAssetImageGenerator` object and calls + /// the `init(assetImageGenerator:time:)` initializer. + /// + public init(assetURL: URL, time: CMTime) { + let asset = AVAsset(url: assetURL) + let generator = AVAssetImageGenerator(asset: asset) + self.init(assetImageGenerator: generator, time: time) + } + + /// Creates an asset image data provider. + /// + /// - Parameters: + /// - assetURL: The URL of asset for providing image data. + /// - seconds: At which time in seconds in the asset the image should be generated. + /// + /// This method uses `assetURL` to create an `AVAssetImageGenerator` object, uses `seconds` to create a `CMTime`, + /// and calls the `init(assetImageGenerator:time:)` initializer. + /// + public init(assetURL: URL, seconds: TimeInterval) { + let time = CMTime(seconds: seconds, preferredTimescale: 600) + self.init(assetURL: assetURL, time: time) + } + + public func data(handler: @escaping (Result) -> Void) { + assetImageGenerator.generateCGImagesAsynchronously(forTimes: [NSValue(time: time)]) { + (requestedTime, image, imageTime, result, error) in + if let error = error { + handler(.failure(error)) + return + } + + if result == .cancelled { + handler(.failure(AVAssetImageDataProviderError.userCancelled)) + return + } + + guard let cgImage = image, let data = cgImage.jpegData else { + handler(.failure(AVAssetImageDataProviderError.invalidImage(image))) + return + } + + handler(.success(data)) + } + } +} + +extension CGImage { + var jpegData: Data? { + guard let mutableData = CFDataCreateMutable(nil, 0), + let destination = CGImageDestinationCreateWithData(mutableData, kUTTypeJPEG, 1, nil) + else { + return nil + } + CGImageDestinationAddImage(destination, self, nil) + guard CGImageDestinationFinalize(destination) else { return nil } + return mutableData as Data + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift new file mode 100644 index 0000000..b529987 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/ImageDataProvider.swift @@ -0,0 +1,198 @@ +// +// ImageDataProvider.swift +// Kingfisher +// +// Created by onevcat on 2018/11/13. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a data provider to provide image data to Kingfisher when setting with +/// `Source.provider` source. Compared to `Source.network` member, it gives a chance +/// to load some image data in your own way, as long as you can provide the data +/// representation for the image. +public protocol ImageDataProvider { + + /// The key used in cache. + var cacheKey: String { get } + + /// Provides the data which represents image. Kingfisher uses the data you pass in the + /// handler to process images and caches it for later use. + /// + /// - Parameter handler: The handler you should call when you prepared your data. + /// If the data is loaded successfully, call the handler with + /// a `.success` with the data associated. Otherwise, call it + /// with a `.failure` and pass the error. + /// + /// - Note: + /// If the `handler` is called with a `.failure` with error, a `dataProviderError` of + /// `ImageSettingErrorReason` will be finally thrown out to you as the `KingfisherError` + /// from the framework. + func data(handler: @escaping (Result) -> Void) + + /// The content URL represents this provider, if exists. + var contentURL: URL? { get } +} + +public extension ImageDataProvider { + var contentURL: URL? { return nil } + func convertToSource() -> Source { + .provider(self) + } +} + +/// Represents an image data provider for loading from a local file URL on disk. +/// Uses this type for adding a disk image to Kingfisher. Compared to loading it +/// directly, you can get benefit of using Kingfisher's extension methods, as well +/// as applying `ImageProcessor`s and storing the image to `ImageCache` of Kingfisher. +public struct LocalFileImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + + /// The file URL from which the image be loaded. + public let fileURL: URL + private let loadingQueue: ExecutionQueue + + // MARK: Initializers + + /// Creates an image data provider by supplying the target local file URL. + /// + /// - Parameters: + /// - fileURL: The file URL from which the image be loaded. + /// - cacheKey: The key is used for caching the image data. By default, + /// the `absoluteString` of `fileURL` is used. + /// - loadingQueue: The queue where the file loading should happen. By default, the dispatch queue of + /// `.global(qos: .userInitiated)` will be used. + public init( + fileURL: URL, + cacheKey: String? = nil, + loadingQueue: ExecutionQueue = .dispatch(DispatchQueue.global(qos: .userInitiated)) + ) { + self.fileURL = fileURL + self.cacheKey = cacheKey ?? fileURL.localFileCacheKey + self.loadingQueue = loadingQueue + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler:@escaping (Result) -> Void) { + loadingQueue.execute { + handler(Result(catching: { try Data(contentsOf: fileURL) })) + } + } + + /// The URL of the local file on the disk. + public var contentURL: URL? { + return fileURL + } +} + +extension URL { + static let localFileCacheKeyPrefix = "kingfisher.local.cacheKey" + + // The special version of cache key for a local file on disk. Every time the app is reinstalled on the disk, + // the system assigns a new container folder to hold the .app (and the extensions, .appex) folder. So the URL for + // the same image in bundle might be different. + // + // This getter only uses the fixed part in the URL (until the bundle name folder) to provide a stable cache key + // for the image under the same path inside the bundle. + // + // See #1825 (https://github.com/onevcat/Kingfisher/issues/1825) + var localFileCacheKey: String { + var validComponents: [String] = [] + for part in pathComponents.reversed() { + validComponents.append(part) + if part.hasSuffix(".app") || part.hasSuffix(".appex") { + break + } + } + let fixedPath = "\(Self.localFileCacheKeyPrefix)/\(validComponents.reversed().joined(separator: "/"))" + if let q = query { + return "\(fixedPath)?\(q)" + } else { + return fixedPath + } + } +} + +/// Represents an image data provider for loading image from a given Base64 encoded string. +public struct Base64ImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + /// The encoded Base64 string for the image. + public let base64String: String + + // MARK: Initializers + + /// Creates an image data provider by supplying the Base64 encoded string. + /// + /// - Parameters: + /// - base64String: The Base64 encoded string for an image. + /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. + public init(base64String: String, cacheKey: String) { + self.base64String = base64String + self.cacheKey = cacheKey + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler: (Result) -> Void) { + let data = Data(base64Encoded: base64String)! + handler(.success(data)) + } +} + +/// Represents an image data provider for a raw data object. +public struct RawImageDataProvider: ImageDataProvider { + + // MARK: Public Properties + + /// The raw data object to provide to Kingfisher image loader. + public let data: Data + + // MARK: Initializers + + /// Creates an image data provider by the given raw `data` value and a `cacheKey` be used in Kingfisher cache. + /// + /// - Parameters: + /// - data: The raw data reprensents an image. + /// - cacheKey: The key is used for caching the image data. You need a different key for any different image. + public init(data: Data, cacheKey: String) { + self.data = data + self.cacheKey = cacheKey + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public var cacheKey: String + + public func data(handler: @escaping (Result) -> Void) { + handler(.success(data)) + } +} diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift new file mode 100644 index 0000000..4295055 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/Resource.swift @@ -0,0 +1,86 @@ +// +// Resource.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents an image resource at a certain url and a given cache key. +/// Kingfisher will use a `Resource` to download a resource from network and cache it with the cache key when +/// using `Source.network` as its image setting source. +public protocol Resource { + + /// The key used in cache. + var cacheKey: String { get } + + /// The target image URL. + var downloadURL: URL { get } +} + +extension Resource { + + /// Converts `self` to a valid `Source` based on its `downloadURL` scheme. A `.provider` with + /// `LocalFileImageDataProvider` associated will be returned if the URL points to a local file. Otherwise, + /// `.network` is returned. + public func convertToSource(overrideCacheKey: String? = nil) -> Source { + return downloadURL.isFileURL ? + .provider(LocalFileImageDataProvider(fileURL: downloadURL, cacheKey: overrideCacheKey ?? downloadURL.localFileCacheKey)) : + .network(ImageResource(downloadURL: downloadURL, cacheKey: overrideCacheKey ?? cacheKey)) + } +} + +/// ImageResource is a simple combination of `downloadURL` and `cacheKey`. +/// When passed to image view set methods, Kingfisher will try to download the target +/// image from the `downloadURL`, and then store it with the `cacheKey` as the key in cache. +public struct ImageResource: Resource { + + // MARK: - Initializers + + /// Creates an image resource. + /// + /// - Parameters: + /// - downloadURL: The target image URL from where the image can be downloaded. + /// - cacheKey: The cache key. If `nil`, Kingfisher will use the `absoluteString` of `downloadURL` as the key. + /// Default is `nil`. + public init(downloadURL: URL, cacheKey: String? = nil) { + self.downloadURL = downloadURL + self.cacheKey = cacheKey ?? downloadURL.absoluteString + } + + // MARK: Protocol Conforming + + /// The key used in cache. + public let cacheKey: String + + /// The target image URL. + public let downloadURL: URL +} + +/// URL conforms to `Resource` in Kingfisher. +/// The `absoluteString` of this URL is used as `cacheKey`. And the URL itself will be used as `downloadURL`. +/// If you need customize the url and/or cache key, use `ImageResource` instead. +extension URL: Resource { + public var cacheKey: String { return absoluteString } + public var downloadURL: URL { return self } +} diff --git a/Pods/Kingfisher/Sources/General/ImageSource/Source.swift b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift new file mode 100644 index 0000000..0fcf28b --- /dev/null +++ b/Pods/Kingfisher/Sources/General/ImageSource/Source.swift @@ -0,0 +1,123 @@ +// +// Source.swift +// Kingfisher +// +// Created by onevcat on 2018/11/17. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents an image setting source for Kingfisher methods. +/// +/// A `Source` value indicates the way how the target image can be retrieved and cached. +/// +/// - network: The target image should be got from network remotely. The associated `Resource` +/// value defines detail information like image URL and cache key. +/// - provider: The target image should be provided in a data format. Normally, it can be an image +/// from local storage or in any other encoding format (like Base64). +public enum Source { + + /// Represents the source task identifier when setting an image to a view with extension methods. + public enum Identifier { + + /// The underlying value type of source identifier. + public typealias Value = UInt + static var current: Value = 0 + static func next() -> Value { + current += 1 + return current + } + } + + // MARK: Member Cases + + /// The target image should be got from network remotely. The associated `Resource` + /// value defines detail information like image URL and cache key. + case network(Resource) + + /// The target image should be provided in a data format. Normally, it can be an image + /// from local storage or in any other encoding format (like Base64). + case provider(ImageDataProvider) + + // MARK: Getting Properties + + /// The cache key defined for this source value. + public var cacheKey: String { + switch self { + case .network(let resource): return resource.cacheKey + case .provider(let provider): return provider.cacheKey + } + } + + /// The URL defined for this source value. + /// + /// For a `.network` source, it is the `downloadURL` of associated `Resource` instance. + /// For a `.provider` value, it is always `nil`. + public var url: URL? { + switch self { + case .network(let resource): return resource.downloadURL + case .provider(let provider): return provider.contentURL + } + } +} + +extension Source: Hashable { + public static func == (lhs: Source, rhs: Source) -> Bool { + switch (lhs, rhs) { + case (.network(let r1), .network(let r2)): + return r1.cacheKey == r2.cacheKey && r1.downloadURL == r2.downloadURL + case (.provider(let p1), .provider(let p2)): + return p1.cacheKey == p2.cacheKey && p1.contentURL == p2.contentURL + case (.provider(_), .network(_)): + return false + case (.network(_), .provider(_)): + return false + } + } + + public func hash(into hasher: inout Hasher) { + switch self { + case .network(let r): + hasher.combine(r.cacheKey) + hasher.combine(r.downloadURL) + case .provider(let p): + hasher.combine(p.cacheKey) + hasher.combine(p.contentURL) + } + } +} + +extension Source { + var asResource: Resource? { + guard case .network(let resource) = self else { + return nil + } + return resource + } + + var asProvider: ImageDataProvider? { + guard case .provider(let provider) = self else { + return nil + } + return provider + } +} diff --git a/Pods/Kingfisher/Sources/General/KF.swift b/Pods/Kingfisher/Sources/General/KF.swift new file mode 100644 index 0000000..b4fc431 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KF.swift @@ -0,0 +1,442 @@ +// +// KF.swift +// Kingfisher +// +// Created by onevcat on 2020/09/21. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(UIKit) +import UIKit +#endif + +#if canImport(CarPlay) +import CarPlay +#endif + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +#if canImport(WatchKit) +import WatchKit +#endif + +#if canImport(TVUIKit) +import TVUIKit +#endif + +/// A helper type to create image setting tasks in a builder pattern. +/// Use methods in this type to create a `KF.Builder` instance and configure image tasks there. +public enum KF { + + /// Creates a builder for a given `Source`. + /// - Parameter source: The `Source` object defines data information from network or a data provider. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func source(_ source: Source?) -> KF.Builder { + Builder(source: source) + } + + /// Creates a builder for a given `Resource`. + /// - Parameter resource: The `Resource` object defines data information like key or URL. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func resource(_ resource: Resource?) -> KF.Builder { + source(resource?.convertToSource()) + } + + /// Creates a builder for a given `URL` and an optional cache key. + /// - Parameters: + /// - url: The URL where the image should be downloaded. + /// - cacheKey: The key used to store the downloaded image in cache. + /// If `nil`, the `absoluteString` of `url` is used as the cache key. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func url(_ url: URL?, cacheKey: String? = nil) -> KF.Builder { + source(url?.convertToSource(overrideCacheKey: cacheKey)) + } + + /// Creates a builder for a given `ImageDataProvider`. + /// - Parameter provider: The `ImageDataProvider` object contains information about the data. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func dataProvider(_ provider: ImageDataProvider?) -> KF.Builder { + source(provider?.convertToSource()) + } + + /// Creates a builder for some given raw data and a cache key. + /// - Parameters: + /// - data: The data object from which the image should be created. + /// - cacheKey: The key used to store the downloaded image in cache. + /// - Returns: A `KF.Builder` for future configuration. After configuring the builder, call `set(to:)` + /// to start the image loading. + public static func data(_ data: Data?, cacheKey: String) -> KF.Builder { + if let data = data { + return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) + } else { + return dataProvider(nil) + } + } +} + + +extension KF { + + /// A builder class to configure an image retrieving task and set it to a holder view or component. + public class Builder { + private let source: Source? + + #if os(watchOS) + private var placeholder: KFCrossPlatformImage? + #else + private var placeholder: Placeholder? + #endif + + public var options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions) + + public let onFailureDelegate = Delegate() + public let onSuccessDelegate = Delegate() + public let onProgressDelegate = Delegate<(Int64, Int64), Void>() + + init(source: Source?) { + self.source = source + } + + private var resultHandler: ((Result) -> Void)? { + { + switch $0 { + case .success(let result): + self.onSuccessDelegate(result) + case .failure(let error): + self.onFailureDelegate(error) + } + } + } + + private var progressBlock: DownloadProgressBlock { + { self.onProgressDelegate(($0, $1)) } + } + } +} + +extension KF.Builder { + #if !os(watchOS) + + /// Builds the image task request and sets it to an image view. + /// - Parameter imageView: The image view which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to imageView: KFCrossPlatformImageView) -> DownloadTask? { + imageView.kf.setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to an `NSTextAttachment` object. + /// - Parameters: + /// - attachment: The text attachment object which loads the task and should be set with the image. + /// - attributedView: The owner of the attributed string which this `NSTextAttachment` is added. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to attachment: NSTextAttachment, attributedView: @autoclosure @escaping () -> KFCrossPlatformView) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return attachment.kf.setImage( + with: source, + attributedView: attributedView, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + #if canImport(UIKit) + + /// Builds the image task request and sets it to a button. + /// - Parameters: + /// - button: The button which loads the task and should be set with the image. + /// - state: The button state to which the image should be set. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to button: UIButton, for state: UIControl.State) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setImage( + with: source, + for: state, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to the background image for a button. + /// - Parameters: + /// - button: The button which loads the task and should be set with the image. + /// - state: The button state to which the image should be set. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func setBackground(to button: UIButton, for state: UIControl.State) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setBackgroundImage( + with: source, + for: state, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(UIKit) + + #if canImport(CarPlay) + + /// Builds the image task request and sets it to the image for a list item. + /// - Parameters: + /// - listItem: The list item which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @available(iOS 14.0, *) + @discardableResult + public func set(to listItem: CPListItem) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return listItem.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + + } + + #endif + + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + /// Builds the image task request and sets it to a button. + /// - Parameter button: The button which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to button: NSButton) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + + /// Builds the image task request and sets it to the alternative image for a button. + /// - Parameter button: The button which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func setAlternative(to button: NSButton) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return button.kf.setAlternateImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(AppKit) + #endif // end of !os(watchOS) + + #if canImport(WatchKit) + /// Builds the image task request and sets it to a `WKInterfaceImage` object. + /// - Parameter interfaceImage: The watch interface image which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @discardableResult + public func set(to interfaceImage: WKInterfaceImage) -> DownloadTask? { + return interfaceImage.kf.setImage( + with: source, + placeholder: placeholder, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(WatchKit) + + #if canImport(TVUIKit) + /// Builds the image task request and sets it to a TV monogram view. + /// - Parameter monogramView: The monogram view which loads the task and should be set with the image. + /// - Returns: A task represents the image downloading, if initialized. + /// This value is `nil` if the image is being loaded from cache. + @available(tvOS 12.0, *) + @discardableResult + public func set(to monogramView: TVMonogramView) -> DownloadTask? { + let placeholderImage = placeholder as? KFCrossPlatformImage ?? nil + return monogramView.kf.setImage( + with: source, + placeholder: placeholderImage, + parsedOptions: options, + progressBlock: progressBlock, + completionHandler: resultHandler + ) + } + #endif // end of canImport(TVUIKit) +} + +#if !os(watchOS) +extension KF.Builder { + #if os(iOS) || os(tvOS) + + /// Sets a placeholder which is used while retrieving the image. + /// - Parameter placeholder: A placeholder to show while retrieving the image from its source. + /// - Returns: A `KF.Builder` with changes applied. + public func placeholder(_ placeholder: Placeholder?) -> Self { + self.placeholder = placeholder + return self + } + #endif + + /// Sets a placeholder image which is used while retrieving the image. + /// - Parameter placeholder: An image to show while retrieving the image from its source. + /// - Returns: A `KF.Builder` with changes applied. + public func placeholder(_ image: KFCrossPlatformImage?) -> Self { + self.placeholder = image + return self + } +} +#endif + +extension KF.Builder { + + #if os(iOS) || os(tvOS) + /// Sets the transition for the image task. + /// - Parameter transition: The desired transition effect when setting the image to image view. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Kingfisher will use the `transition` to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. + public func transition(_ transition: ImageTransition) -> Self { + options.transition = transition + return self + } + + /// Sets a fade transition for the image task. + /// - Parameter duration: The duration of the fade transition. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KF.Builder`. + public func fade(duration: TimeInterval) -> Self { + options.transition = .fade(duration) + return self + } + #endif + + /// Sets whether keeping the existing image of image view while setting another image to it. + /// - Parameter enabled: Whether the existing image should be kept. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// By setting this option, the placeholder image parameter of image view extension method + /// will be ignored and the current image will be kept while loading or downloading the new image. + /// + public func keepCurrentImageWhileLoading(_ enabled: Bool = true) -> Self { + options.keepCurrentImageWhileLoading = enabled + return self + } + + /// Sets whether only the first frame from an animated image file should be loaded as a single image. + /// - Parameter enabled: Whether the only the first frame should be loaded. + /// - Returns: A `KF.Builder` with changes applied. + /// + /// Loading an animated images may take too much memory. It will be useful when you want to display a + /// static preview of the first frame from an animated image. + /// + /// This option will be ignored if the target image is not animated image data. + /// + public func onlyLoadFirstFrame(_ enabled: Bool = true) -> Self { + options.onlyLoadFirstFrame = enabled + return self + } + + /// Enables progressive image loading with a specified `ImageProgressive` setting to process the + /// progressive JPEG data and display it in a progressive way. + /// - Parameter progressive: The progressive settings which is used while loading. + /// - Returns: A `KF.Builder` with changes applied. + public func progressiveJPEG(_ progressive: ImageProgressive? = .default) -> Self { + options.progressiveJPEG = progressive + return self + } +} + +// MARK: - Deprecated +extension KF.Builder { + /// Starts the loading process of `self` immediately. + /// + /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading + /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a + /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once + /// could help avoiding the flickering, with some performance trade-off. + /// + /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data. + /// It does nothing now and please just remove it. + /// + /// - Returns: The `Self` value with changes applied. + @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.") + public func loadImmediately(_ start: Bool = true) -> Self { + return self + } +} + +// MARK: - Redirect Handler +extension KF { + + /// Represents the detail information when a task redirect happens. It is wrapping necessary information for a + /// `ImageDownloadRedirectHandler`. See that protocol for more information. + public struct RedirectPayload { + + /// The related session data task when the redirect happens. It is + /// the current `SessionDataTask` which triggers this redirect. + public let task: SessionDataTask + + /// The response received during redirection. + public let response: HTTPURLResponse + + /// The request for redirection which can be modified. + public let newRequest: URLRequest + + /// A closure for being called with modified request. + public let completionHandler: (URLRequest?) -> Void + } +} diff --git a/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift b/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift new file mode 100644 index 0000000..7722f54 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KFOptionsSetter.swift @@ -0,0 +1,695 @@ +// +// KFOptionsSetter.swift +// Kingfisher +// +// Created by onevcat on 2020/12/22. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +public protocol KFOptionSetter { + var options: KingfisherParsedOptionsInfo { get nonmutating set } + + var onFailureDelegate: Delegate { get } + var onSuccessDelegate: Delegate { get } + var onProgressDelegate: Delegate<(Int64, Int64), Void> { get } + + var delegateObserver: AnyObject { get } +} + +extension KF.Builder: KFOptionSetter { + public var delegateObserver: AnyObject { self } +} + +// MARK: - Life cycles +extension KFOptionSetter { + /// Sets the progress block to current builder. + /// - Parameter block: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. If `block` is `nil`, the callback + /// will be reset. + /// - Returns: A `Self` value with changes applied. + public func onProgress(_ block: DownloadProgressBlock?) -> Self { + onProgressDelegate.delegate(on: delegateObserver) { (observer, result) in + block?(result.0, result.1) + } + return self + } + + /// Sets the the done block to current builder. + /// - Parameter block: Called when the image task successfully completes and the the image set is done. If `block` + /// is `nil`, the callback will be reset. + /// - Returns: A `KF.Builder` with changes applied. + public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self { + onSuccessDelegate.delegate(on: delegateObserver) { (observer, result) in + block?(result) + } + return self + } + + /// Sets the catch block to current builder. + /// - Parameter block: Called when an error happens during the image task. If `block` + /// is `nil`, the callback will be reset. + /// - Returns: A `KF.Builder` with changes applied. + public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self { + onFailureDelegate.delegate(on: delegateObserver) { (observer, error) in + block?(error) + } + return self + } +} + +// MARK: - Basic options settings. +extension KFOptionSetter { + /// Sets the target image cache for this task. + /// - Parameter cache: The target cache is about to be used for the task. + /// - Returns: A `Self` value with changes applied. + /// + /// Kingfisher will use the associated `ImageCache` object when handling related operations, + /// including trying to retrieve the cached images and store the downloaded image to it. + /// + public func targetCache(_ cache: ImageCache) -> Self { + options.targetCache = cache + return self + } + + /// Sets the target image cache to store the original downloaded image for this task. + /// - Parameter cache: The target cache is about to be used for storing the original downloaded image from the task. + /// - Returns: A `Self` value with changes applied. + /// + /// The `ImageCache` for storing and retrieving original images. If `originalCache` is + /// contained in the options, it will be preferred for storing and retrieving original images. + /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. + /// + /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is + /// applied in the option, the original image will be stored to this `originalCache`. At the + /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, + /// Kingfisher will try to search the original image to check whether it is already there. If found, + /// it will be used and applied with the given processor. It is an optimization for not downloading + /// the same image for multiple times. + /// + public func originalCache(_ cache: ImageCache) -> Self { + options.originalCache = cache + return self + } + + /// Sets the downloader used to perform the image download task. + /// - Parameter downloader: The downloader which is about to be used for downloading. + /// - Returns: A `Self` value with changes applied. + /// + /// Kingfisher will use the set `ImageDownloader` object to download the requested images. + public func downloader(_ downloader: ImageDownloader) -> Self { + options.downloader = downloader + return self + } + + /// Sets the download priority for the image task. + /// - Parameter priority: The download priority of image download task. + /// - Returns: A `Self` value with changes applied. + /// + /// The `priority` value will be set as the priority of the image download task. The value for it should be + /// between 0.0~1.0. You can choose a value between `URLSessionTask.defaultPriority`, `URLSessionTask.lowPriority` + /// or `URLSessionTask.highPriority`. If this option not set, the default value (`URLSessionTask.defaultPriority`) + /// will be used. + public func downloadPriority(_ priority: Float) -> Self { + options.downloadPriority = priority + return self + } + + /// Sets whether Kingfisher should ignore the cache and try to start a download task for the image source. + /// - Parameter enabled: Enable the force refresh or not. + /// - Returns: A `Self` value with changes applied. + public func forceRefresh(_ enabled: Bool = true) -> Self { + options.forceRefresh = enabled + return self + } + + /// Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the + /// disk cache and starts a download task for the image source. + /// - Parameter enabled: Enable the memory-only cache searching or not. + /// - Returns: A `Self` value with changes applied. + /// + /// This is useful when you want to display a changeable image behind the same url at the same app session, while + /// avoiding download it for multiple times. + public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self { + options.fromMemoryCacheOrRefresh = enabled + return self + } + + /// Sets whether the image should only be cached in memory but not in disk. + /// - Parameter enabled: Whether the image should be only cache in memory or not. + /// - Returns: A `Self` value with changes applied. + public func cacheMemoryOnly(_ enabled: Bool = true) -> Self { + options.cacheMemoryOnly = enabled + return self + } + + /// Sets whether Kingfisher should wait for caching operation to be completed before calling the + /// `onSuccess` or `onFailure` block. + /// - Parameter enabled: Whether Kingfisher should wait for caching operation. + /// - Returns: A `Self` value with changes applied. + public func waitForCache(_ enabled: Bool = true) -> Self { + options.waitForCache = enabled + return self + } + + /// Sets whether Kingfisher should only try to retrieve the image from cache, but not from network. + /// - Parameter enabled: Whether Kingfisher should only try to retrieve the image from cache. + /// - Returns: A `Self` value with changes applied. + /// + /// If the image is not in cache, the image retrieving will fail with the + /// `KingfisherError.cacheError` with `.imageNotExisting` as its reason. + public func onlyFromCache(_ enabled: Bool = true) -> Self { + options.onlyFromCache = enabled + return self + } + + /// Sets whether the image should be decoded in a background thread before using. + /// - Parameter enabled: Whether the image should be decoded in a background thread before using. + /// - Returns: A `Self` value with changes applied. + /// + /// Setting to `true` will decode the downloaded image data and do a off-screen rendering to extract pixel + /// information in background. This can speed up display, but will cost more time and memory to prepare the image + /// for using. + public func backgroundDecode(_ enabled: Bool = true) -> Self { + options.backgroundDecode = enabled + return self + } + + /// Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from + /// cache. If not set, Kingfisher will use main queue for callbacks. + /// - Parameter queue: The target queue which the cache retrieving callback will be invoked on. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: + /// This option does not affect the callbacks for UI related extension methods or `KFImage` result handlers. + /// You will always get the callbacks called from main queue. + public func callbackQueue(_ queue: CallbackQueue) -> Self { + options.callbackQueue = queue + return self + } + + /// Sets the scale factor value when converting retrieved data to an image. + /// - Parameter factor: The scale factor value. + /// - Returns: A `Self` value with changes applied. + /// + /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing + /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. + /// + public func scaleFactor(_ factor: CGFloat) -> Self { + options.scaleFactor = factor + return self + } + + /// Sets whether the original image should be cached even when the original image has been processed by any other + /// `ImageProcessor`s. + /// - Parameter enabled: Whether the original image should be cached. + /// - Returns: A `Self` value with changes applied. + /// + /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original + /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same + /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original + /// images if necessary. + /// + /// The original image will be only cached to disk storage. + /// + public func cacheOriginalImage(_ enabled: Bool = true) -> Self { + options.cacheOriginalImage = enabled + return self + } + + /// Sets whether the disk storage loading should happen in the same calling queue. + /// - Parameter enabled: Whether the disk storage loading should happen in the same calling queue. + /// - Returns: A `Self` value with changes applied. + /// + /// By default, disk storage file loading + /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk + /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already + /// has an image set. + /// + /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue + /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. + /// + public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self { + options.loadDiskFileSynchronously = enabled + return self + } + + /// Sets a queue on which the image processing should happen. + /// - Parameter queue: The queue on which the image processing should happen. + /// - Returns: A `Self` value with changes applied. + /// + /// By default, Kingfisher uses a pre-defined serial + /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` + /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of + /// blocking the UI, especially if the processor needs a lot of time to run). + public func processingQueue(_ queue: CallbackQueue?) -> Self { + options.processingQueue = queue + return self + } + + /// Sets the alternative sources that will be used when loading of the original input `Source` fails. + /// - Parameter sources: The alternative sources will be used. + /// - Returns: A `Self` value with changes applied. + /// + /// Values of the `sources` array will be used to start a new image loading task if the previous task + /// fails due to an error. The image source loading process will stop as soon as a source is loaded successfully. + /// If all `sources` are used but the loading is still failing, an `imageSettingError` with + /// `alternativeSourcesExhausted` as its reason will be given out in the `catch` block. + /// + /// This is useful if you want to implement a fallback solution for setting image. + /// + /// User cancellation will not trigger the alternative source loading. + public func alternativeSources(_ sources: [Source]?) -> Self { + options.alternativeSources = sources + return self + } + + /// Sets a retry strategy that will be used when something gets wrong during the image retrieving. + /// - Parameter strategy: The provided strategy to define how the retrying should happen. + /// - Returns: A `Self` value with changes applied. + public func retry(_ strategy: RetryStrategy?) -> Self { + options.retryStrategy = strategy + return self + } + + /// Sets a retry strategy with a max retry count and retrying interval. + /// - Parameters: + /// - maxCount: The maximum count before the retry stops. + /// - interval: The time interval between each retry attempt. + /// - Returns: A `Self` value with changes applied. + /// + /// This defines the simplest retry strategy, which retry a failing request for several times, with some certain + /// interval between each time. For example, `.retry(maxCount: 3, interval: .second(3))` means attempt for at most + /// three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt. + public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self { + let strategy = DelayRetryStrategy(maxRetryCount: maxCount, retryInterval: interval) + options.retryStrategy = strategy + return self + } + + /// Sets the `Source` should be loaded when user enables Low Data Mode and the original source fails with an + /// `NSURLErrorNetworkUnavailableReason.constrained` error. + /// - Parameter source: The `Source` will be loaded under low data mode. + /// - Returns: A `Self` value with changes applied. + /// + /// When this option is set, the + /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the + /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a + /// low-resolution version of your image or a local image provider to display a placeholder. + /// + /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will + /// be loaded following the system default behavior, in a normal way. + public func lowDataModeSource(_ source: Source?) -> Self { + options.lowDataModeSource = source + return self + } + + /// Sets whether the image setting for an image view should happen with transition even when retrieved from cache. + /// - Parameter enabled: Enable the force transition or not. + /// - Returns: A `Self` with changes applied. + public func forceTransition(_ enabled: Bool = true) -> Self { + options.forceTransition = enabled + return self + } + + /// Sets the image that will be used if an image retrieving task fails. + /// - Parameter image: The image that will be used when something goes wrong. + /// - Returns: A `Self` with changes applied. + /// + /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) + /// in place of requested one. It's useful when you don't want to show placeholder + /// during loading time but wants to use some default image when requests will be failed. + /// + public func onFailureImage(_ image: KFCrossPlatformImage?) -> Self { + options.onFailureImage = .some(image) + return self + } +} + +// MARK: - Request Modifier +extension KFOptionSetter { + /// Sets an `ImageDownloadRequestModifier` to change the image download request before it being sent. + /// - Parameter modifier: The modifier will be used to change the request before it being sent. + /// - Returns: A `Self` value with changes applied. + /// + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + public func requestModifier(_ modifier: ImageDownloadRequestModifier) -> Self { + options.requestModifier = modifier + return self + } + + /// Sets a block to change the image download request before it being sent. + /// - Parameter modifyBlock: The modifying block will be called to change the request before it being sent. + /// - Returns: A `Self` value with changes applied. + /// + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self { + options.requestModifier = AnyModifier { r -> URLRequest? in + var request = r + modifyBlock(&request) + return request + } + return self + } +} + +// MARK: - Redirect Handler +extension KFOptionSetter { + /// The `ImageDownloadRedirectHandler` argument will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + /// - Parameter handler: The handler will be used for redirection. + /// - Returns: A `Self` value with changes applied. + public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self { + options.redirectHandler = handler + return self + } + + /// The `block` will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + /// - Parameter block: The block will be used for redirection. + /// - Returns: A `Self` value with changes applied. + public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self { + let redirectHandler = AnyRedirectHandler { (task, response, request, handler) in + let payload = KF.RedirectPayload( + task: task, response: response, newRequest: request, completionHandler: handler + ) + block(payload) + } + options.redirectHandler = redirectHandler + return self + } +} + +// MARK: - Processor +extension KFOptionSetter { + + /// Sets an image processor for the image task. It replaces the current image processor settings. + /// + /// - Parameter processor: The processor you want to use to process the image after it is downloaded. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: + /// To append a processor to current ones instead of replacing them all, use `appendProcessor(_:)`. + public func setProcessor(_ processor: ImageProcessor) -> Self { + options.processor = processor + return self + } + + /// Sets an array of image processors for the image task. It replaces the current image processor settings. + /// - Parameter processors: An array of processors. The processors inside this array will be concatenated one by one + /// to form a processor pipeline. + /// - Returns: A `Self` value with changes applied. + /// + /// - Note: + /// To append processors to current ones instead of replacing them all, concatenate them by `|>`, then use + /// `appendProcessor(_:)`. + public func setProcessors(_ processors: [ImageProcessor]) -> Self { + switch processors.count { + case 0: + options.processor = DefaultImageProcessor.default + case 1...: + options.processor = processors.dropFirst().reduce(processors[0]) { $0 |> $1 } + default: + assertionFailure("Never happen") + } + return self + } + + /// Appends a processor to the current set processors. + /// - Parameter processor: The processor which will be appended to current processor settings. + /// - Returns: A `Self` value with changes applied. + public func appendProcessor(_ processor: ImageProcessor) -> Self { + options.processor = options.processor |> processor + return self + } + + /// Appends a `RoundCornerImageProcessor` to current processors. + /// - Parameters: + /// - radius: The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction + /// of the target image with `.widthFraction`. or `.heightFraction`. For example, given a square image + /// with width and height equals, `.widthFraction(0.5)` means use half of the length of size and makes + /// the final image a round one. + /// - targetSize: Target size of output image should be. If `nil`, the image will keep its original size after processing. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: Background color of the output image. If `nil`, it will use a transparent background. + /// - Returns: A `Self` value with changes applied. + public func roundCorner( + radius: RoundCornerImageProcessor.Radius, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> Self + { + let processor = RoundCornerImageProcessor( + radius: radius, + targetSize: targetSize, + roundingCorners: corners, + backgroundColor: backgroundColor + ) + return appendProcessor(processor) + } + + /// Appends a `BlurImageProcessor` to current processors. + /// - Parameter radius: Blur radius for the simulated Gaussian blur. + /// - Returns: A `Self` value with changes applied. + public func blur(radius: CGFloat) -> Self { + appendProcessor( + BlurImageProcessor(blurRadius: radius) + ) + } + + /// Appends a `OverlayImageProcessor` to current processors. + /// - Parameters: + /// - color: Overlay color will be used to overlay the input image. + /// - fraction: Fraction will be used when overlay the color to image. + /// - Returns: A `Self` value with changes applied. + public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self { + appendProcessor( + OverlayImageProcessor(overlay: color, fraction: fraction) + ) + } + + /// Appends a `TintImageProcessor` to current processors. + /// - Parameter color: Tint color will be used to tint the input image. + /// - Returns: A `Self` value with changes applied. + public func tint(color: KFCrossPlatformColor) -> Self { + appendProcessor( + TintImageProcessor(tint: color) + ) + } + + /// Appends a `BlackWhiteProcessor` to current processors. + /// - Returns: A `Self` value with changes applied. + public func blackWhite() -> Self { + appendProcessor( + BlackWhiteProcessor() + ) + } + + /// Appends a `CroppingImageProcessor` to current processors. + /// - Parameters: + /// - size: Target size of output image should be. + /// - anchor: Anchor point from which the output size should be calculate. The anchor point is consisted by two + /// values between 0.0 and 1.0. It indicates a related point in current image. + /// See `CroppingImageProcessor.init(size:anchor:)` for more. + /// - Returns: A `Self` value with changes applied. + public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self { + appendProcessor( + CroppingImageProcessor(size: size, anchor: anchor) + ) + } + + /// Appends a `DownsamplingImageProcessor` to current processors. + /// + /// Compared to `ResizingImageProcessor`, the `DownsamplingImageProcessor` does not render the original images and + /// then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient + /// than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible + /// as you can than the `ResizingImageProcessor`. + /// + /// Only CG-based images are supported. Animated images (like GIF) is not supported. + /// + /// - Parameter size: Target size of output image should be. It should be smaller than the size of input image. + /// If it is larger, the result image will be the same size of input data without downsampling. + /// - Returns: A `Self` value with changes applied. + public func downsampling(size: CGSize) -> Self { + let processor = DownsamplingImageProcessor(size: size) + if options.processor == DefaultImageProcessor.default { + return setProcessor(processor) + } else { + return appendProcessor(processor) + } + } + + + /// Appends a `ResizingImageProcessor` to current processors. + /// + /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` + /// instead, which is more efficient and uses less memory. + /// + /// - Parameters: + /// - referenceSize: The reference size for resizing operation in point. + /// - mode: Target content mode of output image should be. Default is `.none`. + /// - Returns: A `Self` value with changes applied. + public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self { + appendProcessor( + ResizingImageProcessor(referenceSize: referenceSize, mode: mode) + ) + } +} + +// MARK: - Cache Serializer +extension KFOptionSetter { + + /// Uses a given `CacheSerializer` to convert some data to an image object for retrieving from disk cache or vice + /// versa for storing to disk cache. + /// - Parameter cacheSerializer: The `CacheSerializer` which will be used. + /// - Returns: A `Self` value with changes applied. + public func serialize(by cacheSerializer: CacheSerializer) -> Self { + options.cacheSerializer = cacheSerializer + return self + } + + /// Uses a given format to serializer the image data to disk. It converts the image object to the give data format. + /// - Parameters: + /// - format: The desired data encoding format when store the image on disk. + /// - jpegCompressionQuality: If the format is `.JPEG`, it specify the compression quality when converting the + /// image to a JPEG data. Otherwise, it is ignored. + /// - Returns: A `Self` value with changes applied. + public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self { + let cacheSerializer: FormatIndicatedCacheSerializer + switch format { + case .JPEG: + cacheSerializer = .jpeg(compressionQuality: jpegCompressionQuality ?? 1.0) + case .PNG: + cacheSerializer = .png + case .GIF: + cacheSerializer = .gif + case .unknown: + cacheSerializer = .png + } + options.cacheSerializer = cacheSerializer + return self + } +} + +// MARK: - Image Modifier +extension KFOptionSetter { + + /// Sets an `ImageModifier` to the image task. Use this to modify the fetched image object properties if needed. + /// + /// If the image was fetched directly from the downloader, the modifier will run directly after the + /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`. + /// - Parameter modifier: The `ImageModifier` which will be used to modify the image object. + /// - Returns: A `Self` value with changes applied. + public func imageModifier(_ modifier: ImageModifier?) -> Self { + options.imageModifier = modifier + return self + } + + /// Sets a block to modify the image object. Use this to modify the fetched image object properties if needed. + /// + /// If the image was fetched directly from the downloader, the modifier block will run directly after the + /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`. + /// + /// - Parameter block: The block which is used to modify the image object. + /// - Returns: A `Self` value with changes applied. + public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self { + let modifier = AnyImageModifier { image -> KFCrossPlatformImage in + var image = image + try block(&image) + return image + } + options.imageModifier = modifier + return self + } +} + + +// MARK: - Cache Expiration +extension KFOptionSetter { + + /// Sets the expiration setting for memory cache of this image task. + /// + /// By default, the underlying `MemoryStorage.Backend` uses the + /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this value to overwrite + /// the config setting for this caching item. + /// + /// - Parameter expiration: The expiration setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self { + options.memoryCacheExpiration = expiration + return self + } + + /// Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this + /// value after access. + /// + /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all, sets `.none` to it. + /// + /// - Parameter extending: The expiration extending setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self { + options.memoryCacheAccessExtendingExpiration = extending + return self + } + + /// Sets the expiration setting for disk cache of this image task. + /// + /// By default, the underlying `DiskStorage.Backend` uses the expiration in its config for all items. If set, + /// the `DiskStorage.Backend` will use this value to overwrite the config setting for this caching item. + /// + /// - Parameter expiration: The expiration setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self { + options.diskCacheExpiration = expiration + return self + } + + /// Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this + /// value after access. + /// + /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all, sets `.none` to it. + /// + /// - Parameter extending: The expiration extending setting used in cache storage. + /// - Returns: A `Self` value with changes applied. + public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self { + options.diskCacheAccessExtendingExpiration = extending + return self + } +} diff --git a/Pods/Kingfisher/Sources/General/Kingfisher.swift b/Pods/Kingfisher/Sources/General/Kingfisher.swift new file mode 100644 index 0000000..6f3aa53 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/Kingfisher.swift @@ -0,0 +1,106 @@ +// +// Kingfisher.swift +// Kingfisher +// +// Created by Wei Wang on 16/9/14. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import ImageIO + +#if os(macOS) +import AppKit +public typealias KFCrossPlatformImage = NSImage +public typealias KFCrossPlatformView = NSView +public typealias KFCrossPlatformColor = NSColor +public typealias KFCrossPlatformImageView = NSImageView +public typealias KFCrossPlatformButton = NSButton +#else +import UIKit +public typealias KFCrossPlatformImage = UIImage +public typealias KFCrossPlatformColor = UIColor +#if !os(watchOS) +public typealias KFCrossPlatformImageView = UIImageView +public typealias KFCrossPlatformView = UIView +public typealias KFCrossPlatformButton = UIButton +#if canImport(TVUIKit) +import TVUIKit +#endif +#if canImport(CarPlay) +import CarPlay +#endif +#else +import WatchKit +#endif +#endif + +/// Wrapper for Kingfisher compatible types. This type provides an extension point for +/// convenience methods in Kingfisher. +public struct KingfisherWrapper { + public let base: Base + public init(_ base: Base) { + self.base = base + } +} + +/// Represents an object type that is compatible with Kingfisher. You can use `kf` property to get a +/// value in the namespace of Kingfisher. +public protocol KingfisherCompatible: AnyObject { } + +/// Represents a value type that is compatible with Kingfisher. You can use `kf` property to get a +/// value in the namespace of Kingfisher. +public protocol KingfisherCompatibleValue {} + +extension KingfisherCompatible { + /// Gets a namespace holder for Kingfisher compatible types. + public var kf: KingfisherWrapper { + get { return KingfisherWrapper(self) } + set { } + } +} + +extension KingfisherCompatibleValue { + /// Gets a namespace holder for Kingfisher compatible types. + public var kf: KingfisherWrapper { + get { return KingfisherWrapper(self) } + set { } + } +} + +extension KFCrossPlatformImage: KingfisherCompatible { } +#if !os(watchOS) +extension KFCrossPlatformImageView: KingfisherCompatible { } +extension KFCrossPlatformButton: KingfisherCompatible { } +extension NSTextAttachment: KingfisherCompatible { } +#else +extension WKInterfaceImage: KingfisherCompatible { } +#endif + +#if os(tvOS) && canImport(TVUIKit) +@available(tvOS 12.0, *) +extension TVMonogramView: KingfisherCompatible { } +#endif + +#if canImport(CarPlay) +@available(iOS 14.0, *) +extension CPListItem: KingfisherCompatible { } +#endif diff --git a/Pods/Kingfisher/Sources/General/KingfisherError.swift b/Pods/Kingfisher/Sources/General/KingfisherError.swift new file mode 100644 index 0000000..83d20a1 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherError.swift @@ -0,0 +1,461 @@ +// +// KingfisherError.swift +// Kingfisher +// +// Created by onevcat on 2018/09/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension Never {} + +/// Represents all the errors which can happen in Kingfisher framework. +/// Kingfisher related methods always throw a `KingfisherError` or invoke the callback with `KingfisherError` +/// as its error type. To handle errors from Kingfisher, you switch over the error to get a reason catalog, +/// then switch over the reason to know error detail. +public enum KingfisherError: Error { + + // MARK: Error Reason Types + + /// Represents the error reason during networking request phase. + /// + /// - emptyRequest: The request is empty. Code 1001. + /// - invalidURL: The URL of request is invalid. Code 1002. + /// - taskCancelled: The downloading task is cancelled by user. Code 1003. + public enum RequestErrorReason { + + /// The request is empty. Code 1001. + case emptyRequest + + /// The URL of request is invalid. Code 1002. + /// - request: The request is tend to be sent but its URL is invalid. + case invalidURL(request: URLRequest) + + /// The downloading task is cancelled by user. Code 1003. + /// - task: The session data task which is cancelled. + /// - token: The cancel token which is used for cancelling the task. + case taskCancelled(task: SessionDataTask, token: SessionDataTask.CancelToken) + } + + /// Represents the error reason during networking response phase. + /// + /// - invalidURLResponse: The response is not a valid URL response. Code 2001. + /// - invalidHTTPStatusCode: The response contains an invalid HTTP status code. Code 2002. + /// - URLSessionError: An error happens in the system URL session. Code 2003. + /// - dataModifyingFailed: Data modifying fails on returning a valid data. Code 2004. + /// - noURLResponse: The task is done but no URL response found. Code 2005. + public enum ResponseErrorReason { + + /// The response is not a valid URL response. Code 2001. + /// - response: The received invalid URL response. + /// The response is expected to be an HTTP response, but it is not. + case invalidURLResponse(response: URLResponse) + + /// The response contains an invalid HTTP status code. Code 2002. + /// - Note: + /// By default, status code 200..<400 is recognized as valid. You can override + /// this behavior by conforming to the `ImageDownloaderDelegate`. + /// - response: The received response. + case invalidHTTPStatusCode(response: HTTPURLResponse) + + /// An error happens in the system URL session. Code 2003. + /// - error: The underlying URLSession error object. + case URLSessionError(error: Error) + + /// Data modifying fails on returning a valid data. Code 2004. + /// - task: The failed task. + case dataModifyingFailed(task: SessionDataTask) + + /// The task is done but no URL response found. Code 2005. + /// - task: The failed task. + case noURLResponse(task: SessionDataTask) + } + + /// Represents the error reason during Kingfisher caching system. + /// + /// - fileEnumeratorCreationFailed: Cannot create a file enumerator for a certain disk URL. Code 3001. + /// - invalidFileEnumeratorContent: Cannot get correct file contents from a file enumerator. Code 3002. + /// - invalidURLResource: The file at target URL exists, but its URL resource is unavailable. Code 3003. + /// - cannotLoadDataFromDisk: The file at target URL exists, but the data cannot be loaded from it. Code 3004. + /// - cannotCreateDirectory: Cannot create a folder at a given path. Code 3005. + /// - imageNotExisting: The requested image does not exist in cache. Code 3006. + /// - cannotConvertToData: Cannot convert an object to data for storing. Code 3007. + /// - cannotSerializeImage: Cannot serialize an image to data for storing. Code 3008. + /// - cannotCreateCacheFile: Cannot create the cache file at a certain fileURL under a key. Code 3009. + /// - cannotSetCacheFileAttribute: Cannot set file attributes to a cached file. Code 3010. + public enum CacheErrorReason { + + /// Cannot create a file enumerator for a certain disk URL. Code 3001. + /// - url: The target disk URL from which the file enumerator should be created. + case fileEnumeratorCreationFailed(url: URL) + + /// Cannot get correct file contents from a file enumerator. Code 3002. + /// - url: The target disk URL from which the content of a file enumerator should be got. + case invalidFileEnumeratorContent(url: URL) + + /// The file at target URL exists, but its URL resource is unavailable. Code 3003. + /// - error: The underlying error thrown by file manager. + /// - key: The key used to getting the resource from cache. + /// - url: The disk URL where the target cached file exists. + case invalidURLResource(error: Error, key: String, url: URL) + + /// The file at target URL exists, but the data cannot be loaded from it. Code 3004. + /// - url: The disk URL where the target cached file exists. + /// - error: The underlying error which describes why this error happens. + case cannotLoadDataFromDisk(url: URL, error: Error) + + /// Cannot create a folder at a given path. Code 3005. + /// - path: The disk path where the directory creating operation fails. + /// - error: The underlying error which describes why this error happens. + case cannotCreateDirectory(path: String, error: Error) + + /// The requested image does not exist in cache. Code 3006. + /// - key: Key of the requested image in cache. + case imageNotExisting(key: String) + + /// Cannot convert an object to data for storing. Code 3007. + /// - object: The object which needs be convert to data. + case cannotConvertToData(object: Any, error: Error) + + /// Cannot serialize an image to data for storing. Code 3008. + /// - image: The input image needs to be serialized to cache. + /// - original: The original image data, if exists. + /// - serializer: The `CacheSerializer` used for the image serializing. + case cannotSerializeImage(image: KFCrossPlatformImage?, original: Data?, serializer: CacheSerializer) + + /// Cannot create the cache file at a certain fileURL under a key. Code 3009. + /// - fileURL: The url where the cache file should be created. + /// - key: The cache key used for the cache. When caching a file through `KingfisherManager` and Kingfisher's + /// extension method, it is the resolved cache key based on your input `Source` and the image processors. + /// - data: The data to be cached. + /// - error: The underlying error originally thrown by Foundation when writing the `data` to the disk file at + /// `fileURL`. + case cannotCreateCacheFile(fileURL: URL, key: String, data: Data, error: Error) + + /// Cannot set file attributes to a cached file. Code 3010. + /// - filePath: The path of target cache file. + /// - attributes: The file attribute to be set to the target file. + /// - error: The underlying error originally thrown by Foundation when setting the `attributes` to the disk + /// file at `filePath`. + case cannotSetCacheFileAttribute(filePath: String, attributes: [FileAttributeKey : Any], error: Error) + + /// The disk storage of cache is not ready. Code 3011. + /// + /// This is usually due to extremely lack of space on disk storage, and + /// Kingfisher failed even when creating the cache folder. The disk storage will be in unusable state. Normally, + /// ask user to free some spaces and restart the app to make the disk storage work again. + /// - cacheURL: The intended URL which should be the storage folder. + case diskStorageIsNotReady(cacheURL: URL) + } + + + /// Represents the error reason during image processing phase. + /// + /// - processingFailed: Image processing fails. There is no valid output image from the processor. Code 4001. + public enum ProcessorErrorReason { + /// Image processing fails. There is no valid output image from the processor. Code 4001. + /// - processor: The `ImageProcessor` used to process the image or its data in `item`. + /// - item: The image or its data content. + case processingFailed(processor: ImageProcessor, item: ImageProcessItem) + } + + /// Represents the error reason during image setting in a view related class. + /// + /// - emptySource: The input resource is empty or `nil`. Code 5001. + /// - notCurrentSourceTask: The source task is finished, but it is not the one expected now. Code 5002. + /// - dataProviderError: An error happens during getting data from an `ImageDataProvider`. Code 5003. + public enum ImageSettingErrorReason { + + /// The input resource is empty or `nil`. Code 5001. + case emptySource + + /// The resource task is finished, but it is not the one expected now. This usually happens when you set another + /// resource on the view without cancelling the current on-going one. The previous setting task will fail with + /// this `.notCurrentSourceTask` error when a result got, regardless of it being successful or not for that task. + /// The result of this original task is contained in the associated value. + /// Code 5002. + /// - result: The `RetrieveImageResult` if the source task is finished without problem. `nil` if an error + /// happens. + /// - error: The `Error` if an issue happens during image setting task. `nil` if the task finishes without + /// problem. + /// - source: The original source value of the task. + case notCurrentSourceTask(result: RetrieveImageResult?, error: Error?, source: Source) + + /// An error happens during getting data from an `ImageDataProvider`. Code 5003. + case dataProviderError(provider: ImageDataProvider, error: Error) + + /// No more alternative `Source` can be used in current loading process. It means that the + /// `.alternativeSources` are used and Kingfisher tried to recovery from the original error, but still + /// fails for all the given alternative sources. The associated value holds all the errors encountered during + /// the load process, including the original source loading error and all the alternative sources errors. + /// Code 5004. + case alternativeSourcesExhausted([PropagationError]) + } + + // MARK: Member Cases + + /// Represents the error reason during networking request phase. + case requestError(reason: RequestErrorReason) + /// Represents the error reason during networking response phase. + case responseError(reason: ResponseErrorReason) + /// Represents the error reason during Kingfisher caching system. + case cacheError(reason: CacheErrorReason) + /// Represents the error reason during image processing phase. + case processorError(reason: ProcessorErrorReason) + /// Represents the error reason during image setting in a view related class. + case imageSettingError(reason: ImageSettingErrorReason) + + // MARK: Helper Properties & Methods + + /// Helper property to check whether this error is a `RequestErrorReason.taskCancelled` or not. + public var isTaskCancelled: Bool { + if case .requestError(reason: .taskCancelled) = self { + return true + } + return false + } + + /// Helper method to check whether this error is a `ResponseErrorReason.invalidHTTPStatusCode` and the + /// associated value is a given status code. + /// + /// - Parameter code: The given status code. + /// - Returns: If `self` is a `ResponseErrorReason.invalidHTTPStatusCode` error + /// and its status code equals to `code`, `true` is returned. Otherwise, `false`. + public func isInvalidResponseStatusCode(_ code: Int) -> Bool { + if case .responseError(reason: .invalidHTTPStatusCode(let response)) = self { + return response.statusCode == code + } + return false + } + + public var isInvalidResponseStatusCode: Bool { + if case .responseError(reason: .invalidHTTPStatusCode) = self { + return true + } + return false + } + + /// Helper property to check whether this error is a `ImageSettingErrorReason.notCurrentSourceTask` or not. + /// When a new image setting task starts while the old one is still running, the new task identifier will be + /// set and the old one is overwritten. A `.notCurrentSourceTask` error will be raised when the old task finishes + /// to let you know the setting process finishes with a certain result, but the image view or button is not set. + public var isNotCurrentTask: Bool { + if case .imageSettingError(reason: .notCurrentSourceTask(_, _, _)) = self { + return true + } + return false + } + + var isLowDataModeConstrained: Bool { + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *), + case .responseError(reason: .URLSessionError(let sessionError)) = self, + let urlError = sessionError as? URLError, + urlError.networkUnavailableReason == .constrained + { + return true + } + return false + } + +} + +// MARK: - LocalizedError Conforming +extension KingfisherError: LocalizedError { + + /// A localized message describing what error occurred. + public var errorDescription: String? { + switch self { + case .requestError(let reason): return reason.errorDescription + case .responseError(let reason): return reason.errorDescription + case .cacheError(let reason): return reason.errorDescription + case .processorError(let reason): return reason.errorDescription + case .imageSettingError(let reason): return reason.errorDescription + } + } +} + + +// MARK: - CustomNSError Conforming +extension KingfisherError: CustomNSError { + + /// The error domain of `KingfisherError`. All errors from Kingfisher is under this domain. + public static let domain = "com.onevcat.Kingfisher.Error" + + /// The error code within the given domain. + public var errorCode: Int { + switch self { + case .requestError(let reason): return reason.errorCode + case .responseError(let reason): return reason.errorCode + case .cacheError(let reason): return reason.errorCode + case .processorError(let reason): return reason.errorCode + case .imageSettingError(let reason): return reason.errorCode + } + } +} + +extension KingfisherError.RequestErrorReason { + var errorDescription: String? { + switch self { + case .emptyRequest: + return "The request is empty or `nil`." + case .invalidURL(let request): + return "The request contains an invalid or empty URL. Request: \(request)." + case .taskCancelled(let task, let token): + return "The session task was cancelled. Task: \(task), cancel token: \(token)." + } + } + + var errorCode: Int { + switch self { + case .emptyRequest: return 1001 + case .invalidURL: return 1002 + case .taskCancelled: return 1003 + } + } +} + +extension KingfisherError.ResponseErrorReason { + var errorDescription: String? { + switch self { + case .invalidURLResponse(let response): + return "The URL response is invalid: \(response)" + case .invalidHTTPStatusCode(let response): + return "The HTTP status code in response is invalid. Code: \(response.statusCode), response: \(response)." + case .URLSessionError(let error): + return "A URL session error happened. The underlying error: \(error)" + case .dataModifyingFailed(let task): + return "The data modifying delegate returned `nil` for the downloaded data. Task: \(task)." + case .noURLResponse(let task): + return "No URL response received. Task: \(task)," + } + } + + var errorCode: Int { + switch self { + case .invalidURLResponse: return 2001 + case .invalidHTTPStatusCode: return 2002 + case .URLSessionError: return 2003 + case .dataModifyingFailed: return 2004 + case .noURLResponse: return 2005 + } + } +} + +extension KingfisherError.CacheErrorReason { + var errorDescription: String? { + switch self { + case .fileEnumeratorCreationFailed(let url): + return "Cannot create file enumerator for URL: \(url)." + case .invalidFileEnumeratorContent(let url): + return "Cannot get contents from the file enumerator at URL: \(url)." + case .invalidURLResource(let error, let key, let url): + return "Cannot get URL resource values or data for the given URL: \(url). " + + "Cache key: \(key). Underlying error: \(error)" + case .cannotLoadDataFromDisk(let url, let error): + return "Cannot load data from disk at URL: \(url). Underlying error: \(error)" + case .cannotCreateDirectory(let path, let error): + return "Cannot create directory at given path: Path: \(path). Underlying error: \(error)" + case .imageNotExisting(let key): + return "The image is not in cache, but you requires it should only be " + + "from cache by enabling the `.onlyFromCache` option. Key: \(key)." + case .cannotConvertToData(let object, let error): + return "Cannot convert the input object to a `Data` object when storing it to disk cache. " + + "Object: \(object). Underlying error: \(error)" + case .cannotSerializeImage(let image, let originalData, let serializer): + return "Cannot serialize an image due to the cache serializer returning `nil`. " + + "Image: \(String(describing:image)), original data: \(String(describing: originalData)), " + + "serializer: \(serializer)." + case .cannotCreateCacheFile(let fileURL, let key, let data, let error): + return "Cannot create cache file at url: \(fileURL), key: \(key), data length: \(data.count). " + + "Underlying foundation error: \(error)." + case .cannotSetCacheFileAttribute(let filePath, let attributes, let error): + return "Cannot set file attribute for the cache file at path: \(filePath), attributes: \(attributes)." + + "Underlying foundation error: \(error)." + case .diskStorageIsNotReady(let cacheURL): + return "The disk storage is not ready to use yet at URL: '\(cacheURL)'. " + + "This is usually caused by extremely lack of disk space. Ask users to free up some space and restart the app." + } + } + + var errorCode: Int { + switch self { + case .fileEnumeratorCreationFailed: return 3001 + case .invalidFileEnumeratorContent: return 3002 + case .invalidURLResource: return 3003 + case .cannotLoadDataFromDisk: return 3004 + case .cannotCreateDirectory: return 3005 + case .imageNotExisting: return 3006 + case .cannotConvertToData: return 3007 + case .cannotSerializeImage: return 3008 + case .cannotCreateCacheFile: return 3009 + case .cannotSetCacheFileAttribute: return 3010 + case .diskStorageIsNotReady: return 3011 + } + } +} + +extension KingfisherError.ProcessorErrorReason { + var errorDescription: String? { + switch self { + case .processingFailed(let processor, let item): + return "Processing image failed. Processor: \(processor). Processing item: \(item)." + } + } + + var errorCode: Int { + switch self { + case .processingFailed: return 4001 + } + } +} + +extension KingfisherError.ImageSettingErrorReason { + var errorDescription: String? { + switch self { + case .emptySource: + return "The input resource is empty." + case .notCurrentSourceTask(let result, let error, let resource): + if let result = result { + return "Retrieving resource succeeded, but this source is " + + "not the one currently expected. Result: \(result). Resource: \(resource)." + } else if let error = error { + return "Retrieving resource failed, and this resource is " + + "not the one currently expected. Error: \(error). Resource: \(resource)." + } else { + return nil + } + case .dataProviderError(let provider, let error): + return "Image data provider fails to provide data. Provider: \(provider), error: \(error)" + case .alternativeSourcesExhausted(let errors): + return "Image setting from alternaive sources failed: \(errors)" + } + } + + var errorCode: Int { + switch self { + case .emptySource: return 5001 + case .notCurrentSourceTask: return 5002 + case .dataProviderError: return 5003 + case .alternativeSourcesExhausted: return 5004 + } + } +} diff --git a/Pods/Kingfisher/Sources/General/KingfisherManager.swift b/Pods/Kingfisher/Sources/General/KingfisherManager.swift new file mode 100644 index 0000000..48d97d1 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherManager.swift @@ -0,0 +1,731 @@ +// +// KingfisherManager.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +import Foundation + +/// The downloading progress block type. +/// The parameter value is the `receivedSize` of current response. +/// The second parameter is the total expected data length from response's "Content-Length" header. +/// If the expected length is not available, this block will not be called. +public typealias DownloadProgressBlock = ((_ receivedSize: Int64, _ totalSize: Int64) -> Void) + +/// Represents the result of a Kingfisher retrieving image task. +public struct RetrieveImageResult { + + /// Gets the image object of this result. + public let image: KFCrossPlatformImage + + /// Gets the cache source of the image. It indicates from which layer of cache this image is retrieved. + /// If the image is just downloaded from network, `.none` will be returned. + public let cacheType: CacheType + + /// The `Source` which this result is related to. This indicated where the `image` of `self` is referring. + public let source: Source + + /// The original `Source` from which the retrieve task begins. It can be different from the `source` property. + /// When an alternative source loading happened, the `source` will be the replacing loading target, while the + /// `originalSource` will be kept as the initial `source` which issued the image loading process. + public let originalSource: Source +} + +/// A struct that stores some related information of an `KingfisherError`. It provides some context information for +/// a pure error so you can identify the error easier. +public struct PropagationError { + + /// The `Source` to which current `error` is bound. + public let source: Source + + /// The actual error happens in framework. + public let error: KingfisherError +} + + +/// The downloading task updated block type. The parameter `newTask` is the updated new task of image setting process. +/// It is a `nil` if the image loading does not require an image downloading process. If an image downloading is issued, +/// this value will contain the actual `DownloadTask` for you to keep and cancel it later if you need. +public typealias DownloadTaskUpdatedBlock = ((_ newTask: DownloadTask?) -> Void) + +/// Main manager class of Kingfisher. It connects Kingfisher downloader and cache, +/// to provide a set of convenience methods to use Kingfisher for tasks. +/// You can use this class to retrieve an image via a specified URL from web or cache. +public class KingfisherManager { + + /// Represents a shared manager used across Kingfisher. + /// Use this instance for getting or storing images with Kingfisher. + public static let shared = KingfisherManager() + + // Mark: Public Properties + /// The `ImageCache` used by this manager. It is `ImageCache.default` by default. + /// If a cache is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be + /// used instead. + public var cache: ImageCache + + /// The `ImageDownloader` used by this manager. It is `ImageDownloader.default` by default. + /// If a downloader is specified in `KingfisherManager.defaultOptions`, the value in `defaultOptions` will be + /// used instead. + public var downloader: ImageDownloader + + /// Default options used by the manager. This option will be used in + /// Kingfisher manager related methods, as well as all view extension methods. + /// You can also passing other options for each image task by sending an `options` parameter + /// to Kingfisher's APIs. The per image options will overwrite the default ones, + /// if the option exists in both. + public var defaultOptions = KingfisherOptionsInfo.empty + + // Use `defaultOptions` to overwrite the `downloader` and `cache`. + private var currentDefaultOptions: KingfisherOptionsInfo { + return [.downloader(downloader), .targetCache(cache)] + defaultOptions + } + + private let processingQueue: CallbackQueue + + private convenience init() { + self.init(downloader: .default, cache: .default) + } + + /// Creates an image setting manager with specified downloader and cache. + /// + /// - Parameters: + /// - downloader: The image downloader used to download images. + /// - cache: The image cache which stores memory and disk images. + public init(downloader: ImageDownloader, cache: ImageCache) { + self.downloader = downloader + self.cache = cache + + let processQueueName = "com.onevcat.Kingfisher.KingfisherManager.processQueue.\(UUID().uuidString)" + processingQueue = .dispatch(DispatchQueue(label: processQueueName)) + } + + // MARK: - Getting Images + + /// Gets an image from a given resource. + /// - Parameters: + /// - resource: The `Resource` object defines data information like key or URL. + /// - options: Options to use when creating the image. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in + /// main queue. + /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This + /// usually happens when an alternative source is used to replace the original (failed) + /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` + /// the new task. + /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked + /// from the `options.callbackQueue`. If not specified, the main queue will be used. + /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, + /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// + /// - Note: + /// This method will first check whether the requested `resource` is already in cache or not. If cached, + /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it + /// will download the `resource`, store it in cache, then call `completionHandler`. + @discardableResult + public func retrieveImage( + with resource: Resource, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + return retrieveImage( + with: resource.convertToSource(), + options: options, + progressBlock: progressBlock, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler + ) + } + + /// Gets an image from a given resource. + /// + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - options: Options to use when creating the image. + /// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an + /// `expectedContentLength`, this block will not be called. `progressBlock` is always called in + /// main queue. + /// - downloadTaskUpdated: Called when a new image downloading task is created for current image retrieving. This + /// usually happens when an alternative source is used to replace the original (failed) + /// task. You can update your reference of `DownloadTask` if you want to manually `cancel` + /// the new task. + /// - completionHandler: Called when the image retrieved and set finished. This completion handler will be invoked + /// from the `options.callbackQueue`. If not specified, the main queue will be used. + /// - Returns: A task represents the image downloading. If there is a download task starts for `.network` resource, + /// the started `DownloadTask` is returned. Otherwise, `nil` is returned. + /// + /// - Note: + /// This method will first check whether the requested `source` is already in cache or not. If cached, + /// it returns `nil` and invoke the `completionHandler` after the cached image retrieved. Otherwise, it + /// will try to load the `source`, store it in cache, then call `completionHandler`. + /// + public func retrieveImage( + with source: Source, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let options = currentDefaultOptions + (options ?? .empty) + let info = KingfisherParsedOptionsInfo(options) + return retrieveImage( + with: source, + options: info, + progressBlock: progressBlock, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler) + } + + func retrieveImage( + with source: Source, + options: KingfisherParsedOptionsInfo, + progressBlock: DownloadProgressBlock? = nil, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + var info = options + if let block = progressBlock { + info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + return retrieveImage( + with: source, + options: info, + downloadTaskUpdated: downloadTaskUpdated, + completionHandler: completionHandler) + } + + func retrieveImage( + with source: Source, + options: KingfisherParsedOptionsInfo, + downloadTaskUpdated: DownloadTaskUpdatedBlock? = nil, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let retrievingContext = RetrievingContext(options: options, originalSource: source) + var retryContext: RetryContext? + + func startNewRetrieveTask( + with source: Source, + downloadTaskUpdated: DownloadTaskUpdatedBlock? + ) { + let newTask = self.retrieveImage(with: source, context: retrievingContext) { result in + handler(currentSource: source, result: result) + } + downloadTaskUpdated?(newTask) + } + + func failCurrentSource(_ source: Source, with error: KingfisherError) { + // Skip alternative sources if the user cancelled it. + guard !error.isTaskCancelled else { + completionHandler?(.failure(error)) + return + } + // When low data mode constrained error, retry with the low data mode source instead of use alternative on fly. + guard !error.isLowDataModeConstrained else { + if let source = retrievingContext.options.lowDataModeSource { + retrievingContext.options.lowDataModeSource = nil + startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated) + } else { + // This should not happen. + completionHandler?(.failure(error)) + } + return + } + if let nextSource = retrievingContext.popAlternativeSource() { + retrievingContext.appendError(error, to: source) + startNewRetrieveTask(with: nextSource, downloadTaskUpdated: downloadTaskUpdated) + } else { + // No other alternative source. Finish with error. + if retrievingContext.propagationErrors.isEmpty { + completionHandler?(.failure(error)) + } else { + retrievingContext.appendError(error, to: source) + let finalError = KingfisherError.imageSettingError( + reason: .alternativeSourcesExhausted(retrievingContext.propagationErrors) + ) + completionHandler?(.failure(finalError)) + } + } + } + + func handler(currentSource: Source, result: (Result)) -> Void { + switch result { + case .success: + completionHandler?(result) + case .failure(let error): + if let retryStrategy = options.retryStrategy { + let context = retryContext?.increaseRetryCount() ?? RetryContext(source: source, error: error) + retryContext = context + + retryStrategy.retry(context: context) { decision in + switch decision { + case .retry(let userInfo): + retryContext?.userInfo = userInfo + startNewRetrieveTask(with: source, downloadTaskUpdated: downloadTaskUpdated) + case .stop: + failCurrentSource(currentSource, with: error) + } + } + } else { + failCurrentSource(currentSource, with: error) + } + } + } + + return retrieveImage( + with: source, + context: retrievingContext) + { + result in + handler(currentSource: source, result: result) + } + + } + + private func retrieveImage( + with source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> DownloadTask? + { + let options = context.options + if options.forceRefresh { + return loadAndCacheImage( + source: source, + context: context, + completionHandler: completionHandler)?.value + + } else { + let loadedFromCache = retrieveImageFromCache( + source: source, + context: context, + completionHandler: completionHandler) + + if loadedFromCache { + return nil + } + + if options.onlyFromCache { + let error = KingfisherError.cacheError(reason: .imageNotExisting(key: source.cacheKey)) + completionHandler?(.failure(error)) + return nil + } + + return loadAndCacheImage( + source: source, + context: context, + completionHandler: completionHandler)?.value + } + } + + func provideImage( + provider: ImageDataProvider, + options: KingfisherParsedOptionsInfo, + completionHandler: ((Result) -> Void)?) + { + guard let completionHandler = completionHandler else { return } + provider.data { result in + switch result { + case .success(let data): + (options.processingQueue ?? self.processingQueue).execute { + let processor = options.processor + let processingItem = ImageProcessItem.data(data) + guard let image = processor.process(item: processingItem, options: options) else { + options.callbackQueue.execute { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: processingItem)) + completionHandler(.failure(error)) + } + return + } + + options.callbackQueue.execute { + let result = ImageLoadingResult(image: image, url: nil, originalData: data) + completionHandler(.success(result)) + } + } + case .failure(let error): + options.callbackQueue.execute { + let error = KingfisherError.imageSettingError( + reason: .dataProviderError(provider: provider, error: error)) + completionHandler(.failure(error)) + } + + } + } + } + + private func cacheImage( + source: Source, + options: KingfisherParsedOptionsInfo, + context: RetrievingContext, + result: Result, + completionHandler: ((Result) -> Void)? + ) + { + switch result { + case .success(let value): + let needToCacheOriginalImage = options.cacheOriginalImage && + options.processor != DefaultImageProcessor.default + let coordinator = CacheCallbackCoordinator( + shouldWaitForCache: options.waitForCache, shouldCacheOriginal: needToCacheOriginalImage) + let result = RetrieveImageResult( + image: options.imageModifier?.modify(value.image) ?? value.image, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + // Add image to cache. + let targetCache = options.targetCache ?? self.cache + targetCache.store( + value.image, + original: value.originalData, + forKey: source.cacheKey, + options: options, + toDisk: !options.cacheMemoryOnly) + { + _ in + coordinator.apply(.cachingImage) { + completionHandler?(.success(result)) + } + } + + // Add original image to cache if necessary. + + if needToCacheOriginalImage { + let originalCache = options.originalCache ?? targetCache + originalCache.storeToDisk( + value.originalData, + forKey: source.cacheKey, + processorIdentifier: DefaultImageProcessor.default.identifier, + expiration: options.diskCacheExpiration) + { + _ in + coordinator.apply(.cachingOriginalImage) { + completionHandler?(.success(result)) + } + } + } + + coordinator.apply(.cacheInitiated) { + completionHandler?(.success(result)) + } + + case .failure(let error): + completionHandler?(.failure(error)) + } + } + + @discardableResult + func loadAndCacheImage( + source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> DownloadTask.WrappedTask? + { + let options = context.options + func _cacheImage(_ result: Result) { + cacheImage( + source: source, + options: options, + context: context, + result: result, + completionHandler: completionHandler + ) + } + + switch source { + case .network(let resource): + let downloader = options.downloader ?? self.downloader + let task = downloader.downloadImage( + with: resource.downloadURL, options: options, completionHandler: _cacheImage + ) + + + // The code below is neat, but it fails the Swift 5.2 compiler with a runtime crash when + // `BUILD_LIBRARY_FOR_DISTRIBUTION` is turned on. I believe it is a bug in the compiler. + // Let's fallback to a traditional style before it can be fixed in Swift. + // + // https://github.com/onevcat/Kingfisher/issues/1436 + // + // return task.map(DownloadTask.WrappedTask.download) + + if let task = task { + return .download(task) + } else { + return nil + } + + case .provider(let provider): + provideImage(provider: provider, options: options, completionHandler: _cacheImage) + return .dataProviding + } + } + + /// Retrieves image from memory or disk cache. + /// + /// - Parameters: + /// - source: The target source from which to get image. + /// - key: The key to use when caching the image. + /// - url: Image request URL. This is not used when retrieving image from cache. It is just used for + /// `RetrieveImageResult` callback compatibility. + /// - options: Options on how to get the image from image cache. + /// - completionHandler: Called when the image retrieving finishes, either with succeeded + /// `RetrieveImageResult` or an error. + /// - Returns: `true` if the requested image or the original image before being processed is existing in cache. + /// Otherwise, this method returns `false`. + /// + /// - Note: + /// The image retrieving could happen in either memory cache or disk cache. The `.processor` option in + /// `options` will be considered when searching in the cache. If no processed image is found, Kingfisher + /// will try to check whether an original version of that image is existing or not. If there is already an + /// original, Kingfisher retrieves it from cache and processes it. Then, the processed image will be store + /// back to cache for later use. + func retrieveImageFromCache( + source: Source, + context: RetrievingContext, + completionHandler: ((Result) -> Void)?) -> Bool + { + let options = context.options + // 1. Check whether the image was already in target cache. If so, just get it. + let targetCache = options.targetCache ?? cache + let key = source.cacheKey + let targetImageCached = targetCache.imageCachedType( + forKey: key, processorIdentifier: options.processor.identifier) + + let validCache = targetImageCached.cached && + (options.fromMemoryCacheOrRefresh == false || targetImageCached == .memory) + if validCache { + targetCache.retrieveImage(forKey: key, options: options) { result in + guard let completionHandler = completionHandler else { return } + options.callbackQueue.execute { + result.match( + onSuccess: { cacheResult in + let value: Result + if let image = cacheResult.image { + value = result.map { + RetrieveImageResult( + image: options.imageModifier?.modify(image) ?? image, + cacheType: $0.cacheType, + source: source, + originalSource: context.originalSource + ) + } + } else { + value = .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) + } + completionHandler(value) + }, + onFailure: { _ in + completionHandler(.failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key)))) + } + ) + } + } + return true + } + + // 2. Check whether the original image exists. If so, get it, process it, save to storage and return. + let originalCache = options.originalCache ?? targetCache + // No need to store the same file in the same cache again. + if originalCache === targetCache && options.processor == DefaultImageProcessor.default { + return false + } + + // Check whether the unprocessed image existing or not. + let originalImageCacheType = originalCache.imageCachedType( + forKey: key, processorIdentifier: DefaultImageProcessor.default.identifier) + let canAcceptDiskCache = !options.fromMemoryCacheOrRefresh + + let canUseOriginalImageCache = + (canAcceptDiskCache && originalImageCacheType.cached) || + (!canAcceptDiskCache && originalImageCacheType == .memory) + + if canUseOriginalImageCache { + // Now we are ready to get found the original image from cache. We need the unprocessed image, so remove + // any processor from options first. + var optionsWithoutProcessor = options + optionsWithoutProcessor.processor = DefaultImageProcessor.default + originalCache.retrieveImage(forKey: key, options: optionsWithoutProcessor) { result in + + result.match( + onSuccess: { cacheResult in + guard let image = cacheResult.image else { + assertionFailure("The image (under key: \(key) should be existing in the original cache.") + return + } + + let processor = options.processor + (options.processingQueue ?? self.processingQueue).execute { + let item = ImageProcessItem.image(image) + guard let processedImage = processor.process(item: item, options: options) else { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: item)) + options.callbackQueue.execute { completionHandler?(.failure(error)) } + return + } + + var cacheOptions = options + cacheOptions.callbackQueue = .untouch + + let coordinator = CacheCallbackCoordinator( + shouldWaitForCache: options.waitForCache, shouldCacheOriginal: false) + + let result = RetrieveImageResult( + image: options.imageModifier?.modify(processedImage) ?? processedImage, + cacheType: .none, + source: source, + originalSource: context.originalSource + ) + + targetCache.store( + processedImage, + forKey: key, + options: cacheOptions, + toDisk: !options.cacheMemoryOnly) + { + _ in + coordinator.apply(.cachingImage) { + options.callbackQueue.execute { completionHandler?(.success(result)) } + } + } + + coordinator.apply(.cacheInitiated) { + options.callbackQueue.execute { completionHandler?(.success(result)) } + } + } + }, + onFailure: { _ in + // This should not happen actually, since we already confirmed `originalImageCached` is `true`. + // Just in case... + options.callbackQueue.execute { + completionHandler?( + .failure(KingfisherError.cacheError(reason: .imageNotExisting(key: key))) + ) + } + } + ) + } + return true + } + + return false + } +} + +class RetrievingContext { + + var options: KingfisherParsedOptionsInfo + + let originalSource: Source + var propagationErrors: [PropagationError] = [] + + init(options: KingfisherParsedOptionsInfo, originalSource: Source) { + self.originalSource = originalSource + self.options = options + } + + func popAlternativeSource() -> Source? { + guard var alternativeSources = options.alternativeSources, !alternativeSources.isEmpty else { + return nil + } + let nextSource = alternativeSources.removeFirst() + options.alternativeSources = alternativeSources + return nextSource + } + + @discardableResult + func appendError(_ error: KingfisherError, to source: Source) -> [PropagationError] { + let item = PropagationError(source: source, error: error) + propagationErrors.append(item) + return propagationErrors + } +} + +class CacheCallbackCoordinator { + + enum State { + case idle + case imageCached + case originalImageCached + case done + } + + enum Action { + case cacheInitiated + case cachingImage + case cachingOriginalImage + } + + private let shouldWaitForCache: Bool + private let shouldCacheOriginal: Bool + private let stateQueue: DispatchQueue + private var threadSafeState: State = .idle + + private (set) var state: State { + set { stateQueue.sync { threadSafeState = newValue } } + get { stateQueue.sync { threadSafeState } } + } + + init(shouldWaitForCache: Bool, shouldCacheOriginal: Bool) { + self.shouldWaitForCache = shouldWaitForCache + self.shouldCacheOriginal = shouldCacheOriginal + let stateQueueName = "com.onevcat.Kingfisher.CacheCallbackCoordinator.stateQueue.\(UUID().uuidString)" + self.stateQueue = DispatchQueue(label: stateQueueName) + } + + func apply(_ action: Action, trigger: () -> Void) { + switch (state, action) { + case (.done, _): + break + + // From .idle + case (.idle, .cacheInitiated): + if !shouldWaitForCache { + state = .done + trigger() + } + case (.idle, .cachingImage): + if shouldCacheOriginal { + state = .imageCached + } else { + state = .done + trigger() + } + case (.idle, .cachingOriginalImage): + state = .originalImageCached + + // From .imageCached + case (.imageCached, .cachingOriginalImage): + state = .done + trigger() + + // From .originalImageCached + case (.originalImageCached, .cachingImage): + state = .done + trigger() + + default: + assertionFailure("This case should not happen in CacheCallbackCoordinator: \(state) - \(action)") + } + } +} diff --git a/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift new file mode 100644 index 0000000..5f2aea6 --- /dev/null +++ b/Pods/Kingfisher/Sources/General/KingfisherOptionsInfo.swift @@ -0,0 +1,400 @@ +// +// KingfisherOptionsInfo.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/23. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + + +/// KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. +/// You can use the enum of option item with value to control some behaviors of Kingfisher. +public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem] + +extension Array where Element == KingfisherOptionsInfoItem { + static let empty: KingfisherOptionsInfo = [] +} + +/// Represents the available option items could be used in `KingfisherOptionsInfo`. +public enum KingfisherOptionsInfoItem { + + /// Kingfisher will use the associated `ImageCache` object when handling related operations, + /// including trying to retrieve the cached images and store the downloaded image to it. + case targetCache(ImageCache) + + /// The `ImageCache` for storing and retrieving original images. If `originalCache` is + /// contained in the options, it will be preferred for storing and retrieving original images. + /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images. + /// + /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is + /// applied in the option, the original image will be stored to this `originalCache`. At the + /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`, + /// Kingfisher will try to search the original image to check whether it is already there. If found, + /// it will be used and applied with the given processor. It is an optimization for not downloading + /// the same image for multiple times. + case originalCache(ImageCache) + + /// Kingfisher will use the associated `ImageDownloader` object to download the requested images. + case downloader(ImageDownloader) + + /// Member for animation transition when using `UIImageView`. Kingfisher will use the `ImageTransition` of + /// this enum to animate the image in if it is downloaded from web. The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, set `.forceRefresh` as well. + case transition(ImageTransition) + + /// Associated `Float` value will be set as the priority of image download task. The value for it should be + /// between 0.0~1.0. If this option not set, the default value (`URLSessionTask.defaultPriority`) will be used. + case downloadPriority(Float) + + /// If set, Kingfisher will ignore the cache and try to start a download task for the image source. + case forceRefresh + + /// If set, Kingfisher will try to retrieve the image from memory cache first. If the image is not in memory + /// cache, then it will ignore the disk cache but download the image again from network. This is useful when + /// you want to display a changeable image behind the same url at the same app session, while avoiding download + /// it for multiple times. + case fromMemoryCacheOrRefresh + + /// If set, setting the image to an image view will happen with transition even when retrieved from cache. + /// See `.transition` option for more. + case forceTransition + + /// If set, Kingfisher will only cache the value in memory but not in disk. + case cacheMemoryOnly + + /// If set, Kingfisher will wait for caching operation to be completed before calling the completion block. + case waitForCache + + /// If set, Kingfisher will only try to retrieve the image from cache, but not from network. If the image is not in + /// cache, the image retrieving will fail with the `KingfisherError.cacheError` with `.imageNotExisting` as its + /// reason. + case onlyFromCache + + /// Decode the image in background thread before using. It will decode the downloaded image data and do a off-screen + /// rendering to extract pixel information in background. This can speed up display, but will cost more time to + /// prepare the image for using. + case backgroundDecode + + /// The associated value will be used as the target queue of dispatch callbacks when retrieving images from + /// cache. If not set, Kingfisher will use `.mainCurrentOrAsync` for callbacks. + /// + /// - Note: + /// This option does not affect the callbacks for UI related extension methods. You will always get the + /// callbacks called from main queue. + case callbackQueue(CallbackQueue) + + /// The associated value will be used as the scale factor when converting retrieved data to an image. + /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing + /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0. + case scaleFactor(CGFloat) + + /// Whether all the animated image data should be preloaded. Default is `false`, which means only following frames + /// will be loaded on need. If `true`, all the animated image data will be loaded and decoded into memory. + /// + /// This option is mainly used for back compatibility internally. You should not set it directly. Instead, + /// you should choose the image view class to control the GIF data loading. There are two classes in Kingfisher + /// support to display a GIF image. `AnimatedImageView` does not preload all data, it takes much less memory, but + /// uses more CPU when display. While a normal image view (`UIImageView` or `NSImageView`) loads all data at once, + /// which uses more memory but only decode image frames once. + case preloadAllAnimationData + + /// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// The original request will be sent without any modification by default. + case requestModifier(AsyncImageDownloadRequestModifier) + + /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. + /// This is the possibility you can modify the image download request during redirect. You can modify the request for + /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url + /// mapping. + /// The original redirection request will be sent without any modification by default. + case redirectHandler(ImageDownloadRedirectHandler) + + /// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image + /// and/or apply some filter on it. If a cache is connected to the downloader (it happens when you are using + /// KingfisherManager or any of the view extension methods), the converted image will also be sent to cache as well. + /// If not set, the `DefaultImageProcessor.default` will be used. + case processor(ImageProcessor) + + /// Provides a `CacheSerializer` to convert some data to an image object for + /// retrieving from disk cache or vice versa for storing to disk cache. + /// If not set, the `DefaultCacheSerializer.default` will be used. + case cacheSerializer(CacheSerializer) + + /// An `ImageModifier` is for modifying an image as needed right before it is used. If the image was fetched + /// directly from the downloader, the modifier will run directly after the `ImageProcessor`. If the image is being + /// fetched from a cache, the modifier will run after the `CacheSerializer`. + /// + /// Use `ImageModifier` when you need to set properties that do not persist when caching the image on a concrete + /// type of `Image`, such as the `renderingMode` or the `alignmentInsets` of `UIImage`. + case imageModifier(ImageModifier) + + /// Keep the existing image of image view while setting another image to it. + /// By setting this option, the placeholder image parameter of image view extension method + /// will be ignored and the current image will be kept while loading or downloading the new image. + case keepCurrentImageWhileLoading + + /// If set, Kingfisher will only load the first frame from an animated image file as a single image. + /// Loading an animated images may take too much memory. It will be useful when you want to display a + /// static preview of the first frame from an animated image. + /// + /// This option will be ignored if the target image is not animated image data. + case onlyLoadFirstFrame + + /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original + /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same + /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original + /// images if necessary. + /// + /// The original image will be only cached to disk storage. + case cacheOriginalImage + + /// If set and an image retrieving error occurred Kingfisher will set provided image (or empty) + /// in place of requested one. It's useful when you don't want to show placeholder + /// during loading time but wants to use some default image when requests will be failed. + case onFailureImage(KFCrossPlatformImage?) + + /// If set and used in `ImagePrefetcher`, the prefetching operation will load the images into memory storage + /// aggressively. By default this is not contained in the options, that means if the requested image is already + /// in disk cache, Kingfisher will not try to load it to memory. + case alsoPrefetchToMemory + + /// If set, the disk storage loading will happen in the same calling queue. By default, disk storage file loading + /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk + /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already + /// has an image set. + /// + /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue + /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance. + case loadDiskFileSynchronously + + /// Options to control the writing of data to disk storage + /// If set, options will be passed the store operation for a new files. + case diskStoreWriteOptions(Data.WritingOptions) + + /// The expiration setting for memory cache. By default, the underlying `MemoryStorage.Backend` uses the + /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this associated + /// value to overwrite the config setting for this caching item. + case memoryCacheExpiration(StorageExpiration) + + /// The expiration extending setting for memory cache. The item expiration time will be incremented by this + /// value after access. + /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending + /// value: .cacheTime. + /// + /// To disable extending option at all add memoryCacheAccessExtendingExpiration(.none) to options. + case memoryCacheAccessExtendingExpiration(ExpirationExtending) + + /// The expiration setting for disk cache. By default, the underlying `DiskStorage.Backend` uses the + /// expiration in its config for all items. If set, the `DiskStorage.Backend` will use this associated + /// value to overwrite the config setting for this caching item. + case diskCacheExpiration(StorageExpiration) + + /// The expiration extending setting for disk cache. The item expiration time will be incremented by this value after access. + /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending value: .cacheTime. + /// To disable extending option at all add diskCacheAccessExtendingExpiration(.none) to options. + case diskCacheAccessExtendingExpiration(ExpirationExtending) + + /// Decides on which queue the image processing should happen. By default, Kingfisher uses a pre-defined serial + /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync` + /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of + /// blocking the UI, especially if the processor needs a lot of time to run). + case processingQueue(CallbackQueue) + + /// Enable progressive image loading, Kingfisher will use the associated `ImageProgressive` value to process the + /// progressive JPEG data and display it in a progressive way. + case progressiveJPEG(ImageProgressive) + + /// The alternative sources will be used when the original input `Source` fails. The `Source`s in the associated + /// array will be used to start a new image loading task if the previous task fails due to an error. The image + /// source loading process will stop as soon as a source is loaded successfully. If all `[Source]`s are used but + /// the loading is still failing, an `imageSettingError` with `alternativeSourcesExhausted` as its reason will be + /// thrown out. + /// + /// This option is useful if you want to implement a fallback solution for setting image. + /// + /// User cancellation will not trigger the alternative source loading. + case alternativeSources([Source]) + + /// Provide a retry strategy which will be used when something gets wrong during the image retrieving process from + /// `KingfisherManager`. You can define a strategy by create a type conforming to the `RetryStrategy` protocol. + /// + /// - Note: + /// + /// All extension methods of Kingfisher (`kf` extensions on `UIImageView` or `UIButton`) retrieve images through + /// `KingfisherManager`, so the retry strategy also applies when using them. However, this option does not apply + /// when pass to an `ImageDownloader` or `ImageCache`. + /// + case retryStrategy(RetryStrategy) + + /// The `Source` should be loaded when user enables Low Data Mode and the original source fails with an + /// `NSURLErrorNetworkUnavailableReason.constrained` error. When this option is set, the + /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the + /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a + /// low-resolution version of your image or a local image provider to display a placeholder. + /// + /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will + /// be loaded following the system default behavior, in a normal way. + case lowDataMode(Source?) +} + +// Improve performance by parsing the input `KingfisherOptionsInfo` (self) first. +// So we can prevent the iterating over the options array again and again. +/// The parsed options info used across Kingfisher methods. Each property in this type corresponds a case member +/// in `KingfisherOptionsInfoItem`. When a `KingfisherOptionsInfo` sent to Kingfisher related methods, it will be +/// parsed and converted to a `KingfisherParsedOptionsInfo` first, and pass through the internal methods. +public struct KingfisherParsedOptionsInfo { + + public var targetCache: ImageCache? = nil + public var originalCache: ImageCache? = nil + public var downloader: ImageDownloader? = nil + public var transition: ImageTransition = .none + public var downloadPriority: Float = URLSessionTask.defaultPriority + public var forceRefresh = false + public var fromMemoryCacheOrRefresh = false + public var forceTransition = false + public var cacheMemoryOnly = false + public var waitForCache = false + public var onlyFromCache = false + public var backgroundDecode = false + public var preloadAllAnimationData = false + public var callbackQueue: CallbackQueue = .mainCurrentOrAsync + public var scaleFactor: CGFloat = 1.0 + public var requestModifier: AsyncImageDownloadRequestModifier? = nil + public var redirectHandler: ImageDownloadRedirectHandler? = nil + public var processor: ImageProcessor = DefaultImageProcessor.default + public var imageModifier: ImageModifier? = nil + public var cacheSerializer: CacheSerializer = DefaultCacheSerializer.default + public var keepCurrentImageWhileLoading = false + public var onlyLoadFirstFrame = false + public var cacheOriginalImage = false + public var onFailureImage: Optional = .none + public var alsoPrefetchToMemory = false + public var loadDiskFileSynchronously = false + public var diskStoreWriteOptions: Data.WritingOptions = [] + public var memoryCacheExpiration: StorageExpiration? = nil + public var memoryCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime + public var diskCacheExpiration: StorageExpiration? = nil + public var diskCacheAccessExtendingExpiration: ExpirationExtending = .cacheTime + public var processingQueue: CallbackQueue? = nil + public var progressiveJPEG: ImageProgressive? = nil + public var alternativeSources: [Source]? = nil + public var retryStrategy: RetryStrategy? = nil + public var lowDataModeSource: Source? = nil + + var onDataReceived: [DataReceivingSideEffect]? = nil + + public init(_ info: KingfisherOptionsInfo?) { + guard let info = info else { return } + for option in info { + switch option { + case .targetCache(let value): targetCache = value + case .originalCache(let value): originalCache = value + case .downloader(let value): downloader = value + case .transition(let value): transition = value + case .downloadPriority(let value): downloadPriority = value + case .forceRefresh: forceRefresh = true + case .fromMemoryCacheOrRefresh: fromMemoryCacheOrRefresh = true + case .forceTransition: forceTransition = true + case .cacheMemoryOnly: cacheMemoryOnly = true + case .waitForCache: waitForCache = true + case .onlyFromCache: onlyFromCache = true + case .backgroundDecode: backgroundDecode = true + case .preloadAllAnimationData: preloadAllAnimationData = true + case .callbackQueue(let value): callbackQueue = value + case .scaleFactor(let value): scaleFactor = value + case .requestModifier(let value): requestModifier = value + case .redirectHandler(let value): redirectHandler = value + case .processor(let value): processor = value + case .imageModifier(let value): imageModifier = value + case .cacheSerializer(let value): cacheSerializer = value + case .keepCurrentImageWhileLoading: keepCurrentImageWhileLoading = true + case .onlyLoadFirstFrame: onlyLoadFirstFrame = true + case .cacheOriginalImage: cacheOriginalImage = true + case .onFailureImage(let value): onFailureImage = .some(value) + case .alsoPrefetchToMemory: alsoPrefetchToMemory = true + case .loadDiskFileSynchronously: loadDiskFileSynchronously = true + case .diskStoreWriteOptions(let options): diskStoreWriteOptions = options + case .memoryCacheExpiration(let expiration): memoryCacheExpiration = expiration + case .memoryCacheAccessExtendingExpiration(let expirationExtending): memoryCacheAccessExtendingExpiration = expirationExtending + case .diskCacheExpiration(let expiration): diskCacheExpiration = expiration + case .diskCacheAccessExtendingExpiration(let expirationExtending): diskCacheAccessExtendingExpiration = expirationExtending + case .processingQueue(let queue): processingQueue = queue + case .progressiveJPEG(let value): progressiveJPEG = value + case .alternativeSources(let sources): alternativeSources = sources + case .retryStrategy(let strategy): retryStrategy = strategy + case .lowDataMode(let source): lowDataModeSource = source + } + } + + if originalCache == nil { + originalCache = targetCache + } + } +} + +extension KingfisherParsedOptionsInfo { + var imageCreatingOptions: ImageCreatingOptions { + return ImageCreatingOptions( + scale: scaleFactor, + duration: 0.0, + preloadAll: preloadAllAnimationData, + onlyFirstFrame: onlyLoadFirstFrame) + } +} + +protocol DataReceivingSideEffect: AnyObject { + var onShouldApply: () -> Bool { get set } + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) +} + +class ImageLoadingProgressSideEffect: DataReceivingSideEffect { + + var onShouldApply: () -> Bool = { return true } + + let block: DownloadProgressBlock + + init(_ block: @escaping DownloadProgressBlock) { + self.block = block + } + + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { + guard self.onShouldApply() else { return } + guard let expectedContentLength = task.task.response?.expectedContentLength, + expectedContentLength != -1 else + { + return + } + + let dataLength = Int64(task.mutableData.count) + DispatchQueue.main.async { + self.block(dataLength, expectedContentLength) + } + } +} diff --git a/Pods/Kingfisher/Sources/Image/Filter.swift b/Pods/Kingfisher/Sources/Image/Filter.swift new file mode 100644 index 0000000..6e4b386 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Filter.swift @@ -0,0 +1,146 @@ +// +// Filter.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/31. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +import CoreImage + +// Reuse the same CI Context for all CI drawing. +private let ciContext = CIContext(options: nil) + +/// Represents the type of transformer method, which will be used in to provide a `Filter`. +public typealias Transformer = (CIImage) -> CIImage? + +/// Represents a processor based on a `CIImage` `Filter`. +/// It requires a filter to create an `ImageProcessor`. +public protocol CIImageProcessor: ImageProcessor { + var filter: Filter { get } +} + +extension CIImageProcessor { + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.apply(filter) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// A wrapper struct for a `Transformer` of CIImage filters. A `Filter` +/// value could be used to create a `CIImage` processor. +public struct Filter { + + let transform: Transformer + + public init(transform: @escaping Transformer) { + self.transform = transform + } + + /// Tint filter which will apply a tint color to images. + public static var tint: (KFCrossPlatformColor) -> Filter = { + color in + Filter { + input in + + let colorFilter = CIFilter(name: "CIConstantColorGenerator")! + colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey) + + let filter = CIFilter(name: "CISourceOverCompositing")! + + let colorImage = colorFilter.outputImage + filter.setValue(colorImage, forKey: kCIInputImageKey) + filter.setValue(input, forKey: kCIInputBackgroundImageKey) + + return filter.outputImage?.cropped(to: input.extent) + } + } + + /// Represents color control elements. It is a tuple of + /// `(brightness, contrast, saturation, inputEV)` + public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat) + + /// Color control filter which will apply color control change to images. + public static var colorControl: (ColorElement) -> Filter = { arg -> Filter in + let (brightness, contrast, saturation, inputEV) = arg + return Filter { input in + let paramsColor = [kCIInputBrightnessKey: brightness, + kCIInputContrastKey: contrast, + kCIInputSaturationKey: saturation] + let blackAndWhite = input.applyingFilter("CIColorControls", parameters: paramsColor) + let paramsExposure = [kCIInputEVKey: inputEV] + return blackAndWhite.applyingFilter("CIExposureAdjust", parameters: paramsExposure) + } + } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Applies a `Filter` containing `CIImage` transformer to `self`. + /// + /// - Parameter filter: The filter used to transform `self`. + /// - Returns: A transformed image by input `Filter`. + /// + /// - Note: + /// Only CG-based images are supported. If any error happens + /// during transforming, `self` will be returned. + public func apply(_ filter: Filter) -> KFCrossPlatformImage { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Tint image only works for CG-based image.") + return base + } + + let inputImage = CIImage(cgImage: cgImage) + guard let outputImage = filter.transform(inputImage) else { + return base + } + + guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else { + assertionFailure("[Kingfisher] Can not make an tint image within context.") + return base + } + + #if os(macOS) + return fixedForRetinaPixel(cgImage: result, to: size) + #else + return KFCrossPlatformImage(cgImage: result, scale: base.scale, orientation: base.imageOrientation) + #endif + } + +} + +#endif diff --git a/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift new file mode 100644 index 0000000..8b2480f --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/GIFAnimatedImage.swift @@ -0,0 +1,121 @@ +// +// AnimatedImage.swift +// Kingfisher +// +// Created by onevcat on 2018/09/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import ImageIO + +/// Represents a set of image creating options used in Kingfisher. +public struct ImageCreatingOptions { + + /// The target scale of image needs to be created. + public let scale: CGFloat + + /// The expected animation duration if an animated image being created. + public let duration: TimeInterval + + /// For an animated image, whether or not all frames should be loaded before displaying. + public let preloadAll: Bool + + /// For an animated image, whether or not only the first image should be + /// loaded as a static image. It is useful for preview purpose of an animated image. + public let onlyFirstFrame: Bool + + /// Creates an `ImageCreatingOptions` object. + /// + /// - Parameters: + /// - scale: The target scale of image needs to be created. Default is `1.0`. + /// - duration: The expected animation duration if an animated image being created. + /// A value less or equal to `0.0` means the animated image duration will + /// be determined by the frame data. Default is `0.0`. + /// - preloadAll: For an animated image, whether or not all frames should be loaded before displaying. + /// Default is `false`. + /// - onlyFirstFrame: For an animated image, whether or not only the first image should be + /// loaded as a static image. It is useful for preview purpose of an animated image. + /// Default is `false`. + public init( + scale: CGFloat = 1.0, + duration: TimeInterval = 0.0, + preloadAll: Bool = false, + onlyFirstFrame: Bool = false) + { + self.scale = scale + self.duration = duration + self.preloadAll = preloadAll + self.onlyFirstFrame = onlyFirstFrame + } +} + +/// Represents the decoding for a GIF image. This class extracts frames from an `imageSource`, then +/// hold the images for later use. +public class GIFAnimatedImage { + let images: [KFCrossPlatformImage] + let duration: TimeInterval + + init?(from imageSource: CGImageSource, for info: [String: Any], options: ImageCreatingOptions) { + let frameCount = CGImageSourceGetCount(imageSource) + var images = [KFCrossPlatformImage]() + var gifDuration = 0.0 + + for i in 0 ..< frameCount { + guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, i, info as CFDictionary) else { + return nil + } + + if frameCount == 1 { + gifDuration = .infinity + } else { + // Get current animated GIF frame duration + gifDuration += GIFAnimatedImage.getFrameDuration(from: imageSource, at: i) + } + images.append(KingfisherWrapper.image(cgImage: imageRef, scale: options.scale, refImage: nil)) + if options.onlyFirstFrame { break } + } + self.images = images + self.duration = gifDuration + } + + /// Calculates frame duration for a gif frame out of the kCGImagePropertyGIFDictionary dictionary. + public static func getFrameDuration(from gifInfo: [String: Any]?) -> TimeInterval { + let defaultFrameDuration = 0.1 + guard let gifInfo = gifInfo else { return defaultFrameDuration } + + let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as? NSNumber + let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as? NSNumber + let duration = unclampedDelayTime ?? delayTime + + guard let frameDuration = duration else { return defaultFrameDuration } + return frameDuration.doubleValue > 0.011 ? frameDuration.doubleValue : defaultFrameDuration + } + + /// Calculates frame duration at a specific index for a gif from an `imageSource`. + public static func getFrameDuration(from imageSource: CGImageSource, at index: Int) -> TimeInterval { + guard let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, index, nil) + as? [String: Any] else { return 0.0 } + + let gifInfo = properties[kCGImagePropertyGIFDictionary as String] as? [String: Any] + return getFrameDuration(from: gifInfo) + } +} diff --git a/Pods/Kingfisher/Sources/Image/GraphicsContext.swift b/Pods/Kingfisher/Sources/Image/GraphicsContext.swift new file mode 100644 index 0000000..6d8443c --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/GraphicsContext.swift @@ -0,0 +1,88 @@ +// +// GraphicsContext.swift +// Kingfisher +// +// Created by taras on 19/04/2021. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif +#if canImport(UIKit) +import UIKit +#endif + +enum GraphicsContext { + static func begin(size: CGSize, scale: CGFloat) { + #if os(macOS) + NSGraphicsContext.saveGraphicsState() + #else + UIGraphicsBeginImageContextWithOptions(size, false, scale) + #endif + } + + static func current(size: CGSize, scale: CGFloat, inverting: Bool, cgImage: CGImage?) -> CGContext? { + #if os(macOS) + guard let rep = NSBitmapImageRep( + bitmapDataPlanes: nil, + pixelsWide: Int(size.width), + pixelsHigh: Int(size.height), + bitsPerSample: cgImage?.bitsPerComponent ?? 8, + samplesPerPixel: 4, + hasAlpha: true, + isPlanar: false, + colorSpaceName: .calibratedRGB, + bytesPerRow: 0, + bitsPerPixel: 0) else + { + assertionFailure("[Kingfisher] Image representation cannot be created.") + return nil + } + rep.size = size + guard let context = NSGraphicsContext(bitmapImageRep: rep) else { + assertionFailure("[Kingfisher] Image context cannot be created.") + return nil + } + + NSGraphicsContext.current = context + return context.cgContext + #else + guard let context = UIGraphicsGetCurrentContext() else { + return nil + } + if inverting { // If drawing a CGImage, we need to make context flipped. + context.scaleBy(x: 1.0, y: -1.0) + context.translateBy(x: 0, y: -size.height) + } + return context + #endif + } + + static func end() { + #if os(macOS) + NSGraphicsContext.restoreGraphicsState() + #else + UIGraphicsEndImageContext() + #endif + } +} + diff --git a/Pods/Kingfisher/Sources/Image/Image.swift b/Pods/Kingfisher/Sources/Image/Image.swift new file mode 100644 index 0000000..509dfcd --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Image.swift @@ -0,0 +1,373 @@ +// +// Image.swift +// Kingfisher +// +// Created by Wei Wang on 16/1/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +private var imagesKey: Void? +private var durationKey: Void? +#else +import UIKit +import MobileCoreServices +private var imageSourceKey: Void? +#endif + +#if !os(watchOS) +import CoreImage +#endif + +import CoreGraphics +import ImageIO + +private var animatedImageDataKey: Void? +private var imageFrameCountKey: Void? + +// MARK: - Image Properties +extension KingfisherWrapper where Base: KFCrossPlatformImage { + private(set) var animatedImageData: Data? { + get { return getAssociatedObject(base, &animatedImageDataKey) } + set { setRetainedAssociatedObject(base, &animatedImageDataKey, newValue) } + } + + public var imageFrameCount: Int? { + get { return getAssociatedObject(base, &imageFrameCountKey) } + set { setRetainedAssociatedObject(base, &imageFrameCountKey, newValue) } + } + + #if os(macOS) + var cgImage: CGImage? { + return base.cgImage(forProposedRect: nil, context: nil, hints: nil) + } + + var scale: CGFloat { + return 1.0 + } + + private(set) var images: [KFCrossPlatformImage]? { + get { return getAssociatedObject(base, &imagesKey) } + set { setRetainedAssociatedObject(base, &imagesKey, newValue) } + } + + private(set) var duration: TimeInterval { + get { return getAssociatedObject(base, &durationKey) ?? 0.0 } + set { setRetainedAssociatedObject(base, &durationKey, newValue) } + } + + var size: CGSize { + return base.representations.reduce(.zero) { size, rep in + let width = max(size.width, CGFloat(rep.pixelsWide)) + let height = max(size.height, CGFloat(rep.pixelsHigh)) + return CGSize(width: width, height: height) + } + } + #else + var cgImage: CGImage? { return base.cgImage } + var scale: CGFloat { return base.scale } + var images: [KFCrossPlatformImage]? { return base.images } + var duration: TimeInterval { return base.duration } + var size: CGSize { return base.size } + + /// The image source reference of current image. + public private(set) var imageSource: CGImageSource? { + get { return getAssociatedObject(base, &imageSourceKey) } + set { setRetainedAssociatedObject(base, &imageSourceKey, newValue) } + } + #endif + + // Bitmap memory cost with bytes. + var cost: Int { + let pixel = Int(size.width * size.height * scale * scale) + guard let cgImage = cgImage else { + return pixel * 4 + } + return pixel * cgImage.bitsPerPixel / 8 + } +} + +// MARK: - Image Conversion +extension KingfisherWrapper where Base: KFCrossPlatformImage { + #if os(macOS) + static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage { + return KFCrossPlatformImage(cgImage: cgImage, size: .zero) + } + + /// Normalize the image. This getter does nothing on macOS but return the image itself. + public var normalized: KFCrossPlatformImage { return base } + + #else + /// Creating an image from a give `CGImage` at scale and orientation for refImage. The method signature is for + /// compatibility of macOS version. + static func image(cgImage: CGImage, scale: CGFloat, refImage: KFCrossPlatformImage?) -> KFCrossPlatformImage { + return KFCrossPlatformImage(cgImage: cgImage, scale: scale, orientation: refImage?.imageOrientation ?? .up) + } + + /// Returns normalized image for current `base` image. + /// This method will try to redraw an image with orientation and scale considered. + public var normalized: KFCrossPlatformImage { + // prevent animated image (GIF) lose it's images + guard images == nil else { return base.copy() as! KFCrossPlatformImage } + // No need to do anything if already up + guard base.imageOrientation != .up else { return base.copy() as! KFCrossPlatformImage } + + return draw(to: size, inverting: true, refImage: KFCrossPlatformImage()) { + fixOrientation(in: $0) + return true + } + } + + func fixOrientation(in context: CGContext) { + + var transform = CGAffineTransform.identity + + let orientation = base.imageOrientation + + switch orientation { + case .down, .downMirrored: + transform = transform.translatedBy(x: size.width, y: size.height) + transform = transform.rotated(by: .pi) + case .left, .leftMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.rotated(by: .pi / 2.0) + case .right, .rightMirrored: + transform = transform.translatedBy(x: 0, y: size.height) + transform = transform.rotated(by: .pi / -2.0) + case .up, .upMirrored: + break + #if compiler(>=5) + @unknown default: + break + #endif + } + + //Flip image one more time if needed to, this is to prevent flipped image + switch orientation { + case .upMirrored, .downMirrored: + transform = transform.translatedBy(x: size.width, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .leftMirrored, .rightMirrored: + transform = transform.translatedBy(x: size.height, y: 0) + transform = transform.scaledBy(x: -1, y: 1) + case .up, .down, .left, .right: + break + #if compiler(>=5) + @unknown default: + break + #endif + } + + context.concatenate(transform) + switch orientation { + case .left, .leftMirrored, .right, .rightMirrored: + context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width)) + default: + context.draw(cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height)) + } + } + #endif +} + +// MARK: - Image Representation +extension KingfisherWrapper where Base: KFCrossPlatformImage { + /// Returns PNG representation of `base` image. + /// + /// - Returns: PNG data of image. + public func pngRepresentation() -> Data? { + #if os(macOS) + guard let cgImage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgImage) + return rep.representation(using: .png, properties: [:]) + #else + return base.pngData() + #endif + } + + /// Returns JPEG representation of `base` image. + /// + /// - Parameter compressionQuality: The compression quality when converting image to JPEG data. + /// - Returns: JPEG data of image. + public func jpegRepresentation(compressionQuality: CGFloat) -> Data? { + #if os(macOS) + guard let cgImage = cgImage else { + return nil + } + let rep = NSBitmapImageRep(cgImage: cgImage) + return rep.representation(using:.jpeg, properties: [.compressionFactor: compressionQuality]) + #else + return base.jpegData(compressionQuality: compressionQuality) + #endif + } + + /// Returns GIF representation of `base` image. + /// + /// - Returns: Original GIF data of image. + public func gifRepresentation() -> Data? { + return animatedImageData + } + + /// Returns a data representation for `base` image, with the `format` as the format indicator. + /// - Parameters: + /// - format: The format in which the output data should be. If `unknown`, the `base` image will be + /// converted in the PNG representation. + /// - compressionQuality: The compression quality when converting image to a lossy format data. + /// + /// - Returns: The output data representing. + public func data(format: ImageFormat, compressionQuality: CGFloat = 1.0) -> Data? { + return autoreleasepool { () -> Data? in + let data: Data? + switch format { + case .PNG: data = pngRepresentation() + case .JPEG: data = jpegRepresentation(compressionQuality: compressionQuality) + case .GIF: data = gifRepresentation() + case .unknown: data = normalized.kf.pngRepresentation() + } + + return data + } + } +} + +// MARK: - Creating Images +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Creates an animated image from a given data and options. Currently only GIF data is supported. + /// + /// - Parameters: + /// - data: The animated image data. + /// - options: Options to use when creating the animated image. + /// - Returns: An `Image` object represents the animated image. It is in form of an array of image frames with a + /// certain duration. `nil` if anything wrong when creating animated image. + public static func animatedImage(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? { + let info: [String: Any] = [ + kCGImageSourceShouldCache as String: true, + kCGImageSourceTypeIdentifierHint as String: kUTTypeGIF + ] + + guard let imageSource = CGImageSourceCreateWithData(data as CFData, info as CFDictionary) else { + return nil + } + + #if os(macOS) + guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else { + return nil + } + var image: KFCrossPlatformImage? + if options.onlyFirstFrame { + image = animatedImage.images.first + } else { + image = KFCrossPlatformImage(data: data) + var kf = image?.kf + kf?.images = animatedImage.images + kf?.duration = animatedImage.duration + } + image?.kf.animatedImageData = data + image?.kf.imageFrameCount = Int(CGImageSourceGetCount(imageSource)) + return image + #else + + var image: KFCrossPlatformImage? + if options.preloadAll || options.onlyFirstFrame { + // Use `images` image if you want to preload all animated data + guard let animatedImage = GIFAnimatedImage(from: imageSource, for: info, options: options) else { + return nil + } + if options.onlyFirstFrame { + image = animatedImage.images.first + } else { + let duration = options.duration <= 0.0 ? animatedImage.duration : options.duration + image = .animatedImage(with: animatedImage.images, duration: duration) + } + image?.kf.animatedImageData = data + } else { + image = KFCrossPlatformImage(data: data, scale: options.scale) + var kf = image?.kf + kf?.imageSource = imageSource + kf?.animatedImageData = data + } + + image?.kf.imageFrameCount = Int(CGImageSourceGetCount(imageSource)) + return image + #endif + } + + /// Creates an image from a given data and options. `.JPEG`, `.PNG` or `.GIF` is supported. For other + /// image format, image initializer from system will be used. If no image object could be created from + /// the given `data`, `nil` will be returned. + /// + /// - Parameters: + /// - data: The image data representation. + /// - options: Options to use when creating the image. + /// - Returns: An `Image` object represents the image if created. If the `data` is invalid or not supported, `nil` + /// will be returned. + public static func image(data: Data, options: ImageCreatingOptions) -> KFCrossPlatformImage? { + var image: KFCrossPlatformImage? + switch data.kf.imageFormat { + case .JPEG: + image = KFCrossPlatformImage(data: data, scale: options.scale) + case .PNG: + image = KFCrossPlatformImage(data: data, scale: options.scale) + case .GIF: + image = KingfisherWrapper.animatedImage(data: data, options: options) + case .unknown: + image = KFCrossPlatformImage(data: data, scale: options.scale) + } + return image + } + + /// Creates a downsampled image from given data to a certain size and scale. + /// + /// - Parameters: + /// - data: The image data contains a JPEG or PNG image. + /// - pointSize: The target size in point to which the image should be downsampled. + /// - scale: The scale of result image. + /// - Returns: A downsampled `Image` object following the input conditions. + /// + /// - Note: + /// Different from image `resize` methods, downsampling will not render the original + /// input image in pixel format. It does downsampling from the image data, so it is much + /// more memory efficient and friendly. Choose to use downsampling as possible as you can. + /// + /// The input size should be smaller than the size of input image. If it is larger than the + /// original image size, the result image will be the same size of input without downsampling. + public static func downsampledImage(data: Data, to pointSize: CGSize, scale: CGFloat) -> KFCrossPlatformImage? { + let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary + guard let imageSource = CGImageSourceCreateWithData(data as CFData, imageSourceOptions) else { + return nil + } + + let maxDimensionInPixels = max(pointSize.width, pointSize.height) * scale + let downsampleOptions = [ + kCGImageSourceCreateThumbnailFromImageAlways: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceThumbnailMaxPixelSize: maxDimensionInPixels] as CFDictionary + guard let downsampledImage = CGImageSourceCreateThumbnailAtIndex(imageSource, 0, downsampleOptions) else { + return nil + } + return KingfisherWrapper.image(cgImage: downsampledImage, scale: scale, refImage: nil) + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageDrawing.swift b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift new file mode 100644 index 0000000..fce627c --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageDrawing.swift @@ -0,0 +1,632 @@ +// +// ImageDrawing.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Accelerate + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif +#if canImport(UIKit) +import UIKit +#endif + +// MARK: - Image Transforming +extension KingfisherWrapper where Base: KFCrossPlatformImage { + // MARK: Blend Mode + /// Create image from `base` image and apply blend mode. + /// + /// - parameter blendMode: The blend mode of creating image. + /// - parameter alpha: The alpha should be used for image. + /// - parameter backgroundColor: The background color for the output image. + /// + /// - returns: An image with blend mode applied. + /// + /// - Note: This method only works for CG-based image. + #if !os(macOS) + public func image(withBlendMode blendMode: CGBlendMode, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { _ in + if let backgroundColor = backgroundColor { + backgroundColor.setFill() + UIRectFill(rect) + } + + base.draw(in: rect, blendMode: blendMode, alpha: alpha) + return false + } + } + #endif + + #if os(macOS) + // MARK: Compositing + /// Creates image from `base` image and apply compositing operation. + /// + /// - Parameters: + /// - compositingOperation: The compositing operation of creating image. + /// - alpha: The alpha should be used for image. + /// - backgroundColor: The background color for the output image. + /// - Returns: An image with compositing operation applied. + /// + /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned. + public func image(withCompositingOperation compositingOperation: NSCompositingOperation, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { _ in + if let backgroundColor = backgroundColor { + backgroundColor.setFill() + rect.fill() + } + base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha) + return false + } + } + #endif + + // MARK: Round Corner + + /// Creates a round corner image from on `base` image. + /// + /// - Parameters: + /// - radius: The round corner radius of creating image. + /// - size: The target size of creating image. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: The background color for the output image + /// - Returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func image( + withRadius radius: Radius, + fit size: CGSize, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> KFCrossPlatformImage + { + + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Round corner image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(to: size, inverting: false) { _ in + #if os(macOS) + if let backgroundColor = backgroundColor { + let rectPath = NSBezierPath(rect: rect) + backgroundColor.setFill() + rectPath.fill() + } + + let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners) + path.addClip() + base.draw(in: rect) + #else + guard let context = UIGraphicsGetCurrentContext() else { + assertionFailure("[Kingfisher] Failed to create CG context for image.") + return false + } + + if let backgroundColor = backgroundColor { + let rectPath = UIBezierPath(rect: rect) + backgroundColor.setFill() + rectPath.fill() + } + + let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners) + context.addPath(path.cgPath) + context.clip() + base.draw(in: rect) + #endif + return false + } + } + + /// Creates a round corner image from on `base` image. + /// + /// - Parameters: + /// - radius: The round corner radius of creating image. + /// - size: The target size of creating image. + /// - corners: The target corners which will be applied rounding. + /// - backgroundColor: The background color for the output image + /// - Returns: An image with round corner of `self`. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func image( + withRoundRadius radius: CGFloat, + fit size: CGSize, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) -> KFCrossPlatformImage + { + image(withRadius: .point(radius), fit: size, roundingCorners: corners, backgroundColor: backgroundColor) + } + + #if os(macOS) + func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> NSBezierPath { + let cornerRadius = radius.compute(with: rect.size) + let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: cornerRadius - offsetBase / 2) + path.windingRule = .evenOdd + return path + } + #else + func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> UIBezierPath { + let cornerRadius = radius.compute(with: rect.size) + return UIBezierPath( + roundedRect: rect, + byRoundingCorners: corners.uiRectCorner, + cornerRadii: CGSize( + width: cornerRadius - offsetBase / 2, + height: cornerRadius - offsetBase / 2 + ) + ) + } + #endif + + #if os(iOS) || os(tvOS) + func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage { + switch contentMode { + case .scaleAspectFit: + return resize(to: size, for: .aspectFit) + case .scaleAspectFill: + return resize(to: size, for: .aspectFill) + default: + return resize(to: size) + } + } + #endif + + // MARK: Resizing + /// Resizes `base` image to an image with new size. + /// + /// - Parameter size: The target size in point. + /// - Returns: An image with new size. + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func resize(to size: CGSize) -> KFCrossPlatformImage { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Resize only works for CG-based image.") + return base + } + + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + return draw(to: size, inverting: false) { _ in + #if os(macOS) + base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) + #else + base.draw(in: rect) + #endif + return false + } + } + + /// Resizes `base` image to an image of new size, respecting the given content mode. + /// + /// - Parameters: + /// - targetSize: The target size in point. + /// - contentMode: Content mode of output image should be. + /// - Returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage { + let newSize = size.kf.resize(to: targetSize, for: contentMode) + return resize(to: newSize) + } + + // MARK: Cropping + /// Crops `base` image to a new size with a given anchor. + /// + /// - Parameters: + /// - size: The target size. + /// - anchor: The anchor point from which the size should be calculated. + /// - Returns: An image with new size. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage { + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Crop only works for CG-based image.") + return base + } + + let rect = self.size.kf.constrainedRect(for: size, anchor: anchor) + guard let image = cgImage.cropping(to: rect.scaled(scale)) else { + assertionFailure("[Kingfisher] Cropping image failed.") + return base + } + + return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base) + } + + // MARK: Blur + /// Creates an image with blur effect based on `base` image. + /// + /// - Parameter radius: The blur radius should be used when creating blur effect. + /// - Returns: An image with blur effect applied. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage { + + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Blur only works for CG-based image.") + return base + } + + // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement + // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5) + // if d is odd, use three box-blurs of size 'd', centered on the output pixel. + let s = max(radius, 2.0) + // We will do blur on a resized image (*0.5), so the blur radius could be half as well. + + // Fix the slow compiling time for Swift 3. + // See https://github.com/onevcat/Kingfisher/issues/611 + let pi2 = 2 * CGFloat.pi + let sqrtPi2 = sqrt(pi2) + var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5) + + if targetRadius.isEven { targetRadius += 1 } + + // Determine necessary iteration count by blur radius. + let iterations: Int + if radius < 0.5 { + iterations = 1 + } else if radius < 1.5 { + iterations = 2 + } else { + iterations = 3 + } + + let w = Int(size.width) + let h = Int(size.height) + + func createEffectBuffer(_ context: CGContext) -> vImage_Buffer { + let data = context.data + let width = vImagePixelCount(context.width) + let height = vImagePixelCount(context.height) + let rowBytes = context.bytesPerRow + + return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes) + } + GraphicsContext.begin(size: size, scale: scale) + guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h)) + GraphicsContext.end() + + var inBuffer = createEffectBuffer(context) + + GraphicsContext.begin(size: size, scale: scale) + guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { GraphicsContext.end() } + var outBuffer = createEffectBuffer(outContext) + + for _ in 0 ..< iterations { + let flag = vImage_Flags(kvImageEdgeExtend) + vImageBoxConvolve_ARGB8888( + &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag) + // Next inBuffer should be the outButter of current iteration + (inBuffer, outBuffer) = (outBuffer, inBuffer) + } + + #if os(macOS) + let result = outContext.makeImage().flatMap { + fixedForRetinaPixel(cgImage: $0, to: size) + } + #else + let result = outContext.makeImage().flatMap { + KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation) + } + #endif + guard let blurredImage = result else { + assertionFailure("[Kingfisher] Can not make an blurred image within this context.") + return base + } + + return blurredImage + } + + public func addingBorder(_ border: Border) -> KFCrossPlatformImage + { + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.") + return base + } + + let rect = CGRect(origin: .zero, size: size) + return draw(to: rect.size, inverting: false) { context in + + #if os(macOS) + base.draw(in: rect) + #else + base.draw(in: rect, blendMode: .normal, alpha: 1.0) + #endif + + + let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2) + context.setStrokeColor(border.color.cgColor) + context.setAlpha(border.color.rgba.a) + + let line = pathForRoundCorner( + rect: strokeRect, + radius: border.radius, + corners: border.roundingCorners, + offsetBase: border.lineWidth + ) + line.lineCapStyle = .square + line.lineWidth = border.lineWidth + line.stroke() + + return false + } + } + + // MARK: Overlay + /// Creates an image from `base` image with a color overlay layer. + /// + /// - Parameters: + /// - color: The color should be use to overlay. + /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color, + /// 1.0 means transparent overlay. + /// - Returns: An image with a color overlay applied. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image, `base` itself is returned. + public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage { + + guard let _ = cgImage else { + assertionFailure("[Kingfisher] Overlaying only works for CG-based image.") + return base + } + + let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height) + return draw(to: rect.size, inverting: false) { context in + #if os(macOS) + base.draw(in: rect) + if fraction > 0 { + color.withAlphaComponent(1 - fraction).set() + rect.fill(using: .sourceAtop) + } + #else + color.set() + UIRectFill(rect) + base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0) + + if fraction > 0 { + base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction) + } + #endif + return false + } + } + + // MARK: Tint + /// Creates an image from `base` image with a color tint. + /// + /// - Parameter color: The color should be used to tint `base` + /// - Returns: An image with a color tint applied. + public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage { + #if os(watchOS) + return base + #else + return apply(.tint(color)) + #endif + } + + // MARK: Color Control + + /// Create an image from `self` with color control. + /// + /// - Parameters: + /// - brightness: Brightness changing to image. + /// - contrast: Contrast changing to image. + /// - saturation: Saturation changing to image. + /// - inputEV: InputEV changing to image. + /// - Returns: An image with color control applied. + public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage { + #if os(watchOS) + return base + #else + return apply(.colorControl((brightness, contrast, saturation, inputEV))) + #endif + } + + /// Return an image with given scale. + /// + /// - Parameter scale: Target scale factor the new image should have. + /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned. + public func scaled(to scale: CGFloat) -> KFCrossPlatformImage { + guard scale != self.scale else { + return base + } + guard let cgImage = cgImage else { + assertionFailure("[Kingfisher] Scaling only works for CG-based image.") + return base + } + return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base) + } +} + +// MARK: - Decoding Image +extension KingfisherWrapper where Base: KFCrossPlatformImage { + + /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data + /// from it. This could improve the drawing performance when an image is just created from data but not yet + /// displayed for the first time. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public var decoded: KFCrossPlatformImage { return decoded(scale: scale) } + + /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and + /// return the data from it. This could improve the drawing performance when an image is just created from + /// data but not yet displayed for the first time. + /// + /// - Parameter scale: The given scale of target image should be. + /// - Returns: The decoded image ready to be displayed. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public func decoded(scale: CGFloat) -> KFCrossPlatformImage { + // Prevent animated image (GIF) losing it's images + #if os(iOS) + if imageSource != nil { return base } + #else + if images != nil { return base } + #endif + + guard let imageRef = cgImage else { + assertionFailure("[Kingfisher] Decoding only works for CG-based image.") + return base + } + + let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale) + return draw(to: size, inverting: true, scale: scale) { context in + context.draw(imageRef, in: CGRect(origin: .zero, size: size)) + return true + } + } + + /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and + /// return the data from it. This could improve the drawing performance when an image is just created from + /// data but not yet displayed for the first time. + /// + /// - Parameter context: The context for drawing. + /// - Returns: The decoded image ready to be displayed. + /// + /// - Note: This method only works for CG-based image. The current image scale is kept. + /// For any non-CG-based image or animated image, `base` itself is returned. + public func decoded(on context: CGContext) -> KFCrossPlatformImage { + // Prevent animated image (GIF) losing it's images + #if os(iOS) + if imageSource != nil { return base } + #else + if images != nil { return base } + #endif + + guard let refImage = cgImage else { + assertionFailure("[Kingfisher] Decoding only works for CG-based image.") + return base + } + + let size = CGSize(width: CGFloat(refImage.width) / scale, height: CGFloat(refImage.height) / scale) + + context.draw(refImage, in: CGRect(origin: .zero, size: size)) + + guard let cgImage = context.makeImage() else { + return base + } + + return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base) + } +} + +extension KingfisherWrapper where Base: KFCrossPlatformImage { + func draw( + to size: CGSize, + inverting: Bool, + scale: CGFloat? = nil, + refImage: KFCrossPlatformImage? = nil, + draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`) + ) -> KFCrossPlatformImage + { + #if os(macOS) || os(watchOS) + let targetScale = scale ?? self.scale + GraphicsContext.begin(size: size, scale: targetScale) + guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else { + assertionFailure("[Kingfisher] Failed to create CG context for blurring image.") + return base + } + defer { GraphicsContext.end() } + let useRefImage = draw(context) + guard let cgImage = context.makeImage() else { + return base + } + let ref = useRefImage ? (refImage ?? base) : nil + return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref) + #else + + let format = UIGraphicsImageRendererFormat.preferred() + format.scale = scale ?? self.scale + let renderer = UIGraphicsImageRenderer(size: size, format: format) + + var useRefImage: Bool = false + let image = renderer.image { rendererContext in + + let context = rendererContext.cgContext + if inverting { // If drawing a CGImage, we need to make context flipped. + context.scaleBy(x: 1.0, y: -1.0) + context.translateBy(x: 0, y: -size.height) + } + + useRefImage = draw(context) + } + if useRefImage { + guard let cgImage = image.cgImage else { + return base + } + let ref = refImage ?? base + return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref) + } else { + return image + } + #endif + } + + #if os(macOS) + func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage { + + let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size) + let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size) + + return draw(to: self.size, inverting: false) { context in + image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0) + return false + } + } + #endif +} diff --git a/Pods/Kingfisher/Sources/Image/ImageFormat.swift b/Pods/Kingfisher/Sources/Image/ImageFormat.swift new file mode 100644 index 0000000..464a855 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageFormat.swift @@ -0,0 +1,130 @@ +// +// ImageFormat.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents image format. +/// +/// - unknown: The format cannot be recognized or not supported yet. +/// - PNG: PNG image format. +/// - JPEG: JPEG image format. +/// - GIF: GIF image format. +public enum ImageFormat { + /// The format cannot be recognized or not supported yet. + case unknown + /// PNG image format. + case PNG + /// JPEG image format. + case JPEG + /// GIF image format. + case GIF + + struct HeaderData { + static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A] + static var JPEG_SOI: [UInt8] = [0xFF, 0xD8] + static var JPEG_IF: [UInt8] = [0xFF] + static var GIF: [UInt8] = [0x47, 0x49, 0x46] + } + + /// https://en.wikipedia.org/wiki/JPEG + public enum JPEGMarker { + case SOF0 //baseline + case SOF2 //progressive + case DHT //Huffman Table + case DQT //Quantization Table + case DRI //Restart Interval + case SOS //Start Of Scan + case RSTn(UInt8) //Restart + case APPn //Application-specific + case COM //Comment + case EOI //End Of Image + + var bytes: [UInt8] { + switch self { + case .SOF0: return [0xFF, 0xC0] + case .SOF2: return [0xFF, 0xC2] + case .DHT: return [0xFF, 0xC4] + case .DQT: return [0xFF, 0xDB] + case .DRI: return [0xFF, 0xDD] + case .SOS: return [0xFF, 0xDA] + case .RSTn(let n): return [0xFF, 0xD0 + n] + case .APPn: return [0xFF, 0xE0] + case .COM: return [0xFF, 0xFE] + case .EOI: return [0xFF, 0xD9] + } + } + } +} + + +extension Data: KingfisherCompatibleValue {} + +// MARK: - Misc Helpers +extension KingfisherWrapper where Base == Data { + /// Gets the image format corresponding to the data. + public var imageFormat: ImageFormat { + guard base.count > 8 else { return .unknown } + + var buffer = [UInt8](repeating: 0, count: 8) + base.copyBytes(to: &buffer, count: 8) + + if buffer == ImageFormat.HeaderData.PNG { + return .PNG + + } else if buffer[0] == ImageFormat.HeaderData.JPEG_SOI[0], + buffer[1] == ImageFormat.HeaderData.JPEG_SOI[1], + buffer[2] == ImageFormat.HeaderData.JPEG_IF[0] + { + return .JPEG + + } else if buffer[0] == ImageFormat.HeaderData.GIF[0], + buffer[1] == ImageFormat.HeaderData.GIF[1], + buffer[2] == ImageFormat.HeaderData.GIF[2] + { + return .GIF + } + + return .unknown + } + + public func contains(jpeg marker: ImageFormat.JPEGMarker) -> Bool { + guard imageFormat == .JPEG else { + return false + } + + let bytes = [UInt8](base) + let markerBytes = marker.bytes + for (index, item) in bytes.enumerated() where bytes.count > index + 1 { + guard + item == markerBytes.first, + bytes[index + 1] == markerBytes[1] else { + continue + } + return true + } + return false + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageProcessor.swift b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift new file mode 100644 index 0000000..9883460 --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageProcessor.swift @@ -0,0 +1,938 @@ +// +// ImageProcessor.swift +// Kingfisher +// +// Created by Wei Wang on 2016/08/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +/// Represents an item which could be processed by an `ImageProcessor`. +/// +/// - image: Input image. The processor should provide a way to apply +/// processing on this `image` and return the result image. +/// - data: Input data. The processor should provide a way to apply +/// processing on this `data` and return the result image. +public enum ImageProcessItem { + + /// Input image. The processor should provide a way to apply + /// processing on this `image` and return the result image. + case image(KFCrossPlatformImage) + + /// Input data. The processor should provide a way to apply + /// processing on this `data` and return the result image. + case data(Data) +} + +/// An `ImageProcessor` would be used to convert some downloaded data to an image. +public protocol ImageProcessor { + /// Identifier of the processor. It will be used to identify the processor when + /// caching and retrieving an image. You might want to make sure that processors with + /// same properties/functionality have the same identifiers, so correct processed images + /// could be retrieved with proper key. + /// + /// - Note: Do not supply an empty string for a customized processor, which is already reserved by + /// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of + /// your own for the identifier. + var identifier: String { get } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: The parsed options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: The return value should be `nil` if processing failed while converting an input item to image. + /// If `nil` received by the processing caller, an error will be reported and the process flow stops. + /// If the processing flow is not critical for your flow, then when the input item is already an image + /// (`.image` case) and there is any errors in the processing, you could return the input image itself + /// to keep the processing pipeline continuing. + /// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing + /// a filter, the input image will be returned directly on watchOS. + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? +} + +extension ImageProcessor { + + /// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor` + /// will be "\(self.identifier)|>\(another.identifier)". + /// + /// - Parameter another: An `ImageProcessor` you want to append to `self`. + /// - Returns: The new `ImageProcessor` will process the image in the order + /// of the two processors concatenated. + public func append(another: ImageProcessor) -> ImageProcessor { + let newIdentifier = identifier.appending("|>\(another.identifier)") + return GeneralProcessor(identifier: newIdentifier) { + item, options in + if let image = self.process(item: item, options: options) { + return another.process(item: .image(image), options: options) + } else { + return nil + } + } + } +} + +func ==(left: ImageProcessor, right: ImageProcessor) -> Bool { + return left.identifier == right.identifier +} + +func !=(left: ImageProcessor, right: ImageProcessor) -> Bool { + return !(left == right) +} + +typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> KFCrossPlatformImage?) +struct GeneralProcessor: ImageProcessor { + let identifier: String + let p: ProcessorImp + func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return p(item, options) + } +} + +/// The default processor. It converts the input data to a valid image. +/// Images of .PNG, .JPEG and .GIF format are supported. +/// If an image item is given as `.image` case, `DefaultImageProcessor` will +/// do nothing on it and return the associated image. +public struct DefaultImageProcessor: ImageProcessor { + + /// A default `DefaultImageProcessor` could be used across. + public static let `default` = DefaultImageProcessor() + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier = "" + + /// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance, + /// if you do not have a good reason to create your own `DefaultImageProcessor`. + public init() {} + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + case .data(let data): + return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions) + } + } +} + +/// Represents the rect corner setting when processing a round corner image. +public struct RectCorner: OptionSet { + + /// Raw value of the rect corner. + public let rawValue: Int + + /// Represents the top left corner. + public static let topLeft = RectCorner(rawValue: 1 << 0) + + /// Represents the top right corner. + public static let topRight = RectCorner(rawValue: 1 << 1) + + /// Represents the bottom left corner. + public static let bottomLeft = RectCorner(rawValue: 1 << 2) + + /// Represents the bottom right corner. + public static let bottomRight = RectCorner(rawValue: 1 << 3) + + /// Represents all corners. + public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight] + + /// Creates a `RectCorner` option set with a given value. + /// + /// - Parameter rawValue: The value represents a certain corner option. + public init(rawValue: Int) { + self.rawValue = rawValue + } + + var cornerIdentifier: String { + if self == .all { + return "" + } + return "_corner(\(rawValue))" + } +} + +#if !os(macOS) +/// Processor for adding an blend mode to images. Only CG-based images are supported. +public struct BlendImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Blend Mode will be used to blend the input image. + public let blendMode: CGBlendMode + + /// Alpha will be used when blend image. + public let alpha: CGFloat + + /// Background color of the output image. If `nil`, it will stay transparent. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `BlendImageProcessor`. + /// + /// - Parameters: + /// - blendMode: Blend Mode will be used to blend the input image. + /// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image, + /// 0.0 means transparent image (not visible at all). Default is 1.0. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: KFCrossPlatformColor? = nil) { + self.blendMode = blendMode + self.alpha = alpha + self.backgroundColor = backgroundColor + var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))" + if let color = backgroundColor { + identifier.append("_\(color.rgbaDescription)") + } + self.identifier = identifier + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} +#endif + +#if os(macOS) +/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS. +public struct CompositingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Compositing operation will be used to the input image. + public let compositingOperation: NSCompositingOperation + + /// Alpha will be used when compositing image. + public let alpha: CGFloat + + /// Background color of the output image. If `nil`, it will stay transparent. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `CompositingImageProcessor` + /// + /// - Parameters: + /// - compositingOperation: Compositing operation will be used to the input image. + /// - alpha: Alpha will be used when compositing image. + /// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image. + /// Default is 1.0. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init(compositingOperation: NSCompositingOperation, + alpha: CGFloat = 1.0, + backgroundColor: KFCrossPlatformColor? = nil) + { + self.compositingOperation = compositingOperation + self.alpha = alpha + self.backgroundColor = backgroundColor + var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))" + if let color = backgroundColor { + identifier.append("_\(color.rgbaDescription)") + } + self.identifier = identifier + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.image( + withCompositingOperation: compositingOperation, + alpha: alpha, + backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} +#endif + +/// Represents a radius specified in a `RoundCornerImageProcessor`. +public enum Radius { + /// The radius should be calculated as a fraction of the image width. Typically the associated value should be + /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image width. + case widthFraction(CGFloat) + /// The radius should be calculated as a fraction of the image height. Typically the associated value should be + /// between 0 and 0.5, where 0 represents no radius and 0.5 represents using half of the image height. + case heightFraction(CGFloat) + /// Use a fixed point value as the round corner radius. + case point(CGFloat) + + var radiusIdentifier: String { + switch self { + case .widthFraction(let f): + return "w_frac_\(f)" + case .heightFraction(let f): + return "h_frac_\(f)" + case .point(let p): + return p.description + } + } + + public func compute(with size: CGSize) -> CGFloat { + let cornerRadius: CGFloat + switch self { + case .point(let point): + cornerRadius = point + case .widthFraction(let widthFraction): + cornerRadius = size.width * widthFraction + case .heightFraction(let heightFraction): + cornerRadius = size.height * heightFraction + } + return cornerRadius + } +} + +/// Processor for making round corner images. Only CG-based images are supported in macOS, +/// if a non-CG image passed in, the processor will do nothing. +/// +/// - Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain +/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order +/// to show correctly. However, when cached to disk, Kingfisher respects the original image format by default. That +/// means the alpha channel will be removed for these images. When you load the processed image from cache again, you +/// will lose transparent corner. +/// +/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this +/// case. +/// +public struct RoundCornerImageProcessor: ImageProcessor { + + /// Represents a radius specified in a `RoundCornerImageProcessor`. + public typealias Radius = Kingfisher.Radius + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the + /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and + /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. + public let radius: Radius + + /// The target corners which will be applied rounding. + public let roundingCorners: RectCorner + + /// Target size of output image should be. If `nil`, the image will keep its original size after processing. + public let targetSize: CGSize? + + /// Background color of the output image. If `nil`, it will use a transparent background. + public let backgroundColor: KFCrossPlatformColor? + + /// Creates a `RoundCornerImageProcessor`. + /// + /// - Parameters: + /// - cornerRadius: Corner radius in point will be applied in processing. + /// - targetSize: Target size of output image should be. If `nil`, + /// the image will keep its original size after processing. + /// Default is `nil`. + /// - corners: The target corners which will be applied rounding. Default is `.all`. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + /// + /// - Note: + /// + /// This initializer accepts a concrete point value for `cornerRadius`. If you do not know the image size, but still + /// want to apply a full round-corner (making the final image a round one), or specify the corner radius as a + /// fraction of one dimension of the target image, use the `Radius` version instead. + /// + public init( + cornerRadius: CGFloat, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) + { + let radius = Radius.point(cornerRadius) + self.init(radius: radius, targetSize: targetSize, roundingCorners: corners, backgroundColor: backgroundColor) + } + + /// Creates a `RoundCornerImageProcessor`. + /// + /// - Parameters: + /// - radius: The radius will be applied in processing. + /// - targetSize: Target size of output image should be. If `nil`, + /// the image will keep its original size after processing. + /// Default is `nil`. + /// - corners: The target corners which will be applied rounding. Default is `.all`. + /// - backgroundColor: Background color to apply for the output image. Default is `nil`. + public init( + radius: Radius, + targetSize: CGSize? = nil, + roundingCorners corners: RectCorner = .all, + backgroundColor: KFCrossPlatformColor? = nil + ) + { + self.radius = radius + self.targetSize = targetSize + self.roundingCorners = corners + self.backgroundColor = backgroundColor + + self.identifier = { + var identifier = "" + + if let size = targetSize { + identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + + "(\(radius.radiusIdentifier)_\(size)\(corners.cornerIdentifier))" + } else { + identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" + + "(\(radius.radiusIdentifier)\(corners.cornerIdentifier))" + } + if let backgroundColor = backgroundColor { + identifier += "_\(backgroundColor)" + } + + return identifier + }() + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + let size = targetSize ?? image.kf.size + return image.kf.scaled(to: options.scaleFactor) + .kf.image( + withRadius: radius, + fit: size, + roundingCorners: roundingCorners, + backgroundColor: backgroundColor) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +public struct Border { + public var color: KFCrossPlatformColor + public var lineWidth: CGFloat + + /// The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction of the + /// target image with `.widthFraction`. or `.heightFraction`. For example, given a square image with width and + /// height equals, `.widthFraction(0.5)` means use half of the length of size and makes the final image a round one. + public var radius: Radius + + /// The target corners which will be applied rounding. + public var roundingCorners: RectCorner + + public init( + color: KFCrossPlatformColor = .black, + lineWidth: CGFloat = 4, + radius: Radius = .point(0), + roundingCorners: RectCorner = .all + ) { + self.color = color + self.lineWidth = lineWidth + self.radius = radius + self.roundingCorners = roundingCorners + } + + var identifier: String { + "\(color.rgbaDescription)_\(lineWidth)_\(radius.radiusIdentifier)_\(roundingCorners.cornerIdentifier)" + } +} + +public struct BorderImageProcessor: ImageProcessor { + public var identifier: String { "com.onevcat.Kingfisher.RoundCornerImageProcessor(\(border)" } + public let border: Border + + public init(border: Border) { + self.border = border + } + + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.addingBorder(border) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Represents how a size adjusts itself to fit a target size. +/// +/// - none: Not scale the content. +/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio. +/// - aspectFill: Scales the content to fill the size of the view. +public enum ContentMode { + /// Not scale the content. + case none + /// Scales the content to fit the size of the view by maintaining the aspect ratio. + case aspectFit + /// Scales the content to fill the size of the view. + case aspectFill +} + +/// Processor for resizing images. +/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor` +/// instead, which is more efficient and uses less memory. +public struct ResizingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// The reference size for resizing operation in point. + public let referenceSize: CGSize + + /// Target content mode of output image should be. + /// Default is `.none`. + public let targetContentMode: ContentMode + + /// Creates a `ResizingImageProcessor`. + /// + /// - Parameters: + /// - referenceSize: The reference size for resizing operation in point. + /// - mode: Target content mode of output image should be. + /// + /// - Note: + /// The instance of `ResizingImageProcessor` will follow its `mode` property + /// and try to resizing the input images to fit or fill the `referenceSize`. + /// That means if you are using a `mode` besides of `.none`, you may get an + /// image with its size not be the same as the `referenceSize`. + /// + /// **Example**: With input image size: {100, 200}, + /// `referenceSize`: {100, 100}, `mode`: `.aspectFit`, + /// you will get an output image with size of {50, 100}, which "fit"s + /// the `referenceSize`. + /// + /// If you need an output image exactly to be a specified size, append or use + /// a `CroppingImageProcessor`. + public init(referenceSize: CGSize, mode: ContentMode = .none) { + self.referenceSize = referenceSize + self.targetContentMode = mode + + if mode == .none { + self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))" + } else { + self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))" + } + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.resize(to: referenceSize, for: targetContentMode) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for +/// a better performance. A simulated Gaussian blur with specified blur radius will be applied. +public struct BlurImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Blur radius for the simulated Gaussian blur. + public let blurRadius: CGFloat + + /// Creates a `BlurImageProcessor` + /// + /// - parameter blurRadius: Blur radius for the simulated Gaussian blur. + public init(blurRadius: CGFloat) { + self.blurRadius = blurRadius + self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + let radius = blurRadius * options.scaleFactor + return image.kf.scaled(to: options.scaleFactor) + .kf.blurred(withRadius: radius) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for adding an overlay to images. Only CG-based images are supported in macOS. +public struct OverlayImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Overlay color will be used to overlay the input image. + public let overlay: KFCrossPlatformColor + + /// Fraction will be used when overlay the color to image. + public let fraction: CGFloat + + /// Creates an `OverlayImageProcessor` + /// + /// - parameter overlay: Overlay color will be used to overlay the input image. + /// - parameter fraction: Fraction will be used when overlay the color to image. + /// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay. + public init(overlay: KFCrossPlatformColor, fraction: CGFloat = 0.5) { + self.overlay = overlay + self.fraction = fraction + self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.rgbaDescription)_\(fraction))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.overlaying(with: overlay, fraction: fraction) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for tint images with color. Only CG-based images are supported. +public struct TintImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Tint color will be used to tint the input image. + public let tint: KFCrossPlatformColor + + /// Creates a `TintImageProcessor` + /// + /// - parameter tint: Tint color will be used to tint the input image. + public init(tint: KFCrossPlatformColor) { + self.tint = tint + self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.rgbaDescription))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.tinted(with: tint) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for applying some color control to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct ColorControlsProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Brightness changing to image. + public let brightness: CGFloat + + /// Contrast changing to image. + public let contrast: CGFloat + + /// Saturation changing to image. + public let saturation: CGFloat + + /// InputEV changing to image. + public let inputEV: CGFloat + + /// Creates a `ColorControlsProcessor` + /// + /// - Parameters: + /// - brightness: Brightness changing to image. + /// - contrast: Contrast changing to image. + /// - saturation: Saturation changing to image. + /// - inputEV: InputEV changing to image. + public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) { + self.brightness = brightness + self.contrast = contrast + self.saturation = saturation + self.inputEV = inputEV + self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV) + case .data: + return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for applying black and white effect to images. Only CG-based images are supported. +/// watchOS is not supported. +public struct BlackWhiteProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor" + + /// Creates a `BlackWhiteProcessor` + public init() {} + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7) + .process(item: item, options: options) + } +} + +/// Processor for cropping an image. Only CG-based images are supported. +/// watchOS is not supported. +public struct CroppingImageProcessor: ImageProcessor { + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Target size of output image should be. + public let size: CGSize + + /// Anchor point from which the output size should be calculate. + /// The anchor point is consisted by two values between 0.0 and 1.0. + /// It indicates a related point in current image. + /// See `CroppingImageProcessor.init(size:anchor:)` for more. + public let anchor: CGPoint + + /// Creates a `CroppingImageProcessor`. + /// + /// - Parameters: + /// - size: Target size of output image should be. + /// - anchor: The anchor point from which the size should be calculated. + /// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image. + /// - Note: + /// The anchor point is consisted by two values between 0.0 and 1.0. + /// It indicates a related point in current image, eg: (0.0, 0.0) for top-left + /// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner. + /// The `size` property of `CroppingImageProcessor` will be used along with + /// `anchor` to calculate a target rectangle in the size of image. + /// + /// The target size will be automatically calculated with a reasonable behavior. + /// For example, when you have an image size of `CGSize(width: 100, height: 100)`, + /// and a target size of `CGSize(width: 20, height: 20)`: + /// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`; + /// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}` + /// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}` + public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) { + self.size = size + self.anchor = anchor + self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + return image.kf.scaled(to: options.scaleFactor) + .kf.crop(to: size, anchorOn: anchor) + case .data: return (DefaultImageProcessor.default |> self).process(item: item, options: options) + } + } +} + +/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor +/// does not render the images to resize. Instead, it downsamples the input data directly to an +/// image. It is a more efficient than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible +/// as you can than the `ResizingImageProcessor`. +/// +/// Only CG-based images are supported. Animated images (like GIF) is not supported. +public struct DownsamplingImageProcessor: ImageProcessor { + + /// Target size of output image should be. It should be smaller than the size of + /// input image. If it is larger, the result image will be the same size of input + /// data without downsampling. + public let size: CGSize + + /// Identifier of the processor. + /// - Note: See documentation of `ImageProcessor` protocol for more. + public let identifier: String + + /// Creates a `DownsamplingImageProcessor`. + /// + /// - Parameter size: The target size of the downsample operation. + public init(size: CGSize) { + self.size = size + self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))" + } + + /// Processes the input `ImageProcessItem` with this processor. + /// + /// - Parameters: + /// - item: Input item which will be processed by `self`. + /// - options: Options when processing the item. + /// - Returns: The processed image. + /// + /// - Note: See documentation of `ImageProcessor` protocol for more. + public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? { + switch item { + case .image(let image): + guard let data = image.kf.data(format: .unknown) else { + return nil + } + return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) + case .data(let data): + return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor) + } + } +} + +infix operator |>: AdditionPrecedence +public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor { + return left.append(another: right) +} + +extension KFCrossPlatformColor { + + var rgba: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat) { + var r: CGFloat = 0 + var g: CGFloat = 0 + var b: CGFloat = 0 + var a: CGFloat = 0 + + #if os(macOS) + (usingColorSpace(.extendedSRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a) + #else + getRed(&r, green: &g, blue: &b, alpha: &a) + #endif + + return (r, g, b, a) + } + + var rgbaDescription: String { + let components = self.rgba + return String(format: "(%.2f,%.2f,%.2f,%.2f)", components.r, components.g, components.b, components.a) + } + + @available(*, deprecated, message: "`hex` is not safe for colors in extended space. Do not use this.") + var hex: String { + + let (r, g, b, a) = rgba + + let rInt = Int(r * 255) << 24 + let gInt = Int(g * 255) << 16 + let bInt = Int(b * 255) << 8 + let aInt = Int(a * 255) + + let rgba = rInt | gInt | bInt | aInt + + return String(format:"#%08x", rgba) + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageProgressive.swift b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift new file mode 100644 index 0000000..0e4f3cb --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageProgressive.swift @@ -0,0 +1,328 @@ +// +// ImageProgressive.swift +// Kingfisher +// +// Created by lixiang on 2019/5/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CoreGraphics + +private let sharedProcessingQueue: CallbackQueue = + .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) + +public struct ImageProgressive { + + /// A default `ImageProgressive` could be used across. It blurs the progressive loading with the fastest + /// scan enabled and scan interval as 0. + public static let `default` = ImageProgressive( + isBlur: true, + isFastestScan: true, + scanInterval: 0 + ) + + /// Whether to enable blur effect processing + let isBlur: Bool + /// Whether to enable the fastest scan + let isFastestScan: Bool + /// Minimum time interval for each scan + let scanInterval: TimeInterval + + public init(isBlur: Bool, + isFastestScan: Bool, + scanInterval: TimeInterval + ) + { + self.isBlur = isBlur + self.isFastestScan = isFastestScan + self.scanInterval = scanInterval + } +} + +protocol ImageSettable: AnyObject { + var image: KFCrossPlatformImage? { get set } +} + +final class ImageProgressiveProvider: DataReceivingSideEffect { + + var onShouldApply: () -> Bool = { return true } + + func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) { + + DispatchQueue.main.async { + guard self.onShouldApply() else { return } + self.update(data: task.mutableData, with: task.callbacks) + } + } + + private let option: ImageProgressive + private let refresh: (KFCrossPlatformImage) -> Void + + private let decoder: ImageProgressiveDecoder + private let queue = ImageProgressiveSerialQueue() + + init?(_ options: KingfisherParsedOptionsInfo, + refresh: @escaping (KFCrossPlatformImage) -> Void) { + guard let option = options.progressiveJPEG else { return nil } + + self.option = option + self.refresh = refresh + self.decoder = ImageProgressiveDecoder( + option, + processingQueue: options.processingQueue ?? sharedProcessingQueue, + creatingOptions: options.imageCreatingOptions + ) + } + + func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) { + guard !data.isEmpty else { return } + + queue.add(minimum: option.scanInterval) { completion in + + func decode(_ data: Data) { + self.decoder.decode(data, with: callbacks) { image in + defer { completion() } + guard self.onShouldApply() else { return } + guard let image = image else { return } + self.refresh(image) + } + } + + let semaphore = DispatchSemaphore(value: 0) + var onShouldApply: Bool = false + + CallbackQueue.mainAsync.execute { + onShouldApply = self.onShouldApply() + semaphore.signal() + } + semaphore.wait() + guard onShouldApply else { + self.queue.clean() + completion() + return + } + + if self.option.isFastestScan { + decode(self.decoder.scanning(data) ?? Data()) + } else { + self.decoder.scanning(data).forEach { decode($0) } + } + } + } +} + +private final class ImageProgressiveDecoder { + + private let option: ImageProgressive + private let processingQueue: CallbackQueue + private let creatingOptions: ImageCreatingOptions + private(set) var scannedCount = 0 + private(set) var scannedIndex = -1 + + init(_ option: ImageProgressive, + processingQueue: CallbackQueue, + creatingOptions: ImageCreatingOptions) { + self.option = option + self.processingQueue = processingQueue + self.creatingOptions = creatingOptions + } + + func scanning(_ data: Data) -> [Data] { + guard data.kf.contains(jpeg: .SOF2) else { + return [] + } + guard scannedIndex + 1 < data.count else { + return [] + } + + var datas: [Data] = [] + var index = scannedIndex + 1 + var count = scannedCount + + while index < data.count - 1 { + scannedIndex = index + // 0xFF, 0xDA - Start Of Scan + let SOS = ImageFormat.JPEGMarker.SOS.bytes + if data[index] == SOS[0], data[index + 1] == SOS[1] { + if count > 0 { + datas.append(data[0 ..< index]) + } + count += 1 + } + index += 1 + } + + // Found more scans this the previous time + guard count > scannedCount else { return [] } + scannedCount = count + + // `> 1` checks that we've received a first scan (SOS) and then received + // and also received a second scan (SOS). This way we know that we have + // at least one full scan available. + guard count > 1 else { return [] } + return datas + } + + func scanning(_ data: Data) -> Data? { + guard data.kf.contains(jpeg: .SOF2) else { + return nil + } + guard scannedIndex + 1 < data.count else { + return nil + } + + var index = scannedIndex + 1 + var count = scannedCount + var lastSOSIndex = 0 + + while index < data.count - 1 { + scannedIndex = index + // 0xFF, 0xDA - Start Of Scan + let SOS = ImageFormat.JPEGMarker.SOS.bytes + if data[index] == SOS[0], data[index + 1] == SOS[1] { + lastSOSIndex = index + count += 1 + } + index += 1 + } + + // Found more scans this the previous time + guard count > scannedCount else { return nil } + scannedCount = count + + // `> 1` checks that we've received a first scan (SOS) and then received + // and also received a second scan (SOS). This way we know that we have + // at least one full scan available. + guard count > 1 && lastSOSIndex > 0 else { return nil } + return data[0 ..< lastSOSIndex] + } + + func decode(_ data: Data, + with callbacks: [SessionDataTask.TaskCallback], + completion: @escaping (KFCrossPlatformImage?) -> Void) { + guard data.kf.contains(jpeg: .SOF2) else { + CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } + return + } + + func processing(_ data: Data) { + let processor = ImageDataProcessor( + data: data, + callbacks: callbacks, + processingQueue: processingQueue + ) + processor.onImageProcessed.delegate(on: self) { (self, result) in + guard let image = try? result.0.get() else { + CallbackQueue.mainCurrentOrAsync.execute { completion(nil) } + return + } + + CallbackQueue.mainCurrentOrAsync.execute { completion(image) } + } + processor.process() + } + + // Blur partial images. + let count = scannedCount + + if option.isBlur, count < 6 { + processingQueue.execute { + // Progressively reduce blur as we load more scans. + let image = KingfisherWrapper.image( + data: data, + options: self.creatingOptions + ) + let radius = max(2, 14 - count * 4) + let temp = image?.kf.blurred(withRadius: CGFloat(radius)) + processing(temp?.kf.data(format: .JPEG) ?? data) + } + + } else { + processing(data) + } + } +} + +private final class ImageProgressiveSerialQueue { + typealias ClosureCallback = ((@escaping () -> Void)) -> Void + + private let queue: DispatchQueue + private var items: [DispatchWorkItem] = [] + private var notify: (() -> Void)? + private var lastTime: TimeInterval? + var count: Int { return items.count } + + init() { + self.queue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue") + } + + func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) { + let completion = { [weak self] in + guard let self = self else { return } + + self.queue.async { [weak self] in + guard let self = self else { return } + guard !self.items.isEmpty else { return } + + self.items.removeFirst() + + if let next = self.items.first { + self.queue.asyncAfter( + deadline: .now() + interval, + execute: next + ) + + } else { + self.lastTime = Date().timeIntervalSince1970 + self.notify?() + self.notify = nil + } + } + } + + queue.async { [weak self] in + guard let self = self else { return } + + let item = DispatchWorkItem { + closure(completion) + } + if self.items.isEmpty { + let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0) + let delay = difference < interval ? interval - difference : 0 + self.queue.asyncAfter(deadline: .now() + delay, execute: item) + } + self.items.append(item) + } + } + + func notify(_ closure: @escaping () -> Void) { + self.notify = closure + } + + func clean() { + queue.async { [weak self] in + guard let self = self else { return } + self.items.forEach { $0.cancel() } + self.items.removeAll() + } + } +} diff --git a/Pods/Kingfisher/Sources/Image/ImageTransition.swift b/Pods/Kingfisher/Sources/Image/ImageTransition.swift new file mode 100644 index 0000000..4d042df --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/ImageTransition.swift @@ -0,0 +1,118 @@ +// +// ImageTransition.swift +// Kingfisher +// +// Created by Wei Wang on 15/9/18. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +#if os(iOS) || os(tvOS) +import UIKit + +/// Transition effect which will be used when an image downloaded and set by `UIImageView` +/// extension API in Kingfisher. You can assign an enum value with transition duration as +/// an item in `KingfisherOptionsInfo` to enable the animation transition. +/// +/// Apple's UIViewAnimationOptions is used under the hood. +/// For custom transition, you should specified your own transition options, animations and +/// completion handler as well. +/// +/// - none: No animation transition. +/// - fade: Fade in the loaded image in a given duration. +/// - flipFromLeft: Flip from left transition. +/// - flipFromRight: Flip from right transition. +/// - flipFromTop: Flip from top transition. +/// - flipFromBottom: Flip from bottom transition. +/// - custom: Custom transition. +public enum ImageTransition { + /// No animation transition. + case none + /// Fade in the loaded image in a given duration. + case fade(TimeInterval) + /// Flip from left transition. + case flipFromLeft(TimeInterval) + /// Flip from right transition. + case flipFromRight(TimeInterval) + /// Flip from top transition. + case flipFromTop(TimeInterval) + /// Flip from bottom transition. + case flipFromBottom(TimeInterval) + /// Custom transition defined by a general animation block. + /// - duration: The time duration of this custom transition. + /// - options: `UIView.AnimationOptions` should be used in the transition. + /// - animations: The animation block will be applied when setting image. + /// - completion: A block called when the transition animation finishes. + case custom(duration: TimeInterval, + options: UIView.AnimationOptions, + animations: ((UIImageView, UIImage) -> Void)?, + completion: ((Bool) -> Void)?) + + var duration: TimeInterval { + switch self { + case .none: return 0 + case .fade(let duration): return duration + + case .flipFromLeft(let duration): return duration + case .flipFromRight(let duration): return duration + case .flipFromTop(let duration): return duration + case .flipFromBottom(let duration): return duration + + case .custom(let duration, _, _, _): return duration + } + } + + var animationOptions: UIView.AnimationOptions { + switch self { + case .none: return [] + case .fade: return .transitionCrossDissolve + + case .flipFromLeft: return .transitionFlipFromLeft + case .flipFromRight: return .transitionFlipFromRight + case .flipFromTop: return .transitionFlipFromTop + case .flipFromBottom: return .transitionFlipFromBottom + + case .custom(_, let options, _, _): return options + } + } + + var animations: ((UIImageView, UIImage) -> Void)? { + switch self { + case .custom(_, _, let animations, _): return animations + default: return { $0.image = $1 } + } + } + + var completion: ((Bool) -> Void)? { + switch self { + case .custom(_, _, _, let completion): return completion + default: return nil + } + } +} +#else +// Just a placeholder for compiling on macOS. +public enum ImageTransition { + case none + /// This is a placeholder on macOS now. It is for SwiftUI (KFImage) to identify the fade option only. + case fade(TimeInterval) +} +#endif diff --git a/Pods/Kingfisher/Sources/Image/Placeholder.swift b/Pods/Kingfisher/Sources/Image/Placeholder.swift new file mode 100644 index 0000000..94d9e3a --- /dev/null +++ b/Pods/Kingfisher/Sources/Image/Placeholder.swift @@ -0,0 +1,82 @@ +// +// Placeholder.swift +// Kingfisher +// +// Created by Tieme van Veen on 28/08/2017. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +#if canImport(UIKit) +import UIKit +#endif + +/// Represents a placeholder type which could be set while loading as well as +/// loading finished without getting an image. +public protocol Placeholder { + + /// How the placeholder should be added to a given image view. + func add(to imageView: KFCrossPlatformImageView) + + /// How the placeholder should be removed from a given image view. + func remove(from imageView: KFCrossPlatformImageView) +} + +/// Default implementation of an image placeholder. The image will be set or +/// reset directly for `image` property of the image view. +extension KFCrossPlatformImage: Placeholder { + /// How the placeholder should be added to a given image view. + public func add(to imageView: KFCrossPlatformImageView) { imageView.image = self } + + /// How the placeholder should be removed from a given image view. + public func remove(from imageView: KFCrossPlatformImageView) { imageView.image = nil } +} + +/// Default implementation of an arbitrary view as placeholder. The view will be +/// added as a subview when adding and be removed from its super view when removing. +/// +/// To use your customize View type as placeholder, simply let it conforming to +/// `Placeholder` by `extension MyView: Placeholder {}`. +extension Placeholder where Self: KFCrossPlatformView { + + /// How the placeholder should be added to a given image view. + public func add(to imageView: KFCrossPlatformImageView) { + imageView.addSubview(self) + translatesAutoresizingMaskIntoConstraints = false + + centerXAnchor.constraint(equalTo: imageView.centerXAnchor).isActive = true + centerYAnchor.constraint(equalTo: imageView.centerYAnchor).isActive = true + heightAnchor.constraint(equalTo: imageView.heightAnchor).isActive = true + widthAnchor.constraint(equalTo: imageView.widthAnchor).isActive = true + } + + /// How the placeholder should be removed from a given image view. + public func remove(from imageView: KFCrossPlatformImageView) { + removeFromSuperview() + } +} + +#endif diff --git a/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift b/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift new file mode 100644 index 0000000..d3b3ea1 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/AuthenticationChallengeResponsable.swift @@ -0,0 +1,94 @@ +// +// AuthenticationChallengeResponsable.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +@available(*, deprecated, message: "Typo. Use `AuthenticationChallengeResponsible` instead", renamed: "AuthenticationChallengeResponsible") +public typealias AuthenticationChallengeResponsable = AuthenticationChallengeResponsible + +/// Protocol indicates that an authentication challenge could be handled. +public protocol AuthenticationChallengeResponsible: AnyObject { + + /// Called when a session level authentication challenge is received. + /// This method provide a chance to handle and response to the authentication + /// challenge before downloading could start. + /// + /// - Parameters: + /// - downloader: The downloader which receives this challenge. + /// - challenge: An object that contains the request for authentication. + /// - completionHandler: A handler that your delegate method must call. + /// + /// - Note: This method is a forward from `URLSessionDelegate.urlSession(:didReceiveChallenge:completionHandler:)`. + /// Please refer to the document of it in `URLSessionDelegate`. + func downloader( + _ downloader: ImageDownloader, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + + /// Called when a task level authentication challenge is received. + /// This method provide a chance to handle and response to the authentication + /// challenge before downloading could start. + /// + /// - Parameters: + /// - downloader: The downloader which receives this challenge. + /// - task: The task whose request requires authentication. + /// - challenge: An object that contains the request for authentication. + /// - completionHandler: A handler that your delegate method must call. + func downloader( + _ downloader: ImageDownloader, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) +} + +extension AuthenticationChallengeResponsible { + + public func downloader( + _ downloader: ImageDownloader, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { + if let trustedHosts = downloader.trustedHosts, trustedHosts.contains(challenge.protectionSpace.host) { + let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!) + completionHandler(.useCredential, credential) + return + } + } + + completionHandler(.performDefaultHandling, nil) + } + + public func downloader( + _ downloader: ImageDownloader, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + completionHandler(.performDefaultHandling, nil) + } + +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift b/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift new file mode 100644 index 0000000..b368972 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDataProcessor.swift @@ -0,0 +1,74 @@ +// +// ImageDataProcessor.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +private let sharedProcessingQueue: CallbackQueue = + .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process")) + +// Handles image processing work on an own process queue. +class ImageDataProcessor { + let data: Data + let callbacks: [SessionDataTask.TaskCallback] + let queue: CallbackQueue + + // Note: We have an optimization choice there, to reduce queue dispatch by checking callback + // queue settings in each option... + let onImageProcessed = Delegate<(Result, SessionDataTask.TaskCallback), Void>() + + init(data: Data, callbacks: [SessionDataTask.TaskCallback], processingQueue: CallbackQueue?) { + self.data = data + self.callbacks = callbacks + self.queue = processingQueue ?? sharedProcessingQueue + } + + func process() { + queue.execute(doProcess) + } + + private func doProcess() { + var processedImages = [String: KFCrossPlatformImage]() + for callback in callbacks { + let processor = callback.options.processor + var image = processedImages[processor.identifier] + if image == nil { + image = processor.process(item: .data(data), options: callback.options) + processedImages[processor.identifier] = image + } + + let result: Result + if let image = image { + let finalImage = callback.options.backgroundDecode ? image.kf.decoded : image + result = .success(finalImage) + } else { + let error = KingfisherError.processorError( + reason: .processingFailed(processor: processor, item: .data(data))) + result = .failure(error) + } + onImageProcessed.call((result, callback)) + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift b/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift new file mode 100644 index 0000000..d50ed9a --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDownloader.swift @@ -0,0 +1,488 @@ +// +// ImageDownloader.swift +// Kingfisher +// +// Created by Wei Wang on 15/4/6. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +typealias DownloadResult = Result + +/// Represents a success result of an image downloading progress. +public struct ImageLoadingResult { + + /// The downloaded image. + public let image: KFCrossPlatformImage + + /// Original URL of the image request. + public let url: URL? + + /// The raw data received from downloader. + public let originalData: Data +} + +/// Represents a task of an image downloading process. +public struct DownloadTask { + + /// The `SessionDataTask` object bounded to this download task. Multiple `DownloadTask`s could refer + /// to a same `sessionTask`. This is an optimization in Kingfisher to prevent multiple downloading task + /// for the same URL resource at the same time. + /// + /// When you `cancel` a `DownloadTask`, this `SessionDataTask` and its cancel token will be pass through. + /// You can use them to identify the cancelled task. + public let sessionTask: SessionDataTask + + /// The cancel token which is used to cancel the task. This is only for identify the task when it is cancelled. + /// To cancel a `DownloadTask`, use `cancel` instead. + public let cancelToken: SessionDataTask.CancelToken + + /// Cancel this task if it is running. It will do nothing if this task is not running. + /// + /// - Note: + /// In Kingfisher, there is an optimization to prevent starting another download task if the target URL is being + /// downloading. However, even when internally no new session task created, a `DownloadTask` will be still created + /// and returned when you call related methods, but it will share the session downloading task with a previous task. + /// In this case, if multiple `DownloadTask`s share a single session download task, cancelling a `DownloadTask` + /// does not affect other `DownloadTask`s. + /// + /// If you need to cancel all `DownloadTask`s of a url, use `ImageDownloader.cancel(url:)`. If you need to cancel + /// all downloading tasks of an `ImageDownloader`, use `ImageDownloader.cancelAll()`. + public func cancel() { + sessionTask.cancel(token: cancelToken) + } +} + +extension DownloadTask { + enum WrappedTask { + case download(DownloadTask) + case dataProviding + + func cancel() { + switch self { + case .download(let task): task.cancel() + case .dataProviding: break + } + } + + var value: DownloadTask? { + switch self { + case .download(let task): return task + case .dataProviding: return nil + } + } + } +} + +/// Represents a downloading manager for requesting the image with a URL from server. +open class ImageDownloader { + + // MARK: Singleton + /// The default downloader. + public static let `default` = ImageDownloader(name: "default") + + // MARK: Public Properties + /// The duration before the downloading is timeout. Default is 15 seconds. + open var downloadTimeout: TimeInterval = 15.0 + + /// A set of trusted hosts when receiving server trust challenges. A challenge with host name contained in this + /// set will be ignored. You can use this set to specify the self-signed site. It only will be used if you don't + /// specify the `authenticationChallengeResponder`. + /// + /// If `authenticationChallengeResponder` is set, this property will be ignored and the implementation of + /// `authenticationChallengeResponder` will be used instead. + open var trustedHosts: Set? + + /// Use this to set supply a configuration for the downloader. By default, + /// NSURLSessionConfiguration.ephemeralSessionConfiguration() will be used. + /// + /// You could change the configuration before a downloading task starts. + /// A configuration without persistent storage for caches is requested for downloader working correctly. + open var sessionConfiguration = URLSessionConfiguration.ephemeral { + didSet { + session.invalidateAndCancel() + session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) + } + } + open var sessionDelegate: SessionDelegate { + didSet { + session.invalidateAndCancel() + session = URLSession(configuration: sessionConfiguration, delegate: sessionDelegate, delegateQueue: nil) + setupSessionHandler() + } + } + + /// Whether the download requests should use pipeline or not. Default is false. + open var requestsUsePipelining = false + + /// Delegate of this `ImageDownloader` object. See `ImageDownloaderDelegate` protocol for more. + open weak var delegate: ImageDownloaderDelegate? + + /// A responder for authentication challenge. + /// Downloader will forward the received authentication challenge for the downloading session to this responder. + open weak var authenticationChallengeResponder: AuthenticationChallengeResponsible? + + private let name: String + private var session: URLSession + + // MARK: Initializers + + /// Creates a downloader with name. + /// + /// - Parameter name: The name for the downloader. It should not be empty. + public init(name: String) { + if name.isEmpty { + fatalError("[Kingfisher] You should specify a name for the downloader. " + + "A downloader with empty name is not permitted.") + } + + self.name = name + + sessionDelegate = SessionDelegate() + session = URLSession( + configuration: sessionConfiguration, + delegate: sessionDelegate, + delegateQueue: nil) + + authenticationChallengeResponder = self + setupSessionHandler() + } + + deinit { session.invalidateAndCancel() } + + private func setupSessionHandler() { + sessionDelegate.onReceiveSessionChallenge.delegate(on: self) { (self, invoke) in + self.authenticationChallengeResponder?.downloader(self, didReceive: invoke.1, completionHandler: invoke.2) + } + sessionDelegate.onReceiveSessionTaskChallenge.delegate(on: self) { (self, invoke) in + self.authenticationChallengeResponder?.downloader( + self, task: invoke.1, didReceive: invoke.2, completionHandler: invoke.3) + } + sessionDelegate.onValidStatusCode.delegate(on: self) { (self, code) in + return (self.delegate ?? self).isValidStatusCode(code, for: self) + } + sessionDelegate.onDownloadingFinished.delegate(on: self) { (self, value) in + let (url, result) = value + do { + let value = try result.get() + self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: value, error: nil) + } catch { + self.delegate?.imageDownloader(self, didFinishDownloadingImageForURL: url, with: nil, error: error) + } + } + sessionDelegate.onDidDownloadData.delegate(on: self) { (self, task) in + return (self.delegate ?? self).imageDownloader(self, didDownload: task.mutableData, with: task) + } + } + + // Wraps `completionHandler` to `onCompleted` respectively. + private func createCompletionCallBack(_ completionHandler: ((DownloadResult) -> Void)?) -> Delegate? { + return completionHandler.map { block -> Delegate in + + let delegate = Delegate, Void>() + delegate.delegate(on: self) { (self, callback) in + block(callback) + } + return delegate + } + } + + private func createTaskCallback( + _ completionHandler: ((DownloadResult) -> Void)?, + options: KingfisherParsedOptionsInfo + ) -> SessionDataTask.TaskCallback + { + return SessionDataTask.TaskCallback( + onCompleted: createCompletionCallBack(completionHandler), + options: options + ) + } + + private func createDownloadContext( + with url: URL, + options: KingfisherParsedOptionsInfo, + done: @escaping ((Result) -> Void) + ) + { + func checkRequestAndDone(r: URLRequest) { + + // There is a possibility that request modifier changed the url to `nil` or empty. + // In this case, throw an error. + guard let url = r.url, !url.absoluteString.isEmpty else { + done(.failure(KingfisherError.requestError(reason: .invalidURL(request: r)))) + return + } + + done(.success(DownloadingContext(url: url, request: r, options: options))) + } + + // Creates default request. + var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: downloadTimeout) + request.httpShouldUsePipelining = requestsUsePipelining + if #available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *) , options.lowDataModeSource != nil { + request.allowsConstrainedNetworkAccess = false + } + + if let requestModifier = options.requestModifier { + // Modifies request before sending. + requestModifier.modified(for: request) { result in + guard let finalRequest = result else { + done(.failure(KingfisherError.requestError(reason: .emptyRequest))) + return + } + checkRequestAndDone(r: finalRequest) + } + } else { + checkRequestAndDone(r: request) + } + } + + private func addDownloadTask( + context: DownloadingContext, + callback: SessionDataTask.TaskCallback + ) -> DownloadTask + { + // Ready to start download. Add it to session task manager (`sessionHandler`) + let downloadTask: DownloadTask + if let existingTask = sessionDelegate.task(for: context.url) { + downloadTask = sessionDelegate.append(existingTask, url: context.url, callback: callback) + } else { + let sessionDataTask = session.dataTask(with: context.request) + sessionDataTask.priority = context.options.downloadPriority + downloadTask = sessionDelegate.add(sessionDataTask, url: context.url, callback: callback) + } + return downloadTask + } + + + private func reportWillDownloadImage(url: URL, request: URLRequest) { + delegate?.imageDownloader(self, willDownloadImageForURL: url, with: request) + } + + private func reportDidDownloadImageData(result: Result<(Data, URLResponse?), KingfisherError>, url: URL) { + var response: URLResponse? + var err: Error? + do { + response = try result.get().1 + } catch { + err = error + } + self.delegate?.imageDownloader( + self, + didFinishDownloadingImageForURL: url, + with: response, + error: err + ) + } + + private func reportDidProcessImage( + result: Result, url: URL, response: URLResponse? + ) + { + if let image = try? result.get() { + self.delegate?.imageDownloader(self, didDownload: image, for: url, with: response) + } + + } + + private func startDownloadTask( + context: DownloadingContext, + callback: SessionDataTask.TaskCallback + ) -> DownloadTask + { + + let downloadTask = addDownloadTask(context: context, callback: callback) + + let sessionTask = downloadTask.sessionTask + guard !sessionTask.started else { + return downloadTask + } + + sessionTask.onTaskDone.delegate(on: self) { (self, done) in + // Underlying downloading finishes. + // result: Result<(Data, URLResponse?)>, callbacks: [TaskCallback] + let (result, callbacks) = done + + // Before processing the downloaded data. + self.reportDidDownloadImageData(result: result, url: context.url) + + switch result { + // Download finished. Now process the data to an image. + case .success(let (data, response)): + let processor = ImageDataProcessor( + data: data, callbacks: callbacks, processingQueue: context.options.processingQueue + ) + processor.onImageProcessed.delegate(on: self) { (self, done) in + // `onImageProcessed` will be called for `callbacks.count` times, with each + // `SessionDataTask.TaskCallback` as the input parameter. + // result: Result, callback: SessionDataTask.TaskCallback + let (result, callback) = done + + self.reportDidProcessImage(result: result, url: context.url, response: response) + + let imageResult = result.map { ImageLoadingResult(image: $0, url: context.url, originalData: data) } + let queue = callback.options.callbackQueue + queue.execute { callback.onCompleted?.call(imageResult) } + } + processor.process() + + case .failure(let error): + callbacks.forEach { callback in + let queue = callback.options.callbackQueue + queue.execute { callback.onCompleted?.call(.failure(error)) } + } + } + } + + reportWillDownloadImage(url: context.url, request: context.request) + sessionTask.resume() + return downloadTask + } + + // MARK: Downloading Task + /// Downloads an image with a URL and option. Invoked internally by Kingfisher. Subclasses must invoke super. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherParsedOptionsInfo, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var downloadTask: DownloadTask? + createDownloadContext(with: url, options: options) { result in + switch result { + case .success(let context): + // `downloadTask` will be set if the downloading started immediately. This is the case when no request + // modifier or a sync modifier (`ImageDownloadRequestModifier`) is used. Otherwise, when an + // `AsyncImageDownloadRequestModifier` is used the returned `downloadTask` of this method will be `nil` + // and the actual "delayed" task is given in `AsyncImageDownloadRequestModifier.onDownloadTaskStarted` + // callback. + downloadTask = self.startDownloadTask( + context: context, + callback: self.createTaskCallback(completionHandler, options: options) + ) + if let modifier = options.requestModifier { + modifier.onDownloadTaskStarted?(downloadTask) + } + case .failure(let error): + options.callbackQueue.execute { + completionHandler?(.failure(error)) + } + } + } + + return downloadTask + } + + /// Downloads an image with a URL and option. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - progressBlock: Called when the download progress updated. This block will be always be called in main queue. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherOptionsInfo? = nil, + progressBlock: DownloadProgressBlock? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + var info = KingfisherParsedOptionsInfo(options) + if let block = progressBlock { + info.onDataReceived = (info.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)] + } + return downloadImage( + with: url, + options: info, + completionHandler: completionHandler) + } + + /// Downloads an image with a URL and option. + /// + /// - Parameters: + /// - url: Target URL. + /// - options: The options could control download behavior. See `KingfisherOptionsInfo`. + /// - completionHandler: Called when the download progress finishes. This block will be called in the queue + /// defined in `.callbackQueue` in `options` parameter. + /// - Returns: A downloading task. You could call `cancel` on it to stop the download task. + @discardableResult + open func downloadImage( + with url: URL, + options: KingfisherOptionsInfo? = nil, + completionHandler: ((Result) -> Void)? = nil) -> DownloadTask? + { + downloadImage( + with: url, + options: KingfisherParsedOptionsInfo(options), + completionHandler: completionHandler + ) + } +} + +// MARK: Cancelling Task +extension ImageDownloader { + + /// Cancel all downloading tasks for this `ImageDownloader`. It will trigger the completion handlers + /// for all not-yet-finished downloading tasks. + /// + /// If you need to only cancel a certain task, call `cancel()` on the `DownloadTask` + /// returned by the downloading methods. If you need to cancel all `DownloadTask`s of a certain url, + /// use `ImageDownloader.cancel(url:)`. + public func cancelAll() { + sessionDelegate.cancelAll() + } + + /// Cancel all downloading tasks for a given URL. It will trigger the completion handlers for + /// all not-yet-finished downloading tasks for the URL. + /// + /// - Parameter url: The URL which you want to cancel downloading. + public func cancel(url: URL) { + sessionDelegate.cancel(url: url) + } +} + +// Use the default implementation from extension of `AuthenticationChallengeResponsible`. +extension ImageDownloader: AuthenticationChallengeResponsible {} + +// Use the default implementation from extension of `ImageDownloaderDelegate`. +extension ImageDownloader: ImageDownloaderDelegate {} + +extension ImageDownloader { + struct DownloadingContext { + let url: URL + let request: URLRequest + let options: KingfisherParsedOptionsInfo + } +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift b/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift new file mode 100644 index 0000000..7f98640 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageDownloaderDelegate.swift @@ -0,0 +1,154 @@ +// +// ImageDownloaderDelegate.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/11. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Protocol of `ImageDownloader`. This protocol provides a set of methods which are related to image downloader +/// working stages and rules. +public protocol ImageDownloaderDelegate: AnyObject { + + /// Called when the `ImageDownloader` object will start downloading an image from a specified URL. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - url: URL of the starting request. + /// - request: The request object for the download process. + /// + func imageDownloader(_ downloader: ImageDownloader, willDownloadImageForURL url: URL, with request: URLRequest?) + + /// Called when the `ImageDownloader` completes a downloading request with success or failure. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - url: URL of the original request URL. + /// - response: The response object of the downloading process. + /// - error: The error in case of failure. + /// + func imageDownloader( + _ downloader: ImageDownloader, + didFinishDownloadingImageForURL url: URL, + with response: URLResponse?, + error: Error?) + + /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is + /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition + /// processing on the image data. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - data: The original downloaded data. + /// - dataTask: The data task contains request and response information of the download. + /// - Note: + /// This can be used to pre-process raw image data before creation of `Image` instance (i.e. + /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with + /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image + /// processing flow if you find the data is corrupted or malformed. + /// + /// If this method is implemented, `imageDownloader(_:didDownload:for:)` will not be called anymore. + func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with dataTask: SessionDataTask) -> Data? + + /// Called when the `ImageDownloader` object successfully downloaded image data from specified URL. This is + /// your last chance to verify or modify the downloaded data before Kingfisher tries to perform addition + /// processing on the image data. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - data: The original downloaded data. + /// - url: The URL of the original request URL. + /// - Returns: The data from which Kingfisher should use to create an image. You need to provide valid data + /// which content is one of the supported image file format. Kingfisher will perform process on this + /// data and try to convert it to an image object. + /// - Note: + /// This can be used to pre-process raw image data before creation of `Image` instance (i.e. + /// decrypting or verification). If `nil` returned, the processing is interrupted and a `KingfisherError` with + /// `ResponseErrorReason.dataModifyingFailed` will be raised. You could use this fact to stop the image + /// processing flow if you find the data is corrupted or malformed. + /// + /// If `imageDownloader(_:didDownload:with:)` is implemented, this method will not be called anymore. + func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? + + /// Called when the `ImageDownloader` object successfully downloads and processes an image from specified URL. + /// + /// - Parameters: + /// - downloader: The `ImageDownloader` object which is used for the downloading operation. + /// - image: The downloaded and processed image. + /// - url: URL of the original request URL. + /// - response: The original response object of the downloading process. + /// + func imageDownloader( + _ downloader: ImageDownloader, + didDownload image: KFCrossPlatformImage, + for url: URL, + with response: URLResponse?) + + /// Checks if a received HTTP status code is valid or not. + /// By default, a status code in range 200..<400 is considered as valid. + /// If an invalid code is received, the downloader will raise an `KingfisherError` with + /// `ResponseErrorReason.invalidHTTPStatusCode` as its reason. + /// + /// - Parameters: + /// - code: The received HTTP status code. + /// - downloader: The `ImageDownloader` object asks for validate status code. + /// - Returns: Returns a value to indicate whether this HTTP status code is valid or not. + /// - Note: If the default 200 to 400 valid code does not suit your need, + /// you can implement this method to change that behavior. + func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool +} + +// Default implementation for `ImageDownloaderDelegate`. +extension ImageDownloaderDelegate { + public func imageDownloader( + _ downloader: ImageDownloader, + willDownloadImageForURL url: URL, + with request: URLRequest?) {} + + public func imageDownloader( + _ downloader: ImageDownloader, + didFinishDownloadingImageForURL url: URL, + with response: URLResponse?, + error: Error?) {} + + public func imageDownloader( + _ downloader: ImageDownloader, + didDownload image: KFCrossPlatformImage, + for url: URL, + with response: URLResponse?) {} + + public func isValidStatusCode(_ code: Int, for downloader: ImageDownloader) -> Bool { + return (200..<400).contains(code) + } + + public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, with task: SessionDataTask) -> Data? { + guard let url = task.originalURL else { + return data + } + return imageDownloader(downloader, didDownload: data, for: url) + } + + public func imageDownloader(_ downloader: ImageDownloader, didDownload data: Data, for url: URL) -> Data? { + return data + } +} diff --git a/Pods/Kingfisher/Sources/Networking/ImageModifier.swift b/Pods/Kingfisher/Sources/Networking/ImageModifier.swift new file mode 100644 index 0000000..0acd0e8 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImageModifier.swift @@ -0,0 +1,116 @@ +// +// ImageModifier.swift +// Kingfisher +// +// Created by Ethan Gill on 2017/11/28. +// +// Copyright (c) 2019 Ethan Gill +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// An `ImageModifier` can be used to change properties on an image between cache serialization and the actual use of +/// the image. The `modify(_:)` method will be called after the image retrieved from its source and before it returned +/// to the caller. This modified image is expected to be only used for rendering purpose, any changes applied by the +/// `ImageModifier` will not be serialized or cached. +public protocol ImageModifier { + /// Modify an input `Image`. + /// + /// - parameter image: Image which will be modified by `self` + /// + /// - returns: The modified image. + /// + /// - Note: The return value will be unmodified if modifying is not possible on + /// the current platform. + /// - Note: Most modifiers support UIImage or NSImage, but not CGImage. + func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage +} + +/// A wrapper for creating an `ImageModifier` easier. +/// This type conforms to `ImageModifier` and wraps an image modify block. +/// If the `block` throws an error, the original image will be used. +public struct AnyImageModifier: ImageModifier { + + /// A block which modifies images, or returns the original image + /// if modification cannot be performed with an error. + let block: (KFCrossPlatformImage) throws -> KFCrossPlatformImage + + /// Creates an `AnyImageModifier` with a given `modify` block. + public init(modify: @escaping (KFCrossPlatformImage) throws -> KFCrossPlatformImage) { + block = modify + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return (try? block(image)) ?? image + } +} + +#if os(iOS) || os(tvOS) || os(watchOS) +import UIKit + +/// Modifier for setting the rendering mode of images. +public struct RenderingModeImageModifier: ImageModifier { + + /// The rendering mode to apply to the image. + public let renderingMode: UIImage.RenderingMode + + /// Creates a `RenderingModeImageModifier`. + /// + /// - Parameter renderingMode: The rendering mode to apply to the image. Default is `.automatic`. + public init(renderingMode: UIImage.RenderingMode = .automatic) { + self.renderingMode = renderingMode + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.withRenderingMode(renderingMode) + } +} + +/// Modifier for setting the `flipsForRightToLeftLayoutDirection` property of images. +public struct FlipsForRightToLeftLayoutDirectionImageModifier: ImageModifier { + + /// Creates a `FlipsForRightToLeftLayoutDirectionImageModifier`. + public init() {} + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.imageFlippedForRightToLeftLayoutDirection() + } +} + +/// Modifier for setting the `alignmentRectInsets` property of images. +public struct AlignmentRectInsetsImageModifier: ImageModifier { + + /// The alignment insets to apply to the image + public let alignmentInsets: UIEdgeInsets + + /// Creates an `AlignmentRectInsetsImageModifier`. + public init(alignmentInsets: UIEdgeInsets) { + self.alignmentInsets = alignmentInsets + } + + /// Modify an input `Image`. See `ImageModifier` protocol for more. + public func modify(_ image: KFCrossPlatformImage) -> KFCrossPlatformImage { + return image.withAlignmentRectInsets(alignmentInsets) + } +} +#endif diff --git a/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift b/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift new file mode 100644 index 0000000..3fce14c --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/ImagePrefetcher.swift @@ -0,0 +1,442 @@ +// +// ImagePrefetcher.swift +// Kingfisher +// +// Created by Claire Knight on 24/02/2016 +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + + +#if os(macOS) +import AppKit +#else +import UIKit +#endif + +/// Progress update block of prefetcher when initialized with a list of resources. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while +/// downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherProgressBlock = + ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) + +/// Progress update block of prefetcher when initialized with a list of resources. +/// +/// - `skippedSources`: An array of sources that are already cached before the prefetching starting. +/// - `failedSources`: An array of sources that fail to be fetched. +/// - `completedResources`: An array of sources that are fetched and cached successfully. +public typealias PrefetcherSourceProgressBlock = + ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) + +/// Completion block of prefetcher when initialized with a list of sources. +/// +/// - `skippedResources`: An array of resources that are already cached before the prefetching starting. +/// - `failedResources`: An array of resources that fail to be downloaded. It could because of being cancelled while +/// downloading, encountered an error when downloading or the download not being started at all. +/// - `completedResources`: An array of resources that are downloaded and cached successfully. +public typealias PrefetcherCompletionHandler = + ((_ skippedResources: [Resource], _ failedResources: [Resource], _ completedResources: [Resource]) -> Void) + +/// Completion block of prefetcher when initialized with a list of sources. +/// +/// - `skippedSources`: An array of sources that are already cached before the prefetching starting. +/// - `failedSources`: An array of sources that fail to be fetched. +/// - `completedSources`: An array of sources that are fetched and cached successfully. +public typealias PrefetcherSourceCompletionHandler = + ((_ skippedSources: [Source], _ failedSources: [Source], _ completedSources: [Source]) -> Void) + +/// `ImagePrefetcher` represents a downloading manager for requesting many images via URLs, then caching them. +/// This is useful when you know a list of image resources and want to download them before showing. It also works with +/// some Cocoa prefetching mechanism like table view or collection view `prefetchDataSource`, to start image downloading +/// and caching before they display on screen. +public class ImagePrefetcher: CustomStringConvertible { + + public var description: String { + return "\(Unmanaged.passUnretained(self).toOpaque())" + } + + /// The maximum concurrent downloads to use when prefetching images. Default is 5. + public var maxConcurrentDownloads = 5 + + private let prefetchSources: [Source] + private let optionsInfo: KingfisherParsedOptionsInfo + + private var progressBlock: PrefetcherProgressBlock? + private var completionHandler: PrefetcherCompletionHandler? + + private var progressSourceBlock: PrefetcherSourceProgressBlock? + private var completionSourceHandler: PrefetcherSourceCompletionHandler? + + private var tasks = [String: DownloadTask.WrappedTask]() + + private var pendingSources: ArraySlice + private var skippedSources = [Source]() + private var completedSources = [Source]() + private var failedSources = [Source]() + + private var stopped = false + + // A manager used for prefetching. We will use the helper methods in manager. + private let manager: KingfisherManager + + private let pretchQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.pretchQueue") + private static let requestingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.ImagePrefetcher.requestingQueue") + + private var finished: Bool { + let totalFinished: Int = failedSources.count + skippedSources.count + completedSources.count + return totalFinished == prefetchSources.count && tasks.isEmpty + } + + /// Creates an image prefetcher with an array of URLs. + /// + /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. + /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. + /// The images which are already cached will be skipped without downloading again. + /// + /// - Parameters: + /// - urls: The URLs which should be prefetched. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + urls: [URL], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + let resources: [Resource] = urls.map { $0 } + self.init( + resources: resources, + options: options, + progressBlock: progressBlock, + completionHandler: completionHandler) + } + + /// Creates an image prefetcher with an array of URLs. + /// + /// The prefetcher should be initiated with a list of prefetching targets. The URLs list is immutable. + /// After you get a valid `ImagePrefetcher` object, you call `start()` on it to begin the prefetching process. + /// The images which are already cached will be skipped without downloading again. + /// + /// - Parameters: + /// - urls: The URLs which should be prefetched. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + urls: [URL], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + let resources: [Resource] = urls.map { $0 } + self.init( + resources: resources, + options: options, + progressBlock: nil, + completionHandler: completionHandler) + } + + /// Creates an image prefetcher with an array of resources. + /// + /// - Parameters: + /// - resources: The resources which should be prefetched. See `Resource` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an resource is downloaded, skipped or cancelled. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + resources: [Resource], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherProgressBlock? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + self.init(sources: resources.map { $0.convertToSource() }, options: options) + self.progressBlock = progressBlock + self.completionHandler = completionHandler + } + + /// Creates an image prefetcher with an array of resources. + /// + /// - Parameters: + /// - resources: The resources which should be prefetched. See `Resource` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init( + resources: [Resource], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherCompletionHandler? = nil) + { + self.init(sources: resources.map { $0.convertToSource() }, options: options) + self.completionHandler = completionHandler + } + + /// Creates an image prefetcher with an array of sources. + /// + /// - Parameters: + /// - sources: The sources which should be prefetched. See `Source` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - progressBlock: Called every time an source fetching successes, fails, is skipped. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init(sources: [Source], + options: KingfisherOptionsInfo? = nil, + progressBlock: PrefetcherSourceProgressBlock? = nil, + completionHandler: PrefetcherSourceCompletionHandler? = nil) + { + self.init(sources: sources, options: options) + self.progressSourceBlock = progressBlock + self.completionSourceHandler = completionHandler + } + + /// Creates an image prefetcher with an array of sources. + /// + /// - Parameters: + /// - sources: The sources which should be prefetched. See `Source` type for more. + /// - options: Options could control some behaviors. See `KingfisherOptionsInfo` for more. + /// - completionHandler: Called when the whole prefetching process finished. + /// + /// - Note: + /// By default, the `ImageDownloader.defaultDownloader` and `ImageCache.defaultCache` will be used as + /// the downloader and cache target respectively. You can specify another downloader or cache by using + /// a customized `KingfisherOptionsInfo`. Both the progress and completion block will be invoked in + /// main thread. The `.callbackQueue` value in `optionsInfo` will be ignored in this method. + public convenience init(sources: [Source], + options: KingfisherOptionsInfo? = nil, + completionHandler: PrefetcherSourceCompletionHandler? = nil) + { + self.init(sources: sources, options: options) + self.completionSourceHandler = completionHandler + } + + init(sources: [Source], options: KingfisherOptionsInfo?) { + var options = KingfisherParsedOptionsInfo(options) + prefetchSources = sources + pendingSources = ArraySlice(sources) + + // We want all callbacks from our prefetch queue, so we should ignore the callback queue in options. + // Add our own callback dispatch queue to make sure all internal callbacks are + // coming back in our expected queue. + options.callbackQueue = .dispatch(pretchQueue) + optionsInfo = options + + let cache = optionsInfo.targetCache ?? .default + let downloader = optionsInfo.downloader ?? .default + manager = KingfisherManager(downloader: downloader, cache: cache) + } + + /// Starts to download the resources and cache them. This can be useful for background downloading + /// of assets that are required for later use in an app. This code will not try and update any UI + /// with the results of the process. + public func start() { + pretchQueue.async { + guard !self.stopped else { + assertionFailure("You can not restart the same prefetcher. Try to create a new prefetcher.") + self.handleComplete() + return + } + + guard self.maxConcurrentDownloads > 0 else { + assertionFailure("There should be concurrent downloads value should be at least 1.") + self.handleComplete() + return + } + + // Empty case. + guard self.prefetchSources.count > 0 else { + self.handleComplete() + return + } + + let initialConcurrentDownloads = min(self.prefetchSources.count, self.maxConcurrentDownloads) + for _ in 0 ..< initialConcurrentDownloads { + if let resource = self.pendingSources.popFirst() { + self.startPrefetching(resource) + } + } + } + } + + /// Stops current downloading progress, and cancel any future prefetching activity that might be occuring. + public func stop() { + pretchQueue.async { + if self.finished { return } + self.stopped = true + self.tasks.values.forEach { $0.cancel() } + } + } + + private func downloadAndCache(_ source: Source) { + + let downloadTaskCompletionHandler: ((Result) -> Void) = { result in + self.tasks.removeValue(forKey: source.cacheKey) + do { + let _ = try result.get() + self.completedSources.append(source) + } catch { + self.failedSources.append(source) + } + + self.reportProgress() + if self.stopped { + if self.tasks.isEmpty { + self.failedSources.append(contentsOf: self.pendingSources) + self.handleComplete() + } + } else { + self.reportCompletionOrStartNext() + } + } + + var downloadTask: DownloadTask.WrappedTask? + ImagePrefetcher.requestingQueue.sync { + let context = RetrievingContext( + options: optionsInfo, originalSource: source + ) + downloadTask = manager.loadAndCacheImage( + source: source, + context: context, + completionHandler: downloadTaskCompletionHandler) + } + + if let downloadTask = downloadTask { + tasks[source.cacheKey] = downloadTask + } + } + + private func append(cached source: Source) { + skippedSources.append(source) + + reportProgress() + reportCompletionOrStartNext() + } + + private func startPrefetching(_ source: Source) + { + if optionsInfo.forceRefresh { + downloadAndCache(source) + return + } + + let cacheType = manager.cache.imageCachedType( + forKey: source.cacheKey, + processorIdentifier: optionsInfo.processor.identifier) + switch cacheType { + case .memory: + append(cached: source) + case .disk: + if optionsInfo.alsoPrefetchToMemory { + let context = RetrievingContext(options: optionsInfo, originalSource: source) + _ = manager.retrieveImageFromCache( + source: source, + context: context) + { + _ in + self.append(cached: source) + } + } else { + append(cached: source) + } + case .none: + downloadAndCache(source) + } + } + + private func reportProgress() { + + if progressBlock == nil && progressSourceBlock == nil { + return + } + + let skipped = self.skippedSources + let failed = self.failedSources + let completed = self.completedSources + CallbackQueue.mainCurrentOrAsync.execute { + self.progressSourceBlock?(skipped, failed, completed) + self.progressBlock?( + skipped.compactMap { $0.asResource }, + failed.compactMap { $0.asResource }, + completed.compactMap { $0.asResource } + ) + } + } + + private func reportCompletionOrStartNext() { + if let resource = self.pendingSources.popFirst() { + // Loose call stack for huge ammount of sources. + pretchQueue.async { self.startPrefetching(resource) } + } else { + guard allFinished else { return } + self.handleComplete() + } + } + + var allFinished: Bool { + return skippedSources.count + failedSources.count + completedSources.count == prefetchSources.count + } + + private func handleComplete() { + + if completionHandler == nil && completionSourceHandler == nil { + return + } + + // The completion handler should be called on the main thread + CallbackQueue.mainCurrentOrAsync.execute { + self.completionSourceHandler?(self.skippedSources, self.failedSources, self.completedSources) + self.completionHandler?( + self.skippedSources.compactMap { $0.asResource }, + self.failedSources.compactMap { $0.asResource }, + self.completedSources.compactMap { $0.asResource } + ) + self.completionHandler = nil + self.progressBlock = nil + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift b/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift new file mode 100644 index 0000000..0d13cbe --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RedirectHandler.swift @@ -0,0 +1,76 @@ +// +// RedirectHandler.swift +// Kingfisher +// +// Created by Roman Maidanovych on 2018/12/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents and wraps a method for modifying request during an image download request redirection. +public protocol ImageDownloadRedirectHandler { + + /// The `ImageDownloadRedirectHandler` contained will be used to change the request before redirection. + /// This is the posibility you can modify the image download request during redirection. You can modify the + /// request for some customizing purpose, such as adding auth token to the header, do basic HTTP auth or + /// something like url mapping. + /// + /// Usually, you pass an `ImageDownloadRedirectHandler` as the associated value of + /// `KingfisherOptionsInfoItem.redirectHandler` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will redirect with it. + /// + /// - Parameters: + /// - task: The current `SessionDataTask` which triggers this redirect. + /// - response: The response received during redirection. + /// - newRequest: The request for redirection which can be modified. + /// - completionHandler: A closure for being called with modified request. + func handleHTTPRedirection( + for task: SessionDataTask, + response: HTTPURLResponse, + newRequest: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) +} + +/// A wrapper for creating an `ImageDownloadRedirectHandler` easier. +/// This type conforms to `ImageDownloadRedirectHandler` and wraps a redirect request modify block. +public struct AnyRedirectHandler: ImageDownloadRedirectHandler { + + let block: (SessionDataTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void + + public func handleHTTPRedirection( + for task: SessionDataTask, + response: HTTPURLResponse, + newRequest: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + block(task, response, newRequest, completionHandler) + } + + /// Creates a value of `ImageDownloadRedirectHandler` which runs `modify` block. + /// + /// - Parameter modify: The request modifying block runs when a request modifying task comes. + /// + public init(handle: @escaping (SessionDataTask, HTTPURLResponse, URLRequest, @escaping (URLRequest?) -> Void) -> Void) { + block = handle + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RequestModifier.swift b/Pods/Kingfisher/Sources/Networking/RequestModifier.swift new file mode 100644 index 0000000..a1d972d --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RequestModifier.swift @@ -0,0 +1,108 @@ +// +// RequestModifier.swift +// Kingfisher +// +// Created by Wei Wang on 2016/09/05. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents and wraps a method for modifying request before an image download request starts in an asynchronous way. +public protocol AsyncImageDownloadRequestModifier { + + /// This method will be called just before the `request` being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// When you have done with the modification, call the `reportModified` block with the modified request and the data + /// download will happen with this request. + /// + /// Usually, you pass an `AsyncImageDownloadRequestModifier` as the associated value of + /// `KingfisherOptionsInfoItem.requestModifier` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will start with it. + /// + /// - Parameters: + /// - request: The input request contains necessary information like `url`. This request is generated + /// according to your resource url as a GET request. + /// - reportModified: The callback block you need to call after the asynchronous modifying done. + /// + func modified(for request: URLRequest, reportModified: @escaping (URLRequest?) -> Void) + + /// A block will be called when the download task started. + /// + /// If an `AsyncImageDownloadRequestModifier` and the asynchronous modification happens before the download, the + /// related download method will not return a valid `DownloadTask` value. Instead, you can get one from this method. + var onDownloadTaskStarted: ((DownloadTask?) -> Void)? { get } +} + +/// Represents and wraps a method for modifying request before an image download request starts. +public protocol ImageDownloadRequestModifier: AsyncImageDownloadRequestModifier { + + /// This method will be called just before the `request` being sent. + /// This is the last chance you can modify the image download request. You can modify the request for some + /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping. + /// + /// Usually, you pass an `ImageDownloadRequestModifier` as the associated value of + /// `KingfisherOptionsInfoItem.requestModifier` and use it as the `options` parameter in related methods. + /// + /// If you do nothing with the input `request` and return it as is, a downloading process will start with it. + /// + /// - Parameter request: The input request contains necessary information like `url`. This request is generated + /// according to your resource url as a GET request. + /// - Returns: A modified version of request, which you wish to use for downloading an image. If `nil` returned, + /// a `KingfisherError.requestError` with `.emptyRequest` as its reason will occur. + /// + func modified(for request: URLRequest) -> URLRequest? +} + +extension ImageDownloadRequestModifier { + public func modified(for request: URLRequest, reportModified: @escaping (URLRequest?) -> Void) { + let request = modified(for: request) + reportModified(request) + } + + /// This is `nil` for a sync `ImageDownloadRequestModifier` by default. You can get the `DownloadTask` from the + /// return value of downloader method. + public var onDownloadTaskStarted: ((DownloadTask?) -> Void)? { return nil } +} + +/// A wrapper for creating an `ImageDownloadRequestModifier` easier. +/// This type conforms to `ImageDownloadRequestModifier` and wraps an image modify block. +public struct AnyModifier: ImageDownloadRequestModifier { + + let block: (URLRequest) -> URLRequest? + + /// For `ImageDownloadRequestModifier` conformation. + public func modified(for request: URLRequest) -> URLRequest? { + return block(request) + } + + /// Creates a value of `ImageDownloadRequestModifier` which runs `modify` block. + /// + /// - Parameter modify: The request modifying block runs when a request modifying task comes. + /// The return `URLRequest?` value of this block will be used as the image download request. + /// If `nil` returned, a `KingfisherError.requestError` with `.emptyRequest` as its + /// reason will occur. + public init(modify: @escaping (URLRequest) -> URLRequest?) { + block = modify + } +} diff --git a/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift b/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift new file mode 100644 index 0000000..1ab5a2e --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/RetryStrategy.swift @@ -0,0 +1,153 @@ +// +// RetryStrategy.swift +// Kingfisher +// +// Created by onevcat on 2020/05/04. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a retry context which could be used to determine the current retry status. +public class RetryContext { + + /// The source from which the target image should be retrieved. + public let source: Source + + /// The last error which caused current retry behavior. + public let error: KingfisherError + + /// The retried count before current retry happens. This value is `0` if the current retry is for the first time. + public var retriedCount: Int + + /// A user set value for passing any other information during the retry. If you choose to use `RetryDecision.retry` + /// as the retry decision for `RetryStrategy.retry(context:retryHandler:)`, the associated value of + /// `RetryDecision.retry` will be delivered to you in the next retry. + public internal(set) var userInfo: Any? = nil + + init(source: Source, error: KingfisherError) { + self.source = source + self.error = error + self.retriedCount = 0 + } + + @discardableResult + func increaseRetryCount() -> RetryContext { + retriedCount += 1 + return self + } +} + +/// Represents decision of behavior on the current retry. +public enum RetryDecision { + /// A retry should happen. The associated `userInfo` will be pass to the next retry in the `RetryContext` parameter. + case retry(userInfo: Any?) + /// There should be no more retry attempt. The image retrieving process will fail with an error. + case stop +} + +/// Defines a retry strategy can be applied to a `.retryStrategy` option. +public protocol RetryStrategy { + + /// Kingfisher calls this method if an error happens during the image retrieving process from a `KingfisherManager`. + /// You implement this method to provide necessary logic based on the `context` parameter. Then you need to call + /// `retryHandler` to pass the retry decision back to Kingfisher. + /// + /// - Parameters: + /// - context: The retry context containing information of current retry attempt. + /// - retryHandler: A block you need to call with a decision of whether the retry should happen or not. + func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) +} + +/// A retry strategy that guides Kingfisher to retry when a `.responseError` happens, with a specified max retry count +/// and a certain interval mechanism. +public struct DelayRetryStrategy: RetryStrategy { + + /// Represents the interval mechanism which used in a `DelayRetryStrategy`. + public enum Interval { + /// The next retry attempt should happen in fixed seconds. For example, if the associated value is 3, the + /// attempts happens after 3 seconds after the previous decision is made. + case seconds(TimeInterval) + /// The next retry attempt should happen in an accumulated duration. For example, if the associated value is 3, + /// the attempts happens with interval of 3, 6, 9, 12, ... seconds. + case accumulated(TimeInterval) + /// Uses a block to determine the next interval. The current retry count is given as a parameter. + case custom(block: (_ retriedCount: Int) -> TimeInterval) + + func timeInterval(for retriedCount: Int) -> TimeInterval { + let retryAfter: TimeInterval + switch self { + case .seconds(let interval): + retryAfter = interval + case .accumulated(let interval): + retryAfter = Double(retriedCount + 1) * interval + case .custom(let block): + retryAfter = block(retriedCount) + } + return retryAfter + } + } + + /// The max retry count defined for the retry strategy + public let maxRetryCount: Int + + /// The retry interval mechanism defined for the retry strategy. + public let retryInterval: Interval + + /// Creates a delay retry strategy. + /// - Parameters: + /// - maxRetryCount: The max retry count. + /// - retryInterval: The retry interval mechanism. By default, `.seconds(3)` is used to provide a constant retry + /// interval. + public init(maxRetryCount: Int, retryInterval: Interval = .seconds(3)) { + self.maxRetryCount = maxRetryCount + self.retryInterval = retryInterval + } + + public func retry(context: RetryContext, retryHandler: @escaping (RetryDecision) -> Void) { + // Retry count exceeded. + guard context.retriedCount < maxRetryCount else { + retryHandler(.stop) + return + } + + // User cancel the task. No retry. + guard !context.error.isTaskCancelled else { + retryHandler(.stop) + return + } + + // Only retry for a response error. + guard case KingfisherError.responseError = context.error else { + retryHandler(.stop) + return + } + + let interval = retryInterval.timeInterval(for: context.retriedCount) + if interval == 0 { + retryHandler(.retry(userInfo: nil)) + } else { + DispatchQueue.main.asyncAfter(deadline: .now() + interval) { + retryHandler(.retry(userInfo: nil)) + } + } + } +} diff --git a/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift b/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift new file mode 100644 index 0000000..021e46e --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/SessionDataTask.swift @@ -0,0 +1,121 @@ +// +// SessionDataTask.swift +// Kingfisher +// +// Created by Wei Wang on 2018/11/1. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +/// Represents a session data task in `ImageDownloader`. It consists of an underlying `URLSessionDataTask` and +/// an array of `TaskCallback`. Multiple `TaskCallback`s could be added for a single downloading data task. +public class SessionDataTask { + + /// Represents the type of token which used for cancelling a task. + public typealias CancelToken = Int + + struct TaskCallback { + let onCompleted: Delegate, Void>? + let options: KingfisherParsedOptionsInfo + } + + /// Downloaded raw data of current task. + public private(set) var mutableData: Data + + // This is a copy of `task.originalRequest?.url`. It is for getting a race-safe behavior for a pitfall on iOS 13. + // Ref: https://github.com/onevcat/Kingfisher/issues/1511 + public let originalURL: URL? + + /// The underlying download task. It is only for debugging purpose when you encountered an error. You should not + /// modify the content of this task or start it yourself. + public let task: URLSessionDataTask + private var callbacksStore = [CancelToken: TaskCallback]() + + var callbacks: [SessionDataTask.TaskCallback] { + lock.lock() + defer { lock.unlock() } + return Array(callbacksStore.values) + } + + private var currentToken = 0 + private let lock = NSLock() + + let onTaskDone = Delegate<(Result<(Data, URLResponse?), KingfisherError>, [TaskCallback]), Void>() + let onCallbackCancelled = Delegate<(CancelToken, TaskCallback), Void>() + + var started = false + var containsCallbacks: Bool { + // We should be able to use `task.state != .running` to check it. + // However, in some rare cases, cancelling the task does not change + // task state to `.cancelling` immediately, but still in `.running`. + // So we need to check callbacks count to for sure that it is safe to remove the + // task in delegate. + return !callbacks.isEmpty + } + + init(task: URLSessionDataTask) { + self.task = task + self.originalURL = task.originalRequest?.url + mutableData = Data() + } + + func addCallback(_ callback: TaskCallback) -> CancelToken { + lock.lock() + defer { lock.unlock() } + callbacksStore[currentToken] = callback + defer { currentToken += 1 } + return currentToken + } + + func removeCallback(_ token: CancelToken) -> TaskCallback? { + lock.lock() + defer { lock.unlock() } + if let callback = callbacksStore[token] { + callbacksStore[token] = nil + return callback + } + return nil + } + + func resume() { + guard !started else { return } + started = true + task.resume() + } + + func cancel(token: CancelToken) { + guard let callback = removeCallback(token) else { + return + } + onCallbackCancelled.call((token, callback)) + } + + func forceCancel() { + for token in callbacksStore.keys { + cancel(token: token) + } + } + + func didReceiveData(_ data: Data) { + mutableData.append(data) + } +} diff --git a/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift b/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift new file mode 100644 index 0000000..17a8930 --- /dev/null +++ b/Pods/Kingfisher/Sources/Networking/SessionDelegate.swift @@ -0,0 +1,262 @@ +// +// SessionDelegate.swift +// Kingfisher +// +// Created by Wei Wang on 2018/11/1. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// Represents the delegate object of downloader session. It also behave like a task manager for downloading. +@objc(KFSessionDelegate) // Fix for ObjC header name conflicting. https://github.com/onevcat/Kingfisher/issues/1530 +open class SessionDelegate: NSObject { + + typealias SessionChallengeFunc = ( + URLSession, + URLAuthenticationChallenge, + (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) + + typealias SessionTaskChallengeFunc = ( + URLSession, + URLSessionTask, + URLAuthenticationChallenge, + (URLSession.AuthChallengeDisposition, URLCredential?) -> Void + ) + + private var tasks: [URL: SessionDataTask] = [:] + private let lock = NSLock() + + let onValidStatusCode = Delegate() + let onDownloadingFinished = Delegate<(URL, Result), Void>() + let onDidDownloadData = Delegate() + + let onReceiveSessionChallenge = Delegate() + let onReceiveSessionTaskChallenge = Delegate() + + func add( + _ dataTask: URLSessionDataTask, + url: URL, + callback: SessionDataTask.TaskCallback) -> DownloadTask + { + lock.lock() + defer { lock.unlock() } + + // Create a new task if necessary. + let task = SessionDataTask(task: dataTask) + task.onCallbackCancelled.delegate(on: self) { [weak task] (self, value) in + guard let task = task else { return } + + let (token, callback) = value + + let error = KingfisherError.requestError(reason: .taskCancelled(task: task, token: token)) + task.onTaskDone.call((.failure(error), [callback])) + // No other callbacks waiting, we can clear the task now. + if !task.containsCallbacks { + let dataTask = task.task + + self.cancelTask(dataTask) + self.remove(task) + } + } + let token = task.addCallback(callback) + tasks[url] = task + return DownloadTask(sessionTask: task, cancelToken: token) + } + + private func cancelTask(_ dataTask: URLSessionDataTask) { + lock.lock() + defer { lock.unlock() } + dataTask.cancel() + } + + func append( + _ task: SessionDataTask, + url: URL, + callback: SessionDataTask.TaskCallback) -> DownloadTask + { + let token = task.addCallback(callback) + return DownloadTask(sessionTask: task, cancelToken: token) + } + + private func remove(_ task: SessionDataTask) { + lock.lock() + defer { lock.unlock() } + + guard let url = task.originalURL else { + return + } + tasks[url] = nil + } + + private func task(for task: URLSessionTask) -> SessionDataTask? { + lock.lock() + defer { lock.unlock() } + + guard let url = task.originalRequest?.url else { + return nil + } + guard let sessionTask = tasks[url] else { + return nil + } + guard sessionTask.task.taskIdentifier == task.taskIdentifier else { + return nil + } + return sessionTask + } + + func task(for url: URL) -> SessionDataTask? { + lock.lock() + defer { lock.unlock() } + return tasks[url] + } + + func cancelAll() { + lock.lock() + let taskValues = tasks.values + lock.unlock() + for task in taskValues { + task.forceCancel() + } + } + + func cancel(url: URL) { + lock.lock() + let task = tasks[url] + lock.unlock() + task?.forceCancel() + } +} + +extension SessionDelegate: URLSessionDataDelegate { + + open func urlSession( + _ session: URLSession, + dataTask: URLSessionDataTask, + didReceive response: URLResponse, + completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) + { + guard let httpResponse = response as? HTTPURLResponse else { + let error = KingfisherError.responseError(reason: .invalidURLResponse(response: response)) + onCompleted(task: dataTask, result: .failure(error)) + completionHandler(.cancel) + return + } + + let httpStatusCode = httpResponse.statusCode + guard onValidStatusCode.call(httpStatusCode) == true else { + let error = KingfisherError.responseError(reason: .invalidHTTPStatusCode(response: httpResponse)) + onCompleted(task: dataTask, result: .failure(error)) + completionHandler(.cancel) + return + } + completionHandler(.allow) + } + + open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { + guard let task = self.task(for: dataTask) else { + return + } + + task.didReceiveData(data) + + task.callbacks.forEach { callback in + callback.options.onDataReceived?.forEach { sideEffect in + sideEffect.onDataReceived(session, task: task, data: data) + } + } + } + + open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { + guard let sessionTask = self.task(for: task) else { return } + + if let url = sessionTask.originalURL { + let result: Result + if let error = error { + result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error))) + } else if let response = task.response { + result = .success(response) + } else { + result = .failure(KingfisherError.responseError(reason: .noURLResponse(task: sessionTask))) + } + onDownloadingFinished.call((url, result)) + } + + let result: Result<(Data, URLResponse?), KingfisherError> + if let error = error { + result = .failure(KingfisherError.responseError(reason: .URLSessionError(error: error))) + } else { + if let data = onDidDownloadData.call(sessionTask) { + result = .success((data, task.response)) + } else { + result = .failure(KingfisherError.responseError(reason: .dataModifyingFailed(task: sessionTask))) + } + } + onCompleted(task: task, result: result) + } + + open func urlSession( + _ session: URLSession, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionChallenge.call((session, challenge, completionHandler)) + } + + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + didReceive challenge: URLAuthenticationChallenge, + completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) + { + onReceiveSessionTaskChallenge.call((session, task, challenge, completionHandler)) + } + + open func urlSession( + _ session: URLSession, + task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, + newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) + { + guard let sessionDataTask = self.task(for: task), + let redirectHandler = Array(sessionDataTask.callbacks).last?.options.redirectHandler else + { + completionHandler(request) + return + } + + redirectHandler.handleHTTPRedirection( + for: sessionDataTask, + response: response, + newRequest: request, + completionHandler: completionHandler) + } + + private func onCompleted(task: URLSessionTask, result: Result<(Data, URLResponse?), KingfisherError>) { + guard let sessionTask = self.task(for: task) else { + return + } + remove(sessionTask) + sessionTask.onTaskDone.call((result, sessionTask.callbacks)) + } +} diff --git a/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift b/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift new file mode 100644 index 0000000..eb3e23c --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/ImageBinder.swift @@ -0,0 +1,120 @@ +// +// ImageBinder.swift +// Kingfisher +// +// Created by onevcat on 2019/06/27. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + + /// Represents a binder for `KFImage`. It takes responsibility as an `ObjectBinding` and performs + /// image downloading and progress reporting based on `KingfisherManager`. + class ImageBinder: ObservableObject { + + init() {} + + var downloadTask: DownloadTask? + private var loading = false + + var loadingOrSucceeded: Bool { + return loading || loadedImage != nil + } + + @Published var loaded = false + @Published var loadedImage: KFCrossPlatformImage? = nil + @Published var progress: Progress = .init() + + func start(context: Context) { + guard let source = context.source else { + CallbackQueue.mainCurrentOrAsync.execute { + context.onFailureDelegate.call(KingfisherError.imageSettingError(reason: .emptySource)) + } + return + } + + loading = true + + progress = .init() + downloadTask = KingfisherManager.shared + .retrieveImage( + with: source, + options: context.options, + progressBlock: { size, total in + self.updateProgress(downloaded: size, total: total) + context.onProgressDelegate.call((size, total)) + }, + completionHandler: { [weak self] result in + + guard let self = self else { return } + + CallbackQueue.mainCurrentOrAsync.execute { + self.downloadTask = nil + self.loading = false + } + + switch result { + case .success(let value): + CallbackQueue.mainCurrentOrAsync.execute { + self.loadedImage = value.image + let animation = context.fadeTransitionDuration(cacheType: value.cacheType) + .map { duration in Animation.linear(duration: duration) } + withAnimation(animation) { self.loaded = true } + } + + CallbackQueue.mainAsync.execute { + context.onSuccessDelegate.call(value) + } + case .failure(let error): + CallbackQueue.mainCurrentOrAsync.execute { + if let image = context.options.onFailureImage { + self.loadedImage = image + } + self.loaded = true + } + + CallbackQueue.mainAsync.execute { + context.onFailureDelegate.call(error) + } + } + }) + } + + private func updateProgress(downloaded: Int64, total: Int64) { + progress.totalUnitCount = total + progress.completedUnitCount = downloaded + objectWillChange.send() + } + + /// Cancels the download task if it is in progress. + func cancel() { + downloadTask?.cancel() + downloadTask = nil + loading = false + } + } +} +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift b/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift new file mode 100644 index 0000000..7275f0e --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/ImageContext.swift @@ -0,0 +1,99 @@ +// +// ImageContext.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + public class Context { + let source: Source? + var options = KingfisherParsedOptionsInfo( + KingfisherManager.shared.defaultOptions + [.loadDiskFileSynchronously] + ) + + var configurations: [(HoldingView) -> HoldingView] = [] + var renderConfigurations: [(HoldingView.RenderingView) -> Void] = [] + + var cancelOnDisappear: Bool = false + var placeholder: ((Progress) -> AnyView)? = nil + + let onFailureDelegate = Delegate() + let onSuccessDelegate = Delegate() + let onProgressDelegate = Delegate<(Int64, Int64), Void>() + + init(source: Source?) { + self.source = source + } + + func shouldApplyFade(cacheType: CacheType) -> Bool { + options.forceTransition || cacheType == .none + } + + func fadeTransitionDuration(cacheType: CacheType) -> TimeInterval? { + shouldApplyFade(cacheType: cacheType) + ? options.transition.fadeDuration + : nil + } + } +} + +extension ImageTransition { + // Only for fade effect in SwiftUI. + fileprivate var fadeDuration: TimeInterval? { + switch self { + case .fade(let duration): + return duration + default: + return nil + } + } +} + + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage.Context: Hashable { + public static func == (lhs: KFImage.Context, rhs: KFImage.Context) -> Bool { + lhs.source == rhs.source && + lhs.options.processor.identifier == rhs.options.processor.identifier + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(source) + hasher.combine(options.processor.identifier) + } +} + +#if canImport(UIKit) && !os(watchOS) +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFAnimatedImage { + public typealias Context = KFImage.Context + typealias ImageBinder = KFImage.ImageBinder +} +#endif + +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift b/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift new file mode 100644 index 0000000..071da58 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFAnimatedImage.swift @@ -0,0 +1,97 @@ +// +// KFAnimatedImage.swift +// Kingfisher +// +// Created by wangxingbin on 2021/4/29. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) && canImport(UIKit) && !os(watchOS) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFAnimatedImage: KFImageProtocol { + public typealias HoldingView = KFAnimatedImageViewRepresenter + public var context: Context + public init(context: KFImage.Context) { + self.context = context + } + + /// Configures current rendering view with a `block`. This block will be applied when the under-hood + /// `AnimatedImageView` is created in `UIViewRepresentable.makeUIView(context:)` + /// + /// - Parameter block: The block applies to the animated image view. + /// - Returns: A `KFAnimatedImage` view that being configured by the `block`. + public func configure(_ block: @escaping (HoldingView.RenderingView) -> Void) -> Self { + context.renderConfigurations.append(block) + return self + } +} + +/// A wrapped `UIViewRepresentable` of `AnimatedImageView` +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFAnimatedImageViewRepresenter: UIViewRepresentable, KFImageHoldingView { + public typealias RenderingView = AnimatedImageView + public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> KFAnimatedImageViewRepresenter { + KFAnimatedImageViewRepresenter(image: image, context: context) + } + + var image: KFCrossPlatformImage? + let context: KFImage.Context + + public func makeUIView(context: Context) -> AnimatedImageView { + let view = AnimatedImageView() + + self.context.renderConfigurations.forEach { $0(view) } + + view.image = image + + // Allow SwiftUI scale (fit/fill) working fine. + view.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + view.setContentCompressionResistancePriority(.defaultLow, for: .vertical) + return view + } + + public func updateUIView(_ uiView: AnimatedImageView, context: Context) { + uiView.image = image + } + +} + +#if DEBUG +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFAnimatedImage_Previews : PreviewProvider { + static var previews: some View { + Group { + KFAnimatedImage(source: .network(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher-TestImages/master/DemoAppImage/GIF/1.gif")!)) + .onSuccess { r in + print(r) + } + .placeholder { + ProgressView() + } + .padding() + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift new file mode 100644 index 0000000..04931be --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImage.swift @@ -0,0 +1,106 @@ +// +// KFImage.swift +// Kingfisher +// +// Created by onevcat on 2019/06/26. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public struct KFImage: KFImageProtocol { + public var context: Context + public init(context: Context) { + self.context = context + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension Image: KFImageHoldingView { + public typealias RenderingView = Image + public static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> Image { + Image(crossPlatformImage: image) + } +} + +// MARK: - Image compatibility. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImage { + + public func resizable( + capInsets: EdgeInsets = EdgeInsets(), + resizingMode: Image.ResizingMode = .stretch) -> KFImage + { + configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) } + } + + public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage { + configure { $0.renderingMode(renderingMode) } + } + + public func interpolation(_ interpolation: Image.Interpolation) -> KFImage { + configure { $0.interpolation(interpolation) } + } + + public func antialiased(_ isAntialiased: Bool) -> KFImage { + configure { $0.antialiased(isAntialiased) } + } + + /// Starts the loading process of `self` immediately. + /// + /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading + /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a + /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once + /// could help avoiding the flickering, with some performance trade-off. + /// + /// - Deprecated: This is not necessary anymore since `@StateObject` is used for holding the image data. + /// It does nothing now and please just remove it. + /// + /// - Returns: The `Self` value with changes applied. + @available(*, deprecated, message: "This is not necessary anymore since `@StateObject` is used. It does nothing now and please just remove it.") + public func loadImmediately(_ start: Bool = true) -> KFImage { + return self + } +} + +#if DEBUG +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFImage_Previews : PreviewProvider { + static var previews: some View { + Group { + KFImage.url(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!) + .onSuccess { r in + print(r) + } + .placeholder { p in + ProgressView(p) + } + .resizable() + .aspectRatio(contentMode: .fit) + .padding() + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift new file mode 100644 index 0000000..e553b2a --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageOptions.swift @@ -0,0 +1,138 @@ +// +// KFImageOptions.swift +// Kingfisher +// +// Created by onevcat on 2020/12/20. +// +// Copyright (c) 2020 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +// MARK: - KFImage creating. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + + /// Creates a `KFImage` for a given `Source`. + /// - Parameters: + /// - source: The `Source` object defines data information from network or a data provider. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func source( + _ source: Source? + ) -> Self + { + Self.init(source: source) + } + + /// Creates a `KFImage` for a given `Resource`. + /// - Parameters: + /// - source: The `Resource` object defines data information like key or URL. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func resource( + _ resource: Resource? + ) -> Self + { + source(resource?.convertToSource()) + } + + /// Creates a `KFImage` for a given `URL`. + /// - Parameters: + /// - url: The URL where the image should be downloaded. + /// - cacheKey: The key used to store the downloaded image in cache. + /// If `nil`, the `absoluteString` of `url` is used as the cache key. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func url( + _ url: URL?, cacheKey: String? = nil + ) -> Self + { + source(url?.convertToSource(overrideCacheKey: cacheKey)) + } + + /// Creates a `KFImage` for a given `ImageDataProvider`. + /// - Parameters: + /// - provider: The `ImageDataProvider` object contains information about the data. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func dataProvider( + _ provider: ImageDataProvider? + ) -> Self + { + source(provider?.convertToSource()) + } + + /// Creates a builder for some given raw data and a cache key. + /// - Parameters: + /// - data: The data object from which the image should be created. + /// - cacheKey: The key used to store the downloaded image in cache. + /// - Returns: A `KFImage` for future configuration or embedding to a `SwiftUI.View`. + public static func data( + _ data: Data?, cacheKey: String + ) -> Self + { + if let data = data { + return dataProvider(RawImageDataProvider(data: data, cacheKey: cacheKey)) + } else { + return dataProvider(nil) + } + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + /// Sets a placeholder `View` which shows when loading the image, with a progress parameter as input. + /// - Parameter content: A view that describes the placeholder. + /// - Returns: A `KFImage` view that contains `content` as its placeholder. + public func placeholder(@ViewBuilder _ content: @escaping (Progress) -> P) -> Self { + context.placeholder = { progress in + return AnyView(content(progress)) + } + return self + } + + /// Sets a placeholder `View` which shows when loading the image. + /// - Parameter content: A view that describes the placeholder. + /// - Returns: A `KFImage` view that contains `content` as its placeholder. + public func placeholder(@ViewBuilder _ content: @escaping () -> P) -> Self { + placeholder { _ in content() } + } + + /// Sets cancelling the download task bound to `self` when the view disappearing. + /// - Parameter flag: Whether cancel the task or not. + /// - Returns: A `KFImage` view that cancels downloading task when disappears. + public func cancelOnDisappear(_ flag: Bool) -> Self { + context.cancelOnDisappear = flag + return self + } + + /// Sets a fade transition for the image task. + /// - Parameter duration: The duration of the fade transition. + /// - Returns: A `KFImage` with changes applied. + /// + /// Kingfisher will use the fade transition to animate the image in if it is downloaded from web. + /// The transition will not happen when the + /// image is retrieved from either memory or disk cache by default. If you need to do the transition even when + /// the image being retrieved from cache, also call `forceRefresh()` on the returned `KFImage`. + public func fade(duration: TimeInterval) -> Self { + context.options.transition = .fade(duration) + return self + } +} +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift new file mode 100644 index 0000000..4eca452 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageProtocol.swift @@ -0,0 +1,93 @@ +// +// KFImageProtocol.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public protocol KFImageProtocol: View, KFOptionSetter { + associatedtype HoldingView: KFImageHoldingView + var context: KFImage.Context { get set } + init(context: KFImage.Context) +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + public var body: some View { + ZStack { + KFImageRenderer( + context: context + ).id(context) + } + } + + /// Creates a Kingfisher compatible image view to load image from the given `Source`. + /// - Parameters: + /// - source: The image `Source` defining where to load the target image. + public init(source: Source?) { + let context = KFImage.Context(source: source) + self.init(context: context) + } + + /// Creates a Kingfisher compatible image view to load image from the given `URL`. + /// - Parameters: + /// - source: The image `Source` defining where to load the target image. + public init(_ url: URL?) { + self.init(source: url?.convertToSource()) + } + + /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`. + /// - Parameter block: The block applies to loaded image. + /// - Returns: A `KFImage` view that configures internal `Image` with `block`. + public func configure(_ block: @escaping (HoldingView) -> HoldingView) -> Self { + context.configurations.append(block) + return self + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +public protocol KFImageHoldingView: View { + associatedtype RenderingView + static func created(from image: KFCrossPlatformImage?, context: KFImage.Context) -> Self +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension KFImageProtocol { + public var options: KingfisherParsedOptionsInfo { + get { context.options } + nonmutating set { context.options = newValue } + } + + public var onFailureDelegate: Delegate { context.onFailureDelegate } + public var onSuccessDelegate: Delegate { context.onSuccessDelegate } + public var onProgressDelegate: Delegate<(Int64, Int64), Void> { context.onProgressDelegate } + + public var delegateObserver: AnyObject { context } +} + + +#endif diff --git a/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift b/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift new file mode 100644 index 0000000..90e6846 --- /dev/null +++ b/Pods/Kingfisher/Sources/SwiftUI/KFImageRenderer.swift @@ -0,0 +1,105 @@ +// +// KFImageRenderer.swift +// Kingfisher +// +// Created by onevcat on 2021/05/08. +// +// Copyright (c) 2021 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if canImport(SwiftUI) && canImport(Combine) +import SwiftUI +import Combine + +/// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`. +/// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`. +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +struct KFImageRenderer : View where HoldingView: KFImageHoldingView { + + @StateObject var binder: KFImage.ImageBinder = .init() + let context: KFImage.Context + + var body: some View { + ZStack { + context.configurations + .reduce(HoldingView.created(from: binder.loadedImage, context: context)) { + current, config in config(current) + } + .opacity(binder.loaded ? 1.0 : 0.0) + if binder.loadedImage == nil { + Group { + if let placeholder = context.placeholder, let view = placeholder(binder.progress) { + view + } else { + Color.clear + } + } + .onAppear { [weak binder = self.binder] in + guard let binder = binder else { + return + } + if !binder.loadingOrSucceeded { + binder.start(context: context) + } + } + .onDisappear { [weak binder = self.binder] in + guard let binder = binder else { + return + } + if context.cancelOnDisappear { + binder.cancel() + } + } + } + } + } +} + +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension Image { + // Creates an Image with either UIImage or NSImage. + init(crossPlatformImage: KFCrossPlatformImage?) { + #if canImport(UIKit) + self.init(uiImage: crossPlatformImage ?? KFCrossPlatformImage()) + #elseif canImport(AppKit) + self.init(nsImage: crossPlatformImage ?? KFCrossPlatformImage()) + #endif + } +} + +#if canImport(UIKit) +@available(iOS 14.0, macOS 11.0, tvOS 14.0, watchOS 7.0, *) +extension UIImage.Orientation { + func toSwiftUI() -> Image.Orientation { + switch self { + case .down: return .down + case .up: return .up + case .left: return .left + case .right: return .right + case .upMirrored: return .upMirrored + case .downMirrored: return .downMirrored + case .leftMirrored: return .leftMirrored + case .rightMirrored: return .rightMirrored + @unknown default: return .up + } + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/Utility/Box.swift b/Pods/Kingfisher/Sources/Utility/Box.swift new file mode 100644 index 0000000..0303a6e --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Box.swift @@ -0,0 +1,34 @@ +// +// Box.swift +// Kingfisher +// +// Created by Wei Wang on 2018/3/17. +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +class Box { + var value: T + + init(_ value: T) { + self.value = value + } +} diff --git a/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift b/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift new file mode 100644 index 0000000..822af28 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/CallbackQueue.swift @@ -0,0 +1,83 @@ +// +// CallbackQueue.swift +// Kingfisher +// +// Created by onevcat on 2018/10/15. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +public typealias ExecutionQueue = CallbackQueue + +/// Represents callback queue behaviors when an calling of closure be dispatched. +/// +/// - asyncMain: Dispatch the calling to `DispatchQueue.main` with an `async` behavior. +/// - currentMainOrAsync: Dispatch the calling to `DispatchQueue.main` with an `async` behavior if current queue is not +/// `.main`. Otherwise, call the closure immediately in current main queue. +/// - untouch: Do not change the calling queue for closure. +/// - dispatch: Dispatches to a specified `DispatchQueue`. +public enum CallbackQueue { + /// Dispatch the calling to `DispatchQueue.main` with an `async` behavior. + case mainAsync + /// Dispatch the calling to `DispatchQueue.main` with an `async` behavior if current queue is not + /// `.main`. Otherwise, call the closure immediately in current main queue. + case mainCurrentOrAsync + /// Do not change the calling queue for closure. + case untouch + /// Dispatches to a specified `DispatchQueue`. + case dispatch(DispatchQueue) + + public func execute(_ block: @escaping () -> Void) { + switch self { + case .mainAsync: + DispatchQueue.main.async { block() } + case .mainCurrentOrAsync: + DispatchQueue.main.safeAsync { block() } + case .untouch: + block() + case .dispatch(let queue): + queue.async { block() } + } + } + + var queue: DispatchQueue { + switch self { + case .mainAsync: return .main + case .mainCurrentOrAsync: return .main + case .untouch: return OperationQueue.current?.underlyingQueue ?? .main + case .dispatch(let queue): return queue + } + } +} + +extension DispatchQueue { + // This method will dispatch the `block` to self. + // If `self` is the main queue, and current thread is main thread, the block + // will be invoked immediately instead of being dispatched. + func safeAsync(_ block: @escaping () -> Void) { + if self === DispatchQueue.main && Thread.isMainThread { + block() + } else { + async { block() } + } + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Delegate.swift b/Pods/Kingfisher/Sources/Utility/Delegate.swift new file mode 100644 index 0000000..9caa1a6 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Delegate.swift @@ -0,0 +1,132 @@ +// +// Delegate.swift +// Kingfisher +// +// Created by onevcat on 2018/10/10. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +/// A class that keeps a weakly reference for `self` when implementing `onXXX` behaviors. +/// Instead of remembering to keep `self` as weak in a stored closure: +/// +/// ```swift +/// // MyClass.swift +/// var onDone: (() -> Void)? +/// func done() { +/// onDone?() +/// } +/// +/// // ViewController.swift +/// var obj: MyClass? +/// +/// func doSomething() { +/// obj = MyClass() +/// obj!.onDone = { [weak self] in +/// self?.reportDone() +/// } +/// } +/// ``` +/// +/// You can create a `Delegate` and observe on `self`. Now, there is no retain cycle inside: +/// +/// ```swift +/// // MyClass.swift +/// let onDone = Delegate<(), Void>() +/// func done() { +/// onDone.call() +/// } +/// +/// // ViewController.swift +/// var obj: MyClass? +/// +/// func doSomething() { +/// obj = MyClass() +/// obj!.onDone.delegate(on: self) { (self, _) +/// // `self` here is shadowed and does not keep a strong ref. +/// // So you can release both `MyClass` instance and `ViewController` instance. +/// self.reportDone() +/// } +/// } +/// ``` +/// +public class Delegate { + public init() {} + + private var block: ((Input) -> Output?)? + public func delegate(on target: T, block: ((T, Input) -> Output)?) { + self.block = { [weak target] input in + guard let target = target else { return nil } + return block?(target, input) + } + } + + public func call(_ input: Input) -> Output? { + return block?(input) + } + + public func callAsFunction(_ input: Input) -> Output? { + return call(input) + } +} + +extension Delegate where Input == Void { + public func call() -> Output? { + return call(()) + } + + public func callAsFunction() -> Output? { + return call() + } +} + +extension Delegate where Input == Void, Output: OptionalProtocol { + public func call() -> Output { + return call(()) + } + + public func callAsFunction() -> Output { + return call() + } +} + +extension Delegate where Output: OptionalProtocol { + public func call(_ input: Input) -> Output { + if let result = block?(input) { + return result + } else { + return Output._createNil + } + } + + public func callAsFunction(_ input: Input) -> Output { + return call(input) + } +} + +public protocol OptionalProtocol { + static var _createNil: Self { get } +} +extension Optional : OptionalProtocol { + public static var _createNil: Optional { + return nil + } +} diff --git a/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift b/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift new file mode 100644 index 0000000..f1e1e8b --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/ExtensionHelpers.swift @@ -0,0 +1,125 @@ +// +// ExtensionHelpers.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +extension CGFloat { + var isEven: Bool { + return truncatingRemainder(dividingBy: 2.0) == 0 + } +} + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +extension NSBezierPath { + convenience init(roundedRect rect: NSRect, topLeftRadius: CGFloat, topRightRadius: CGFloat, + bottomLeftRadius: CGFloat, bottomRightRadius: CGFloat) + { + self.init() + + let maxCorner = min(rect.width, rect.height) / 2 + + let radiusTopLeft = min(maxCorner, max(0, topLeftRadius)) + let radiusTopRight = min(maxCorner, max(0, topRightRadius)) + let radiusBottomLeft = min(maxCorner, max(0, bottomLeftRadius)) + let radiusBottomRight = min(maxCorner, max(0, bottomRightRadius)) + + guard !rect.isEmpty else { + return + } + + let topLeft = NSPoint(x: rect.minX, y: rect.maxY) + let topRight = NSPoint(x: rect.maxX, y: rect.maxY) + let bottomRight = NSPoint(x: rect.maxX, y: rect.minY) + + move(to: NSPoint(x: rect.midX, y: rect.maxY)) + appendArc(from: topLeft, to: rect.origin, radius: radiusTopLeft) + appendArc(from: rect.origin, to: bottomRight, radius: radiusBottomLeft) + appendArc(from: bottomRight, to: topRight, radius: radiusBottomRight) + appendArc(from: topRight, to: topLeft, radius: radiusTopRight) + close() + } + + convenience init(roundedRect rect: NSRect, byRoundingCorners corners: RectCorner, radius: CGFloat) { + let radiusTopLeft = corners.contains(.topLeft) ? radius : 0 + let radiusTopRight = corners.contains(.topRight) ? radius : 0 + let radiusBottomLeft = corners.contains(.bottomLeft) ? radius : 0 + let radiusBottomRight = corners.contains(.bottomRight) ? radius : 0 + + self.init(roundedRect: rect, topLeftRadius: radiusTopLeft, topRightRadius: radiusTopRight, + bottomLeftRadius: radiusBottomLeft, bottomRightRadius: radiusBottomRight) + } +} + +extension KFCrossPlatformImage { + // macOS does not support scale. This is just for code compatibility across platforms. + convenience init?(data: Data, scale: CGFloat) { + self.init(data: data) + } +} +#endif + +#if canImport(UIKit) +import UIKit +extension RectCorner { + var uiRectCorner: UIRectCorner { + + var result: UIRectCorner = [] + + if contains(.topLeft) { result.insert(.topLeft) } + if contains(.topRight) { result.insert(.topRight) } + if contains(.bottomLeft) { result.insert(.bottomLeft) } + if contains(.bottomRight) { result.insert(.bottomRight) } + + return result + } +} +#endif + +extension Date { + var isPast: Bool { + return isPast(referenceDate: Date()) + } + + var isFuture: Bool { + return !isPast + } + + func isPast(referenceDate: Date) -> Bool { + return timeIntervalSince(referenceDate) <= 0 + } + + func isFuture(referenceDate: Date) -> Bool { + return !isPast(referenceDate: referenceDate) + } + + // `Date` in memory is a wrap for `TimeInterval`. But in file attribute it can only accept `Int` number. + // By default the system will `round` it. But it is not friendly for testing purpose. + // So we always `ceil` the value when used for file attributes. + var fileAttributeDate: Date { + return Date(timeIntervalSince1970: ceil(timeIntervalSince1970)) + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Result.swift b/Pods/Kingfisher/Sources/Utility/Result.swift new file mode 100644 index 0000000..b06500d --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Result.swift @@ -0,0 +1,71 @@ +// +// Result.swift +// Kingfisher +// +// Created by onevcat on 2018/09/22. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +// These helper methods are not public since we do not want them to be exposed or cause any conflicting. +// However, they are just wrapper of `ResultUtil` static methods. +extension Result where Failure: Error { + + /// Evaluates the given transform closures to create a single output value. + /// + /// - Parameters: + /// - onSuccess: A closure that transforms the success value. + /// - onFailure: A closure that transforms the error value. + /// - Returns: A single `Output` value. + func match( + onSuccess: (Success) -> Output, + onFailure: (Failure) -> Output) -> Output + { + switch self { + case let .success(value): + return onSuccess(value) + case let .failure(error): + return onFailure(error) + } + } + + func matchSuccess(with folder: (Success?) -> Output) -> Output { + return match( + onSuccess: { value in return folder(value) }, + onFailure: { _ in return folder(nil) } + ) + } + + func matchFailure(with folder: (Error?) -> Output) -> Output { + return match( + onSuccess: { _ in return folder(nil) }, + onFailure: { error in return folder(error) } + ) + } + + func match(with folder: (Success?, Error?) -> Output) -> Output { + return match( + onSuccess: { return folder($0, nil) }, + onFailure: { return folder(nil, $0) } + ) + } +} diff --git a/Pods/Kingfisher/Sources/Utility/Runtime.swift b/Pods/Kingfisher/Sources/Utility/Runtime.swift new file mode 100644 index 0000000..d5818e2 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/Runtime.swift @@ -0,0 +1,35 @@ +// +// Runtime.swift +// Kingfisher +// +// Created by Wei Wang on 2018/10/12. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation + +func getAssociatedObject(_ object: Any, _ key: UnsafeRawPointer) -> T? { + return objc_getAssociatedObject(object, key) as? T +} + +func setRetainedAssociatedObject(_ object: Any, _ key: UnsafeRawPointer, _ value: T) { + objc_setAssociatedObject(object, key, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) +} diff --git a/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift b/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift new file mode 100644 index 0000000..19d05d6 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/SizeExtensions.swift @@ -0,0 +1,110 @@ +// +// SizeExtensions.swift +// Kingfisher +// +// Created by onevcat on 2018/09/28. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import CoreGraphics + +extension CGSize: KingfisherCompatibleValue {} +extension KingfisherWrapper where Base == CGSize { + + /// Returns a size by resizing the `base` size to a target size under a given content mode. + /// + /// - Parameters: + /// - size: The target size to resize to. + /// - contentMode: Content mode of the target size should be when resizing. + /// - Returns: The resized size under the given `ContentMode`. + public func resize(to size: CGSize, for contentMode: ContentMode) -> CGSize { + switch contentMode { + case .aspectFit: + return constrained(size) + case .aspectFill: + return filling(size) + case .none: + return size + } + } + + /// Returns a size by resizing the `base` size by making it aspect fitting the given `size`. + /// + /// - Parameter size: The size in which the `base` should fit in. + /// - Returns: The size fitted in by the input `size`, while keeps `base` aspect. + public func constrained(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth > size.width ? + CGSize(width: size.width, height: aspectHeight) : + CGSize(width: aspectWidth, height: size.height) + } + + /// Returns a size by resizing the `base` size by making it aspect filling the given `size`. + /// + /// - Parameter size: The size in which the `base` should fill. + /// - Returns: The size be filled by the input `size`, while keeps `base` aspect. + public func filling(_ size: CGSize) -> CGSize { + let aspectWidth = round(aspectRatio * size.height) + let aspectHeight = round(size.width / aspectRatio) + + return aspectWidth < size.width ? + CGSize(width: size.width, height: aspectHeight) : + CGSize(width: aspectWidth, height: size.height) + } + + /// Returns a `CGRect` for which the `base` size is constrained to an input `size` at a given `anchor` point. + /// + /// - Parameters: + /// - size: The size in which the `base` should be constrained to. + /// - anchor: An anchor point in which the size constraint should happen. + /// - Returns: The result `CGRect` for the constraint operation. + public func constrainedRect(for size: CGSize, anchor: CGPoint) -> CGRect { + + let unifiedAnchor = CGPoint(x: anchor.x.clamped(to: 0.0...1.0), + y: anchor.y.clamped(to: 0.0...1.0)) + + let x = unifiedAnchor.x * base.width - unifiedAnchor.x * size.width + let y = unifiedAnchor.y * base.height - unifiedAnchor.y * size.height + let r = CGRect(x: x, y: y, width: size.width, height: size.height) + + let ori = CGRect(origin: .zero, size: base) + return ori.intersection(r) + } + + private var aspectRatio: CGFloat { + return base.height == 0.0 ? 1.0 : base.width / base.height + } +} + +extension CGRect { + func scaled(_ scale: CGFloat) -> CGRect { + return CGRect(x: origin.x * scale, y: origin.y * scale, + width: size.width * scale, height: size.height * scale) + } +} + +extension Comparable { + func clamped(to limits: ClosedRange) -> Self { + return min(max(self, limits.lowerBound), limits.upperBound) + } +} diff --git a/Pods/Kingfisher/Sources/Utility/String+MD5.swift b/Pods/Kingfisher/Sources/Utility/String+MD5.swift new file mode 100644 index 0000000..e4cad36 --- /dev/null +++ b/Pods/Kingfisher/Sources/Utility/String+MD5.swift @@ -0,0 +1,292 @@ +// +// String+MD5.swift +// Kingfisher +// +// Created by Wei Wang on 18/09/25. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +import Foundation +import CommonCrypto + +extension String: KingfisherCompatibleValue { } +extension KingfisherWrapper where Base == String { + var md5: String { + guard let data = base.data(using: .utf8) else { + return base + } + + let message = data.withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in + return [UInt8](bytes) + } + + let MD5Calculator = MD5(message) + let MD5Data = MD5Calculator.calculate() + + var MD5String = String() + for c in MD5Data { + MD5String += String(format: "%02x", c) + } + return MD5String + } + + var ext: String? { + var ext = "" + if let index = base.lastIndex(of: ".") { + let extRange = base.index(index, offsetBy: 1).. 0 ? String(firstSeg) : nil + } +} + +// array of bytes, little-endian representation +func arrayOfBytes(_ value: T, length: Int? = nil) -> [UInt8] { + let totalBytes = length ?? (MemoryLayout.size * 8) + + let valuePointer = UnsafeMutablePointer.allocate(capacity: 1) + valuePointer.pointee = value + + let bytes = valuePointer.withMemoryRebound(to: UInt8.self, capacity: totalBytes) { (bytesPointer) -> [UInt8] in + var bytes = [UInt8](repeating: 0, count: totalBytes) + for j in 0...size, totalBytes) { + bytes[totalBytes - 1 - j] = (bytesPointer + j).pointee + } + return bytes + } + + valuePointer.deinitialize(count: 1) + valuePointer.deallocate() + + return bytes +} + +extension Int { + // Array of bytes with optional padding (little-endian) + func bytes(_ totalBytes: Int = MemoryLayout.size) -> [UInt8] { + return arrayOfBytes(self, length: totalBytes) + } + +} + +extension NSMutableData { + + // Convenient way to append bytes + func appendBytes(_ arrayOfBytes: [UInt8]) { + append(arrayOfBytes, length: arrayOfBytes.count) + } + +} + +protocol HashProtocol { + var message: [UInt8] { get } + // Common part for hash calculation. Prepare header data. + func prepare(_ len: Int) -> [UInt8] +} + +extension HashProtocol { + + func prepare(_ len: Int) -> [UInt8] { + var tmpMessage = message + + // Step 1. Append Padding Bits + tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message + + // append "0" bit until message length in bits ≡ 448 (mod 512) + var msgLength = tmpMessage.count + var counter = 0 + + while msgLength % len != (len - 8) { + counter += 1 + msgLength += 1 + } + + tmpMessage += [UInt8](repeating: 0, count: counter) + return tmpMessage + } +} + +func toUInt32Array(_ slice: ArraySlice) -> [UInt32] { + var result = [UInt32]() + result.reserveCapacity(16) + + for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout.size) { + let d0 = UInt32(slice[idx.advanced(by: 3)]) << 24 + let d1 = UInt32(slice[idx.advanced(by: 2)]) << 16 + let d2 = UInt32(slice[idx.advanced(by: 1)]) << 8 + let d3 = UInt32(slice[idx]) + let val: UInt32 = d0 | d1 | d2 | d3 + + result.append(val) + } + return result +} + +struct BytesIterator: IteratorProtocol { + + let chunkSize: Int + let data: [UInt8] + + init(chunkSize: Int, data: [UInt8]) { + self.chunkSize = chunkSize + self.data = data + } + + var offset = 0 + + mutating func next() -> ArraySlice? { + let end = min(chunkSize, data.count - offset) + let result = data[offset.. 0 ? result : nil + } +} + +struct BytesSequence: Sequence { + let chunkSize: Int + let data: [UInt8] + + func makeIterator() -> BytesIterator { + return BytesIterator(chunkSize: chunkSize, data: data) + } +} + +func rotateLeft(_ value: UInt32, bits: UInt32) -> UInt32 { + return ((value << bits) & 0xFFFFFFFF) | (value >> (32 - bits)) +} + +class MD5: HashProtocol { + + static let size = 16 // 128 / 8 + let message: [UInt8] + + init (_ message: [UInt8]) { + self.message = message + } + + // specifies the per-round shift amounts + private let shifts: [UInt32] = [7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21] + + // binary integer part of the sines of integers (Radians) + private let sines: [UInt32] = [0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391] + + private let hashes: [UInt32] = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] + + func calculate() -> [UInt8] { + var tmpMessage = prepare(64) + tmpMessage.reserveCapacity(tmpMessage.count + 4) + + // hash values + var hh = hashes + + // Step 2. Append Length a 64-bit representation of lengthInBits + let lengthInBits = (message.count * 8) + let lengthBytes = lengthInBits.bytes(64 / 8) + tmpMessage += lengthBytes.reversed() + + // Process the message in successive 512-bit chunks: + let chunkSizeBytes = 512 / 8 // 64 + + for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) { + // break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 + let M = toUInt32Array(chunk) + assert(M.count == 16, "Invalid array") + + // Initialize hash value for this chunk: + var A: UInt32 = hh[0] + var B: UInt32 = hh[1] + var C: UInt32 = hh[2] + var D: UInt32 = hh[3] + + var dTemp: UInt32 = 0 + + // Main loop + for j in 0 ..< sines.count { + var g = 0 + var F: UInt32 = 0 + + switch j { + case 0...15: + F = (B & C) | ((~B) & D) + g = j + break + case 16...31: + F = (D & B) | (~D & C) + g = (5 * j + 1) % 16 + break + case 32...47: + F = B ^ C ^ D + g = (3 * j + 5) % 16 + break + case 48...63: + F = C ^ (B | (~D)) + g = (7 * j) % 16 + break + default: + break + } + dTemp = D + D = C + C = B + B = B &+ rotateLeft((A &+ F &+ sines[j] &+ M[g]), bits: shifts[j]) + A = dTemp + } + + hh[0] = hh[0] &+ A + hh[1] = hh[1] &+ B + hh[2] = hh[2] &+ C + hh[3] = hh[3] &+ D + } + var result = [UInt8]() + result.reserveCapacity(hh.count / 4) + + hh.forEach { + let itemLE = $0.littleEndian + let r1 = UInt8(itemLE & 0xff) + let r2 = UInt8((itemLE >> 8) & 0xff) + let r3 = UInt8((itemLE >> 16) & 0xff) + let r4 = UInt8((itemLE >> 24) & 0xff) + result += [r1, r2, r3, r4] + } + return result + } +} diff --git a/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift b/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift new file mode 100644 index 0000000..e1bc38d --- /dev/null +++ b/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift @@ -0,0 +1,659 @@ +// +// AnimatableImageView.swift +// Kingfisher +// +// Created by bl4ckra1sond3tre on 4/22/16. +// +// The AnimatableImageView, AnimatedFrame and Animator is a modified version of +// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu) +// +// The MIT License (MIT) +// +// Copyright (c) 2019 Reda Lemeden. +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +// +// The name and characters used in the demo of this software are property of their +// respective owners. + +#if !os(watchOS) +#if canImport(UIKit) +import UIKit +import ImageIO + +/// Protocol of `AnimatedImageView`. +public protocol AnimatedImageViewDelegate: AnyObject { + + /// Called after the animatedImageView has finished each animation loop. + /// + /// - Parameters: + /// - imageView: The `AnimatedImageView` that is being animated. + /// - count: The looped count. + func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) + + /// Called after the `AnimatedImageView` has reached the max repeat count. + /// + /// - Parameter imageView: The `AnimatedImageView` that is being animated. + func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) +} + +extension AnimatedImageViewDelegate { + public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {} + public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {} +} + +let KFRunLoopModeCommon = RunLoop.Mode.common + +/// Represents a subclass of `UIImageView` for displaying animated image. +/// Different from showing animated image in a normal `UIImageView` (which load all frames at one time), +/// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage. +/// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image +/// view to load GIF data, you could give this class a try. +/// +/// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So +/// it would be fairly easy to switch between them. +open class AnimatedImageView: UIImageView { + /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`. + class TargetProxy { + private weak var target: AnimatedImageView? + + init(target: AnimatedImageView) { + self.target = target + } + + @objc func onScreenUpdate() { + target?.updateFrameIfNeeded() + } + } + + /// Enumeration that specifies repeat count of GIF + public enum RepeatCount: Equatable { + case once + case finite(count: UInt) + case infinite + + public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool { + switch (lhs, rhs) { + case let (.finite(l), .finite(r)): + return l == r + case (.once, .once), + (.infinite, .infinite): + return true + case (.once, .finite(let count)), + (.finite(let count), .once): + return count == 1 + case (.once, _), + (.infinite, _), + (.finite, _): + return false + } + } + } + + // MARK: - Public property + /// Whether automatically play the animation when the view become visible. Default is `true`. + public var autoPlayAnimatedImage = true + + /// The count of the frames should be preloaded before shown. + public var framePreloadCount = 10 + + /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not. + /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use. + /// Default is `true`. + public var needsPrescaling = true + + /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen + /// rendering to extract pixel information in background. This can reduce the main thread CPU usage. + public var backgroundDecode = true + + /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`. + /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling. + public var runLoopMode = KFRunLoopModeCommon { + willSet { + guard runLoopMode != newValue else { return } + stopAnimating() + displayLink.remove(from: .main, forMode: runLoopMode) + displayLink.add(to: .main, forMode: newValue) + startAnimating() + } + } + + /// The repeat count. The animated image will keep animate until it the loop count reaches this value. + /// Setting this value to another one will reset current animation. + /// + /// Default is `.infinite`, which means the animation will last forever. + public var repeatCount = RepeatCount.infinite { + didSet { + if oldValue != repeatCount { + reset() + setNeedsDisplay() + layer.setNeedsDisplay() + } + } + } + + /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more. + public weak var delegate: AnimatedImageViewDelegate? + + /// The `Animator` instance that holds the frames of a specific image in memory. + public private(set) var animator: Animator? + + // MARK: - Private property + // Dispatch queue used for preloading images. + private lazy var preloadQueue: DispatchQueue = { + return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") + }() + + // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. + private var isDisplayLinkInitialized: Bool = false + + // A display link that keeps calling the `updateFrame` method on every screen refresh. + private lazy var displayLink: CADisplayLink = { + isDisplayLinkInitialized = true + let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) + displayLink.add(to: .main, forMode: runLoopMode) + displayLink.isPaused = true + return displayLink + }() + + // MARK: - Override + override open var image: KFCrossPlatformImage? { + didSet { + if image != oldValue { + reset() + } + setNeedsDisplay() + layer.setNeedsDisplay() + } + } + + open override var isHighlighted: Bool { + get { + super.isHighlighted + } + set { + // Highlighted image is unsupported for animated images. + // See https://github.com/onevcat/Kingfisher/issues/1679 + if displayLink.isPaused { + super.isHighlighted = newValue + } + } + } + + deinit { + if isDisplayLinkInitialized { + displayLink.invalidate() + } + } + + override open var isAnimating: Bool { + if isDisplayLinkInitialized { + return !displayLink.isPaused + } else { + return super.isAnimating + } + } + + /// Starts the animation. + override open func startAnimating() { + guard !isAnimating else { return } + guard let animator = animator else { return } + guard !animator.isReachMaxRepeatCount else { return } + + displayLink.isPaused = false + } + + /// Stops the animation. + override open func stopAnimating() { + super.stopAnimating() + if isDisplayLinkInitialized { + displayLink.isPaused = true + } + } + + override open func display(_ layer: CALayer) { + layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage + } + + override open func didMoveToWindow() { + super.didMoveToWindow() + didMove() + } + + override open func didMoveToSuperview() { + super.didMoveToSuperview() + didMove() + } + + // This is for back compatibility that using regular `UIImageView` to show animated image. + override func shouldPreloadAllAnimation() -> Bool { + return false + } + + // Reset the animator. + private func reset() { + animator = nil + if let image = image, let imageSource = image.kf.imageSource { + let targetSize = bounds.scaled(UIScreen.main.scale).size + let animator = Animator( + imageSource: imageSource, + contentMode: contentMode, + size: targetSize, + imageSize: image.kf.size, + imageScale: image.kf.scale, + framePreloadCount: framePreloadCount, + repeatCount: repeatCount, + preloadQueue: preloadQueue) + animator.delegate = self + animator.needsPrescaling = needsPrescaling + animator.backgroundDecode = backgroundDecode + animator.prepareFramesAsynchronously() + self.animator = animator + } + didMove() + } + + private func didMove() { + if autoPlayAnimatedImage && animator != nil { + if let _ = superview, let _ = window { + startAnimating() + } else { + stopAnimating() + } + } + } + + /// Update the current frame with the displayLink duration. + private func updateFrameIfNeeded() { + guard let animator = animator else { + return + } + + guard !animator.isFinished else { + stopAnimating() + delegate?.animatedImageViewDidFinishAnimating(self) + return + } + + let duration: CFTimeInterval + + // CA based display link is opt-out from ProMotion by default. + // So the duration and its FPS might not match. + // See [#718](https://github.com/onevcat/Kingfisher/issues/718) + // By setting CADisableMinimumFrameDuration to YES in Info.plist may + // cause the preferredFramesPerSecond being 0 + let preferredFramesPerSecond = displayLink.preferredFramesPerSecond + if preferredFramesPerSecond == 0 { + duration = displayLink.duration + } else { + // Some devices (like iPad Pro 10.5) will have a different FPS. + duration = 1.0 / TimeInterval(preferredFramesPerSecond) + } + + animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in + if hasNewFrame { + self?.layer.setNeedsDisplay() + } + } + } +} + +protocol AnimatorDelegate: AnyObject { + func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt) +} + +extension AnimatedImageView: AnimatorDelegate { + func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) { + delegate?.animatedImageView(self, didPlayAnimationLoops: count) + } +} + +extension AnimatedImageView { + + // Represents a single frame in a GIF. + struct AnimatedFrame { + + // The image to display for this frame. Its value is nil when the frame is removed from the buffer. + let image: UIImage? + + // The duration that this frame should remain active. + let duration: TimeInterval + + // A placeholder frame with no image assigned. + // Used to replace frames that are no longer needed in the animation. + var placeholderFrame: AnimatedFrame { + return AnimatedFrame(image: nil, duration: duration) + } + + // Whether this frame instance contains an image or not. + var isPlaceholder: Bool { + return image == nil + } + + // Returns a new instance from an optional image. + // + // - parameter image: An optional `UIImage` instance to be assigned to the new frame. + // - returns: An `AnimatedFrame` instance. + func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame { + return AnimatedFrame(image: image, duration: duration) + } + } +} + +extension AnimatedImageView { + + // MARK: - Animator + + /// An animator which used to drive the data behind `AnimatedImageView`. + public class Animator { + private let size: CGSize + + private let imageSize: CGSize + private let imageScale: CGFloat + + /// The maximum count of image frames that needs preload. + public let maxFrameCount: Int + + private let imageSource: CGImageSource + private let maxRepeatCount: RepeatCount + + private let maxTimeStep: TimeInterval = 1.0 + private let animatedFrames = SafeArray() + private var frameCount = 0 + private var timeSinceLastFrameChange: TimeInterval = 0.0 + private var currentRepeatCount: UInt = 0 + + var isFinished: Bool = false + + var needsPrescaling = true + + var backgroundDecode = true + + weak var delegate: AnimatorDelegate? + + // Total duration of one animation loop + var loopDuration: TimeInterval = 0 + + /// The image of the current frame. + public var currentFrameImage: UIImage? { + return frame(at: currentFrameIndex) + } + + /// The duration of the current active frame duration. + public var currentFrameDuration: TimeInterval { + return duration(at: currentFrameIndex) + } + + /// The index of the current animation frame. + public internal(set) var currentFrameIndex = 0 { + didSet { + previousFrameIndex = oldValue + } + } + + var previousFrameIndex = 0 { + didSet { + preloadQueue.async { + self.updatePreloadedFrames() + } + } + } + + var isReachMaxRepeatCount: Bool { + switch maxRepeatCount { + case .once: + return currentRepeatCount >= 1 + case .finite(let maxCount): + return currentRepeatCount >= maxCount + case .infinite: + return false + } + } + + /// Whether the current frame is the last frame or not in the animation sequence. + public var isLastFrame: Bool { + return currentFrameIndex == frameCount - 1 + } + + var preloadingIsNeeded: Bool { + return maxFrameCount < frameCount - 1 + } + + var contentMode = UIView.ContentMode.scaleToFill + + private lazy var preloadQueue: DispatchQueue = { + return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue") + }() + + /// Creates an animator with image source reference. + /// + /// - Parameters: + /// - source: The reference of animated image. + /// - mode: Content mode of the `AnimatedImageView`. + /// - size: Size of the `AnimatedImageView`. + /// - imageSize: Size of the `KingfisherWrapper`. + /// - imageScale: Scale of the `KingfisherWrapper`. + /// - count: Count of frames needed to be preloaded. + /// - repeatCount: The repeat count should this animator uses. + /// - preloadQueue: Dispatch queue used for preloading images. + init(imageSource source: CGImageSource, + contentMode mode: UIView.ContentMode, + size: CGSize, + imageSize: CGSize, + imageScale: CGFloat, + framePreloadCount count: Int, + repeatCount: RepeatCount, + preloadQueue: DispatchQueue) { + self.imageSource = source + self.contentMode = mode + self.size = size + self.imageSize = imageSize + self.imageScale = imageScale + self.maxFrameCount = count + self.maxRepeatCount = repeatCount + self.preloadQueue = preloadQueue + + GraphicsContext.begin(size: imageSize, scale: imageScale) + } + + deinit { + GraphicsContext.end() + } + + /// Gets the image frame of a given index. + /// - Parameter index: The index of desired image. + /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded. + public func frame(at index: Int) -> KFCrossPlatformImage? { + return animatedFrames[index]?.image + } + + public func duration(at index: Int) -> TimeInterval { + return animatedFrames[index]?.duration ?? .infinity + } + + func prepareFramesAsynchronously() { + frameCount = Int(CGImageSourceGetCount(imageSource)) + animatedFrames.reserveCapacity(frameCount) + preloadQueue.async { [weak self] in + self?.setupAnimatedFrames() + } + } + + func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) { + incrementTimeSinceLastFrameChange(with: duration) + + if currentFrameDuration > timeSinceLastFrameChange { + handler(false) + } else { + resetTimeSinceLastFrameChange() + incrementCurrentFrameIndex() + handler(true) + } + } + + private func setupAnimatedFrames() { + resetAnimatedFrames() + + var duration: TimeInterval = 0 + + (0.. maxFrameCount { return } + animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index)) + } + + self.loopDuration = duration + } + + private func resetAnimatedFrames() { + animatedFrames.removeAll() + } + + private func loadFrame(at index: Int) -> UIImage? { + let resize = needsPrescaling && size != .zero + let options: [CFString: Any]? + if resize { + options = [ + kCGImageSourceCreateThumbnailFromImageIfAbsent: true, + kCGImageSourceCreateThumbnailWithTransform: true, + kCGImageSourceShouldCacheImmediately: true, + kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height) + ] + } else { + options = nil + } + + guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) else { + return nil + } + + let image = KFCrossPlatformImage(cgImage: cgImage) + + guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else { + return image + } + + return backgroundDecode ? image.kf.decoded(on: context) : image + } + + private func updatePreloadedFrames() { + guard preloadingIsNeeded else { + return + } + + animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame + + preloadIndexes(start: currentFrameIndex).forEach { index in + guard let currentAnimatedFrame = animatedFrames[index] else { return } + if !currentAnimatedFrame.isPlaceholder { return } + animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index)) + } + } + + private func incrementCurrentFrameIndex() { + let wasLastFrame = isLastFrame + currentFrameIndex = increment(frameIndex: currentFrameIndex) + if isLastFrame { + currentRepeatCount += 1 + if isReachMaxRepeatCount { + isFinished = true + + // Notify the delegate here because the animation is stopping. + delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) + } + } else if wasLastFrame { + + // Notify the delegate that the loop completed + delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount) + } + } + + private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) { + timeSinceLastFrameChange += min(maxTimeStep, duration) + } + + private func resetTimeSinceLastFrameChange() { + timeSinceLastFrameChange -= currentFrameDuration + } + + private func increment(frameIndex: Int, by value: Int = 1) -> Int { + return (frameIndex + value) % frameCount + } + + private func preloadIndexes(start index: Int) -> [Int] { + let nextIndex = increment(frameIndex: index) + let lastIndex = increment(frameIndex: index, by: maxFrameCount) + + if lastIndex >= nextIndex { + return [Int](nextIndex...lastIndex) + } else { + return [Int](nextIndex.. { + private var array: Array = [] + private let lock = NSLock() + + subscript(index: Int) -> Element? { + get { + lock.lock() + defer { lock.unlock() } + return array.indices ~= index ? array[index] : nil + } + + set { + lock.lock() + defer { lock.unlock() } + if let newValue = newValue, array.indices ~= index { + array[index] = newValue + } + } + } + + var count : Int { + lock.lock() + defer { lock.unlock() } + return array.count + } + + func reserveCapacity(_ count: Int) { + lock.lock() + defer { lock.unlock() } + array.reserveCapacity(count) + } + + func append(_ element: Element) { + lock.lock() + defer { lock.unlock() } + array += [element] + } + + func removeAll() { + lock.lock() + defer { lock.unlock() } + array = [] + } +} +#endif +#endif diff --git a/Pods/Kingfisher/Sources/Views/Indicator.swift b/Pods/Kingfisher/Sources/Views/Indicator.swift new file mode 100644 index 0000000..b1585b2 --- /dev/null +++ b/Pods/Kingfisher/Sources/Views/Indicator.swift @@ -0,0 +1,232 @@ +// +// Indicator.swift +// Kingfisher +// +// Created by João D. Moreira on 30/08/16. +// +// Copyright (c) 2019 Wei Wang +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#if !os(watchOS) + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +public typealias IndicatorView = NSView +#else +import UIKit +public typealias IndicatorView = UIView +#endif + +/// Represents the activity indicator type which should be added to +/// an image view when an image is being downloaded. +/// +/// - none: No indicator. +/// - activity: Uses the system activity indicator. +/// - image: Uses an image as indicator. GIF is supported. +/// - custom: Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. +public enum IndicatorType { + /// No indicator. + case none + /// Uses the system activity indicator. + case activity + /// Uses an image as indicator. GIF is supported. + case image(imageData: Data) + /// Uses a custom indicator. The type of associated value should conform to the `Indicator` protocol. + case custom(indicator: Indicator) +} + +/// An indicator type which can be used to show the download task is in progress. +public protocol Indicator { + + /// Called when the indicator should start animating. + func startAnimatingView() + + /// Called when the indicator should stop animating. + func stopAnimatingView() + + /// Center offset of the indicator. Kingfisher will use this value to determine the position of + /// indicator in the super view. + var centerOffset: CGPoint { get } + + /// The indicator view which would be added to the super view. + var view: IndicatorView { get } + + /// The size strategy used when adding the indicator to image view. + /// - Parameter imageView: The super view of indicator. + func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy +} + +public enum IndicatorSizeStrategy { + case intrinsicSize + case full + case size(CGSize) +} + +extension Indicator { + + /// Default implementation of `centerOffset` of `Indicator`. The default value is `.zero`, means that there is + /// no offset for the indicator view. + public var centerOffset: CGPoint { return .zero } + + + /// Default implementation of `centerOffset` of `Indicator`. The default value is `.full`, means that the indicator + /// will pin to the same height and width as the image view. + public func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy { + return .full + } +} + +// Displays a NSProgressIndicator / UIActivityIndicatorView +final class ActivityIndicator: Indicator { + + #if os(macOS) + private let activityIndicatorView: NSProgressIndicator + #else + private let activityIndicatorView: UIActivityIndicatorView + #endif + private var animatingCount = 0 + + var view: IndicatorView { + return activityIndicatorView + } + + func startAnimatingView() { + if animatingCount == 0 { + #if os(macOS) + activityIndicatorView.startAnimation(nil) + #else + activityIndicatorView.startAnimating() + #endif + activityIndicatorView.isHidden = false + } + animatingCount += 1 + } + + func stopAnimatingView() { + animatingCount = max(animatingCount - 1, 0) + if animatingCount == 0 { + #if os(macOS) + activityIndicatorView.stopAnimation(nil) + #else + activityIndicatorView.stopAnimating() + #endif + activityIndicatorView.isHidden = true + } + } + + func sizeStrategy(in imageView: KFCrossPlatformImageView) -> IndicatorSizeStrategy { + return .intrinsicSize + } + + init() { + #if os(macOS) + activityIndicatorView = NSProgressIndicator(frame: CGRect(x: 0, y: 0, width: 16, height: 16)) + activityIndicatorView.controlSize = .small + activityIndicatorView.style = .spinning + #else + let indicatorStyle: UIActivityIndicatorView.Style + + #if os(tvOS) + if #available(tvOS 13.0, *) { + indicatorStyle = UIActivityIndicatorView.Style.large + } else { + indicatorStyle = UIActivityIndicatorView.Style.white + } + #else + if #available(iOS 13.0, * ) { + indicatorStyle = UIActivityIndicatorView.Style.medium + } else { + indicatorStyle = UIActivityIndicatorView.Style.gray + } + #endif + + activityIndicatorView = UIActivityIndicatorView(style: indicatorStyle) + #endif + } +} + +#if canImport(UIKit) +extension UIActivityIndicatorView.Style { + #if compiler(>=5.1) + #else + static let large = UIActivityIndicatorView.Style.white + #if !os(tvOS) + static let medium = UIActivityIndicatorView.Style.gray + #endif + #endif +} +#endif + +// MARK: - ImageIndicator +// Displays an ImageView. Supports gif +final class ImageIndicator: Indicator { + private let animatedImageIndicatorView: KFCrossPlatformImageView + + var view: IndicatorView { + return animatedImageIndicatorView + } + + init?( + imageData data: Data, + processor: ImageProcessor = DefaultImageProcessor.default, + options: KingfisherParsedOptionsInfo? = nil) + { + var options = options ?? KingfisherParsedOptionsInfo(nil) + // Use normal image view to show animations, so we need to preload all animation data. + if !options.preloadAllAnimationData { + options.preloadAllAnimationData = true + } + + guard let image = processor.process(item: .data(data), options: options) else { + return nil + } + + animatedImageIndicatorView = KFCrossPlatformImageView() + animatedImageIndicatorView.image = image + + #if os(macOS) + // Need for gif to animate on macOS + animatedImageIndicatorView.imageScaling = .scaleNone + animatedImageIndicatorView.canDrawSubviewsIntoLayer = true + #else + animatedImageIndicatorView.contentMode = .center + #endif + } + + func startAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = true + #else + animatedImageIndicatorView.startAnimating() + #endif + animatedImageIndicatorView.isHidden = false + } + + func stopAnimatingView() { + #if os(macOS) + animatedImageIndicatorView.animates = false + #else + animatedImageIndicatorView.stopAnimating() + #endif + animatedImageIndicatorView.isHidden = true + } +} + +#endif diff --git a/Pods/Manifest.lock b/Pods/Manifest.lock new file mode 100644 index 0000000..e7c7436 --- /dev/null +++ b/Pods/Manifest.lock @@ -0,0 +1,30 @@ +PODS: + - Kingfisher (7.1.1) + - RxCocoa (6.2.0): + - RxRelay (= 6.2.0) + - RxSwift (= 6.2.0) + - RxRelay (6.2.0): + - RxSwift (= 6.2.0) + - RxSwift (6.2.0) + +DEPENDENCIES: + - Kingfisher (~> 7.0) + - RxCocoa (= 6.2.0) + - RxSwift (= 6.2.0) + +SPEC REPOS: + trunk: + - Kingfisher + - RxCocoa + - RxRelay + - RxSwift + +SPEC CHECKSUMS: + Kingfisher: f738f9c4a3415823b8e2985d10aa2d6a9f37bc4d + RxCocoa: 4baf94bb35f2c0ab31bc0cb9f1900155f646ba42 + RxRelay: e72dbfd157807478401ef1982e1c61c945c94b2f + RxSwift: d356ab7bee873611322f134c5f9ef379fa183d8f + +PODFILE CHECKSUM: 9e4406f25ebfec3e20e49b98c0644cffd32405b1 + +COCOAPODS: 1.11.2 diff --git a/Pods/Pods.xcodeproj/project.pbxproj b/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 0000000..9c31c88 --- /dev/null +++ b/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,2919 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 55; + objects = { + +/* Begin PBXBuildFile section */ + 000702A76DD1A018D9B45DEB79FB505D /* UITextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9D4E24F8810B9D1C4F328503EFC58863 /* UITextView+Rx.swift */; }; + 00BEA6029C428FEE644AC3D42AD83282 /* ImagePrefetcher.swift in Sources */ = {isa = PBXBuildFile; fileRef = C099B50BD50310DBD0C05306CF6C398A /* ImagePrefetcher.swift */; }; + 00D58ACCBB52B44325EBC30E58CD3EEE /* PrimitiveSequence+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = D67C27EE7920EE4807F35105298280E8 /* PrimitiveSequence+Zip+arity.swift */; }; + 022DFEBF3DD3B5B1627278F189254A25 /* RxCocoa.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC025C53C49665C068F28F5ED6E9BA35 /* RxCocoa.swift */; }; + 0285857A24F66E925987A5876F0BE63B /* ImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3F20DF84A10C6732F7675B9AE55FCEF /* ImageDataProvider.swift */; }; + 02F9A9BE4E45DB08E4427B95D0BCFA16 /* NopDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5025FB5B6C0E58DC26EBDD4C7CF6539 /* NopDisposable.swift */; }; + 03D894819ECA3CA8F42C578E42D08960 /* DelegateProxyType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57C02CC9D716ABE836FC698744C40162 /* DelegateProxyType.swift */; }; + 0422FC5745E406CB752E9497A2F56EA9 /* _RXKVOObserver.h in Headers */ = {isa = PBXBuildFile; fileRef = 78DBB9BD0602DF88C96C8874E26D0C27 /* _RXKVOObserver.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 04B2DDDF8C3C5DAE8952E85BD4ECF6CE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + 04B641288248D3ACC28E7F707058073B /* ObservableConvertibleType+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 573926B12A41731C6B0AAA5F1394ACF7 /* ObservableConvertibleType+Signal.swift */; }; + 0510E8EA51914CB2176AD0F173937FAB /* KFImageRenderer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C70F8841D47B6108745F20EAF1B7319 /* KFImageRenderer.swift */; }; + 05228565AAA7FCED4BAFB2B7EF71D53D /* KingfisherOptionsInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7A75B8072A89388F54D328CC33074C05 /* KingfisherOptionsInfo.swift */; }; + 059639E700DEFAEF08F56484E5F67BE7 /* NSButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B026EECB48C75BB8D4373B876D5D757 /* NSButton+Kingfisher.swift */; }; + 070EC803A862D795256CF9DBA627E810 /* ObservableConvertibleType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 256D1BE267826C7A5B0D21E89829F186 /* ObservableConvertibleType.swift */; }; + 071DE38A1044FDA3EC1353CC7B9D6773 /* Completable+AndThen.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC05C3D15F4398DDB4E958C53D4E4116 /* Completable+AndThen.swift */; }; + 07E9184E1F7F568434EB37198DF51C3B /* PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47D9D6FB3FB7EB503D7A85011FA19A8C /* PrimitiveSequence.swift */; }; + 08155F3F6D55A38A07F00F85763290E7 /* UITabBarController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A14E61A58E8566B4B358AD4CB44FCFB3 /* UITabBarController+Rx.swift */; }; + 082EDC820D76DF95C71A5018112DE512 /* UIButton+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 309A7B348C7A018E85DBA902D455347F /* UIButton+Kingfisher.swift */; }; + 0975174D3CF422126D1C65414D463B5B /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + 09997FDBE8364411FFB6F495729608D2 /* Driver+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF59433812B9DC199478694D9B4B1246 /* Driver+Subscription.swift */; }; + 09E4A424C9A4B6AF425B42861E50E5F0 /* UIBarButtonItem+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1BB12986CDCDB89DFABBF6054D06FEC /* UIBarButtonItem+Rx.swift */; }; + 0B2165491D9E7087D8C78C7A8128A9F0 /* UISegmentedControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 39169A0D9A36E134D5B402DFDE82C77E /* UISegmentedControl+Rx.swift */; }; + 0B6974B6BDA652DC64A58317C2934C3D /* Dematerialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17D24989F7C78CBD46A2F964A4A8A477 /* Dematerialize.swift */; }; + 0BF12117307EAFA50B59A5D057C67DF7 /* DispatchQueueConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = 593DACEE9DD963E86B9A4C9355EC9529 /* DispatchQueueConfiguration.swift */; }; + 0D5B9CA194B784F86BC10A145D1B457B /* Disposables.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA089C793A7294C12FC5B8F5C501B129 /* Disposables.swift */; }; + 0D6D0C12EBF3178912A92BF632A29303 /* OperationQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = E207E575E852821818CF45151A7B9EA5 /* OperationQueueScheduler.swift */; }; + 0D7B6FF8C492D77C003609B68CFABA1E /* UISearchController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 066EA749DDAE608EC1C2512673A8CE66 /* UISearchController+Rx.swift */; }; + 0ED8FBFD9A86D21BF69137EC9350E575 /* SessionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 035700EF14CCE6A36A07A5D604252056 /* SessionDelegate.swift */; }; + 0F394A11701EB823EB92A842A34424A2 /* LockOwnerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1E8840266C690A49D91682712E72B9F /* LockOwnerType.swift */; }; + 0F75B8C82523266A3DF606A5974073AA /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74611FF6E108D51044FDACBEDCEA272C /* Platform.Linux.swift */; }; + 116059B3C9097D472A5474217E29A4EA /* Date+Dispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A003EE5E2035D78B7EBC111C3CD1E1C /* Date+Dispatch.swift */; }; + 1185A2B40E14F2FCBC761FC99777CAD8 /* ExtensionHelpers.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD9386FFA38863D2A3273C631322F7E9 /* ExtensionHelpers.swift */; }; + 122980E44B15C64CF0B14DC94D7EB5C9 /* Kingfisher-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = B7FCD356D832308B24DE9B50105999F0 /* Kingfisher-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1472453F13469248FCFDB7DA56B7F427 /* PublishSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 204DC3001AB65CBF63130DB17A9EC6D2 /* PublishSubject.swift */; }; + 14D2C2DC6532CC4AAD73F205B9211DB8 /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 254D9E505B6D1A753C59BFE304EB1BE1 /* RecursiveLock.swift */; }; + 155D953401DF644E75F2ACE729D00DF2 /* Infallible+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CA18C31ED77D7EA8DCE74634CBF93DA /* Infallible+Bind.swift */; }; + 15D5D77E68C8B6AF20B7056602F7AEBF /* RxPickerViewAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = A1E2761EE1212BC4BB8E539BC93D7842 /* RxPickerViewAdapter.swift */; }; + 161856AC63FAA2C3D8164A7500E14CB8 /* UITableView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0A406BF90BFD060A507BFE227FC9730 /* UITableView+Rx.swift */; }; + 16EB1EAEF9D5FF0D6E4B221ECB397D63 /* RxCollectionViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AA01AD91A96C4A92DC718480BF8E4FB /* RxCollectionViewDataSourceProxy.swift */; }; + 16F09B773C24F9947B096E8F1F1CABD9 /* ElementAt.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9204F68E3EC8D088420BE817820C9224 /* ElementAt.swift */; }; + 171A21B0155EA10267C1DE165A6E1500 /* NSButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86DD172B182805841A3A2061759B42D9 /* NSButton+Rx.swift */; }; + 17C3DC7D054023FE2C760209BAD655AC /* Throttle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 47BAF640636860171656B4A3BE35179B /* Throttle.swift */; }; + 181A1502BAE999B700D1865E74F0CC48 /* Empty.swift in Sources */ = {isa = PBXBuildFile; fileRef = D386DA1FDD9D54279A85E31A698B2037 /* Empty.swift */; }; + 183BC936A084A620928D8EDC52132B8C /* Buffer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F6A91146050496D447EBB82EA7EB0FA /* Buffer.swift */; }; + 1952485AFF7A1BCCA4D4B142E82FE627 /* AnimatedImageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 846DDB743B7772FECA5E9D40134868B5 /* AnimatedImageView.swift */; }; + 19999942346C1837E2A7C7024014A164 /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 665C9746CC0234EFDDEBB59D0A6200AF /* InfiniteSequence.swift */; }; + 1AA89F327105C026976BF6E831B193A2 /* ImageBinder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A77EA2F4CBF8F9530A462A4AA2C5489 /* ImageBinder.swift */; }; + 1AD93376D403A851F152D1B804F7BFC0 /* Signal+Subscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6CF11E4E091F4DF262DBF2E02B8339EB /* Signal+Subscription.swift */; }; + 1ADC9B7900EB98DFE683CBDEDBE86E1A /* Infallible+Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D5B9644894C489A87BE27ABAD388DE8 /* Infallible+Zip+arity.swift */; }; + 1AF3BF0EDE10F429386594F787838C1B /* _RX.h in Headers */ = {isa = PBXBuildFile; fileRef = 2A97390210CBA1BCC3E831A2C79397A4 /* _RX.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 1B402AACD54B2064A7BC86857F2769DD /* InfiniteSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 276504E06EE445B80BAE0BE356B3747A /* InfiniteSequence.swift */; }; + 1E07E7F80F58C41D52DA88B1495D4C58 /* Materialize.swift in Sources */ = {isa = PBXBuildFile; fileRef = 90DFD528941DB2E45A03A9B1FA741E64 /* Materialize.swift */; }; + 1E3FBC05EB6DACC9EEAD4C0B6B37472F /* ScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F5A54A9DA49163C7145C76F8355D1C6 /* ScheduledItem.swift */; }; + 1E9033562EACB851BBAB74F033194B48 /* RxPickerViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F60DF6BE39EB76887AA7E118E700A41 /* RxPickerViewDataSourceType.swift */; }; + 1FD2928BC156D990D68B105F518C60B6 /* MemoryStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 038539E8C2329F87853CB519948BE64D /* MemoryStorage.swift */; }; + 1FE693B5ACC6AD7320CEFC20B64546E4 /* KingfisherManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38B418820BDE7F9EAB6033E95EF2DD39 /* KingfisherManager.swift */; }; + 1FEE89BF952BE7ACA46E642DA2E48CA2 /* DiskStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB1621D1356737AD361FF017ACCEE879 /* DiskStorage.swift */; }; + 202148F555B1DD5F0AA74F682713B0BF /* DefaultIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13A194DA04F1FAE32DF8451C7EC0397A /* DefaultIfEmpty.swift */; }; + 210E6BE763C894C38888F5B166A2EA64 /* PublishRelay+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AD59A1FDED35C1684D1987A01272D /* PublishRelay+Signal.swift */; }; + 21D22789C1145C6FED87DC6EA0F4B032 /* Timer.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD67C50AD918E1F87C31C64E32A17C9D /* Timer.swift */; }; + 22216C300C763044344B9DBF97317E63 /* RetryStrategy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42C98E9C3712ADEC843BB1445B0B79DD /* RetryStrategy.swift */; }; + 22540EA90BD2532208BC8FF0806E0746 /* SynchronizedOnType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3559CF60499726E5518704F3352488AD /* SynchronizedOnType.swift */; }; + 22BD1346F66BFCB129AAA44EEF322AC9 /* Resource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38732C512E987D0D3209963CDA609519 /* Resource.swift */; }; + 238C4A1EC8BA1D3A575ADA67F68CD09C /* ControlTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 241691F359B733E2056B8DC609B60F37 /* ControlTarget.swift */; }; + 243D7CFE1D56ED80ACB2B3E71B4CB603 /* AuthenticationChallengeResponsable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 753CD1C6CC020253A407CE3A8E5EB836 /* AuthenticationChallengeResponsable.swift */; }; + 24C44D889CCC3570C277EB1C3CE505F4 /* UIButton+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5141B34991C273AA0F55C8B9C9BAA501 /* UIButton+Rx.swift */; }; + 24CD1D4CE6B2BF7F57045D6C4281F17E /* Maybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA91BB1404869D1480754831C6E82168 /* Maybe.swift */; }; + 25FC036BEA33CAB5D80F5A41644535D3 /* Storage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02D56418189CE2180CD551B09EE03069 /* Storage.swift */; }; + 2722C9B25CF57D3AE89825729DEA9BED /* DelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1208B59E06C649DFE5FE192D877C55B /* DelegateProxy.swift */; }; + 278EB57FA625A697EB8B7A0D8124AC38 /* RxRelay-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = FADB38E9C9FD65A133C879209C9C2021 /* RxRelay-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 28C7C978A5E7DCCAF9F4B229786B3F63 /* Error.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9E44D0D599D5C8440E7F76599046945 /* Error.swift */; }; + 28D5D9EEAE845C76C8079BD1C77BFE82 /* RxCollectionViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 836FA04B8B9B8C930387B9ACAC062972 /* RxCollectionViewDelegateProxy.swift */; }; + 28DDBE36EE067086F4925C830D668FBA /* KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C4B711F5F67AC1D5168CCDA2F79619D /* KVORepresentable.swift */; }; + 29259059754655C94419B9E2810A70B9 /* Deferred.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93D1A993428B6200A1864B6895B46059 /* Deferred.swift */; }; + 2992F474C57FDE1E458D833070188A3A /* ScheduledDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9384A9D594BA0B3ABADCA346461AE61E /* ScheduledDisposable.swift */; }; + 29FF13E23FD52E46D30530549410AD7C /* ImageTransition.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2E005D09C75B7939241EBC3ACF8725EF /* ImageTransition.swift */; }; + 2B767CB910375F76560C6F5694609383 /* ImmediateSchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E26E49C79C3DCD957B46E8A42A534405 /* ImmediateSchedulerType.swift */; }; + 2BC1AD613A135B6EA990426C5DA41E0D /* Infallible+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = DB24EF4D5E4A05A01CF1697F16A3C908 /* Infallible+Operators.swift */; }; + 2BDB7D759A930390DD50BAEFF87C8328 /* WithUnretained.swift in Sources */ = {isa = PBXBuildFile; fileRef = A44DE42418669BA60C6BFDC99A41FF77 /* WithUnretained.swift */; }; + 2BE89C24BFD3FB663E37C607C289B3B6 /* RedirectHandler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87EE52438F504132352D1A803B540129 /* RedirectHandler.swift */; }; + 2C64E385669A619F264F7556914DF205 /* UISlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0A2F3DC44E81F53D72DFFAA215A85B11 /* UISlider+Rx.swift */; }; + 2C82D96E13E491087D3F2EACF9294C8E /* Merge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DF5F64075BE015B0E4A94A4D723C953 /* Merge.swift */; }; + 2CE4463435DA3DA87408995F74475409 /* Pods-Nasa-NasaUITests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 56D4E7ECD516A37F2AEE8978B3B5DF76 /* Pods-Nasa-NasaUITests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 2D0F32108963808871C79483323D7204 /* SerialDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F0CCA805B17A3F518CEB94F5A9E17141 /* SerialDisposable.swift */; }; + 2DEBA024E86F1AFC0D4215AD4A74A4F3 /* Utils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E514D961A1E4FF8A88B9A696859CEF8 /* Utils.swift */; }; + 2E00D18294EBA1D2232D1AF0E1BE9D41 /* Single.swift in Sources */ = {isa = PBXBuildFile; fileRef = 19C61AA1D29DF02DA1DBE6FED144C917 /* Single.swift */; }; + 2E150C92EA41FEC6C98EAA399F2F161F /* AnyObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 300289A8F4020601668E8504FE6E00C4 /* AnyObserver.swift */; }; + 30BD172B405327E404674D436B0B1F2A /* AsyncLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFCA8B0CFBD32671E34A95012FF08B62 /* AsyncLock.swift */; }; + 31F0D187BC76DAB3C2DEE8B2CABB0535 /* RxTableViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 551E9EDABFE6F6C3985087A678D24DD3 /* RxTableViewDelegateProxy.swift */; }; + 32B6121B1923DDF56E9533E23DD0F316 /* Multicast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 58DF78FBCC8D025608AFCDB64E94B7F6 /* Multicast.swift */; }; + 32F572FAB2C08AAF6A3E92B80F621E66 /* VirtualTimeScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72CD3A7E60C3A4A7E20AEBE4D9F79954 /* VirtualTimeScheduler.swift */; }; + 36194766BE6C29E290145F7F0A7C5DA1 /* PublishRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F3EFD230ACBFF33D75339D80A4DBCF2 /* PublishRelay.swift */; }; + 36594622DE161AE6B8212571B98F6A52 /* Binder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87FE5AE82D1B317B99D0BBC417C13EA5 /* Binder.swift */; }; + 382F19611B366911F72D5C9C2A83852C /* WithLatestFrom.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E278B10D48A31495A483A772250AF3F /* WithLatestFrom.swift */; }; + 38D0534EDDC37793282AD797DF3CF4B0 /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = 731DA7559774054AC732C32D2D466D36 /* Observable+Bind.swift */; }; + 39A67C9747B097343EA9D1B7CC8FA14C /* Completable.swift in Sources */ = {isa = PBXBuildFile; fileRef = D54F3220BCF82B5E9D8BB59B599EFEFA /* Completable.swift */; }; + 3AD5DBB915C2623991F7DBACD173BBB4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + 3AF7DB9AEFF47F1F7F91AF28440E4AC6 /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7C1C444C537BD2AF05A4C03C1F164B81 /* Filter.swift */; }; + 3AFEA39C21C700AAB86C4ACD9436D357 /* RxCocoa.h in Headers */ = {isa = PBXBuildFile; fileRef = FB2668BDC38D0808ABCC0AFD272DBBF8 /* RxCocoa.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 3B82FB00AD02652E1801233E5684DB1D /* NSControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0C2577FC9887D8705C76D78D1C5B985E /* NSControl+Rx.swift */; }; + 3BBFDACF1500DD143119CB084D8DCBFF /* SubjectType.swift in Sources */ = {isa = PBXBuildFile; fileRef = F00D34E61FAAFF1A804BFAE8B34F51D2 /* SubjectType.swift */; }; + 3D11D3661303538BCF5F69E28AEA58E6 /* Cancelable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 87E9B0EC98D89A8043AA03EBF3AADF89 /* Cancelable.swift */; }; + 3D42C9D3EEBE1EAD7E365276753FE99E /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 347B29F2635F01233990E9C245FA1DC2 /* Queue.swift */; }; + 3D445FD9D8FFBDD79E0D04BDFE96B0BB /* Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 75567979F42C7049A3177B96B09F1FD1 /* Signal.swift */; }; + 3DD9694A6D1F5035C6C400C6912B9E36 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2D01C452CC574D02C19716426A6EB94 /* RxCollectionViewReactiveArrayDataSource.swift */; }; + 420C200A05BB29E1D299D1BADE9139D2 /* CFNetwork.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 872D7EFA572ECEE8EF993C27196E16DD /* CFNetwork.framework */; }; + 42AC1514E62AD73452FBF69C93C53EE4 /* Switch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6B35C4107E8F589E3345F787F1A1F303 /* Switch.swift */; }; + 43473298D54EB1C5498C9A404AD68F06 /* RxSwift-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 7638CD1C41EA2C2D4C359A360E13A543 /* RxSwift-dummy.m */; }; + 44AEBB2D29B9FB87530556A0CEC170F7 /* RxNavigationControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF6797F3F6131A47B2E90FE2F5657783 /* RxNavigationControllerDelegateProxy.swift */; }; + 457BE444ED617FA7D6851D6DAA9D7234 /* Delegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C73D792E956EB3F2432C8962719CBC4E /* Delegate.swift */; }; + 45C55DE926122B7CA9DF1C302B5D7333 /* AddRef.swift in Sources */ = {isa = PBXBuildFile; fileRef = 066CAD6EFE30AE8BD17C67089662A828 /* AddRef.swift */; }; + 472AF39B5C345EDF67E488A0A667AF4E /* StartWith.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD1B450DD691AE08E1A8E779A484C1CE /* StartWith.swift */; }; + 47A5B1B49A2B0FB00EDFBB6C75FD7C26 /* RxMutableBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24115E491FA4BD6A1F000508B25E41C6 /* RxMutableBox.swift */; }; + 47B48B7531CE161773DEF0B851D08037 /* ControlProperty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6C32BE0FBF23366538EC38133C3B4761 /* ControlProperty.swift */; }; + 4838B3C8759DACF738F61BF91100379A /* RxTabBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E55E337DAF3B45894CF50E3D4D83EC9 /* RxTabBarDelegateProxy.swift */; }; + 4878A6C8BDEF6FCC155719CA93BA9586 /* _RXDelegateProxy.m in Sources */ = {isa = PBXBuildFile; fileRef = C1B32AA07CD3797FDE701EFB2722FCCA /* _RXDelegateProxy.m */; }; + 4972C5113D037B1515BE33E59008F381 /* RecursiveScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC3023A9A8291E6F79715071B06F3D3A /* RecursiveScheduler.swift */; }; + 4994F1CABB9926703D82BA0D9D66321C /* RxCocoaRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = F4E1DA88CDEB6032902BF148F263C418 /* RxCocoaRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 4B745396FD1223BA8532DFE2216E043C /* NSTextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 991A2A3F38D320429C0AF533CCC1A2DA /* NSTextField+Rx.swift */; }; + 4B8BDB6B894C3EBC0E5463298666223C /* ScheduledItemType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2464C1376934D750B723647A48B6C83F /* ScheduledItemType.swift */; }; + 4D8777A12EEDEF2F6FE6190C1DD4F569 /* Repeat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C56FDD70B5E9F43C3796E6AB1585BEE /* Repeat.swift */; }; + 4DCA9775E5CCF599460BDB46E77F6FA4 /* Kingfisher-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 79A4AC560B432B2A9F0D7F8562BA173D /* Kingfisher-dummy.m */; }; + 4EB4328C78B36211BF7D50529327FD7C /* UINavigationController+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32D5973F5B6BE2FD9D6862829F3341B9 /* UINavigationController+Rx.swift */; }; + 4EE0F2D2112CE993AEA24549F5DB19BF /* UIControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A887DFD8B864789ABC116EA35FECBD49 /* UIControl+Rx.swift */; }; + 4EFD31D7DB8D26D9D031A2225A0C6AEC /* UIApplication+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC794D94362E616CA4F9E48C102DF492 /* UIApplication+Rx.swift */; }; + 4F37E521D341C47CE73DDCF21BA95A52 /* KingfisherError.swift in Sources */ = {isa = PBXBuildFile; fileRef = 45DA6997549500684C8FDCAD08448041 /* KingfisherError.swift */; }; + 4F744303AF9B5E7CEF8C3A9327E852B9 /* ControlEvent+Signal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B64D3B6DCACA3245426B3DCC4CBEF4E /* ControlEvent+Signal.swift */; }; + 4FC27FF6DF0328A134393A57E735977B /* RxTextStorageDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D50B144E67E3FEDDD925A1E80FDF5EE4 /* RxTextStorageDelegateProxy.swift */; }; + 506128E1CC424E40E2691546D9547549 /* Placeholder.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF422F832F0B72ABF641D5B011E1ADF2 /* Placeholder.swift */; }; + 50681D70D26BA315A5DDC1365B4CF0BB /* KVORepresentable+CoreGraphics.swift in Sources */ = {isa = PBXBuildFile; fileRef = C018D93FEE06CD7CFB3BD348FA7B9967 /* KVORepresentable+CoreGraphics.swift */; }; + 509490FB1D30FEC59AE4BC21AEEBB7BB /* RequestModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 73282384CDDE200004F6A2A982D8F9C0 /* RequestModifier.swift */; }; + 51C984425C777CF8B613C230DCE2DB65 /* UIGestureRecognizer+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9BE0B00707E6FF026FD1C832618D8245 /* UIGestureRecognizer+Rx.swift */; }; + 5291A92FB6C7E3FB265DC22EDD908884 /* Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = A29091995433007CC3BDB7701C59607B /* Driver.swift */; }; + 529BDA5E8CE104C4B384017447D0DC60 /* _RXObjCRuntime.m in Sources */ = {isa = PBXBuildFile; fileRef = 711A1FB5D3CEBDB29D84C91569DBC787 /* _RXObjCRuntime.m */; }; + 546E291E507CB1DB5C7D19CD100AD7F3 /* SwiftSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8DECDBB7D351E4436AFF57C154B6D604 /* SwiftSupport.swift */; }; + 548B9145185925F281D9B1951379E6D1 /* RxTabBarControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7B243EFB97DCFEC58BFD68592BE69E99 /* RxTabBarControllerDelegateProxy.swift */; }; + 54AABF5F8E6824B98B89B74ADA7CD631 /* Sample.swift in Sources */ = {isa = PBXBuildFile; fileRef = 194DE807E02F7FCF6F24AF3BE9651CA4 /* Sample.swift */; }; + 557D81659F1902BDDAE21CA1779EE49B /* Skip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14C07AEFCB83FD479726E58A485E7F8C /* Skip.swift */; }; + 57DBC03B00EADA274BDF1CF35024AEC7 /* SkipWhile.swift in Sources */ = {isa = PBXBuildFile; fileRef = CAEBF98EC58EF180B60F1F9E548B6B15 /* SkipWhile.swift */; }; + 57FC31B14C753B5C63CEF00560F8A6EF /* SizeExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CE33896B5F0FA3F4B2DE04BBED0806C /* SizeExtensions.swift */; }; + 582D59E0D2EF62E0575933C99B393704 /* GraphicsContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 594877CA38F712D12ED1A3BFBBEB35F4 /* GraphicsContext.swift */; }; + 59449E02883D41EACB918DCE1802711B /* SubscribeOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = 89D58D454E656EB201E21C9EF37A70E6 /* SubscribeOn.swift */; }; + 59691189B7A014BB0230561AC0A489A6 /* RxCocoa-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AABE5D7EBB5C1664F6279707E9AA7519 /* RxCocoa-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 59BC9047F4BEBBC06235608D974E230D /* NSTextAttachment+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8976B65457E61E8AD7899E4D740FDDBF /* NSTextAttachment+Kingfisher.swift */; }; + 59C027CC4112D05795E2B870C33A413D /* Reduce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0D5313A20F617A6A0FFE42F2B9FA8E31 /* Reduce.swift */; }; + 59E9FDBE2B850DF42485D950735E3AB0 /* Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = A935D27A5DA9A4B25D2649B10D85666C /* Create.swift */; }; + 5ADB30DD9A03859018550A999ACB0652 /* KFImageOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8BAD8AFCC4A45BB686B716BE51FBB9C5 /* KFImageOptions.swift */; }; + 5BF6B2D545C5849CE38838A7B50F328B /* DistinctUntilChanged.swift in Sources */ = {isa = PBXBuildFile; fileRef = BB9C3817F7DB7846D93C1B48A7A44FB4 /* DistinctUntilChanged.swift */; }; + 5E27DD292D3A55657712DD7AFA7B8FCA /* KFImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0397017297B9CF552EDB2CBB2EB4D702 /* KFImage.swift */; }; + 5F852F38CBC282496CCBE37C51324B2F /* ImageProgressive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BA2EBCF6C82576ECF70AB7D5052288C /* ImageProgressive.swift */; }; + 621CFB9D43A48783BC730CFE04CA02CE /* Bag+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5A47D822D952110CECC562981840EAEE /* Bag+Rx.swift */; }; + 63719AEFBD0D86AE09823E0E223A33DE /* ConcurrentDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2444CB36080B3F8C9F26783D03E1EF90 /* ConcurrentDispatchQueueScheduler.swift */; }; + 675E467D99B81FC6698572D9CCFC8335 /* Using.swift in Sources */ = {isa = PBXBuildFile; fileRef = 086CB9F323A5A9B4A6BF898353D4E952 /* Using.swift */; }; + 68623BC382EACE93D53213D1D5AAAD3C /* NSTextView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 671F3730AFF17DD82C3672D14F4D8D10 /* NSTextView+Rx.swift */; }; + 690835CAF47F831971F17CC1667C9FC1 /* RetryWhen.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78BBC08AB3F71A56C70C1D83460673B1 /* RetryWhen.swift */; }; + 69537EEBAEE542798C9630CB8F96DF8D /* NotificationCenter+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2E2CDC3BC75BD1863C73AA5362FD273 /* NotificationCenter+Rx.swift */; }; + 697246690DE02DD236B8CCD3531EF331 /* Debounce.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F89590B2C85F3BD4C81FEBC2F44E282 /* Debounce.swift */; }; + 6A90EDE48F6D19587EAD14EB964C9C49 /* ObserverBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DD6FFD079EF8A2DDE25C35353EBD004 /* ObserverBase.swift */; }; + 6C2C2663370962E2D50CAE56B42B0F81 /* CompactMap.swift in Sources */ = {isa = PBXBuildFile; fileRef = F619746893827D94BB14FA4D4F57DB5C /* CompactMap.swift */; }; + 6D8CDC66C950346874056F3F45FAB0FC /* NSView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 67591D311B21307172FABF417357CEC1 /* NSView+Rx.swift */; }; + 6E4532D5FA4D25F35F98D55053B0E940 /* SynchronizedUnsubscribeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1A00EC4EC537E97430E2B41CCA99FD75 /* SynchronizedUnsubscribeType.swift */; }; + 7008E2EEAA93681AE2BEADA2C12E43AF /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9DBE86666C4C7C00176BD62714FC2B60 /* PriorityQueue.swift */; }; + 70527867C4C4C965053E4283F3778986 /* RxCocoa-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9852B9017511004032B9FF1F04C8A653 /* RxCocoa-dummy.m */; }; + 7083081E60074026B4DBACA8BE6E1DD3 /* Concat.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5950202FDF9773C66FA3213D36FD1C5 /* Concat.swift */; }; + 70A41125865DDF878FC4CBD646349805 /* UIScrollView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26E15E018D9EED7F4CE32D7EB7E83DF8 /* UIScrollView+Rx.swift */; }; + 70F121399B82D87F0CAB4400460A337A /* Observable+Bind.swift in Sources */ = {isa = PBXBuildFile; fileRef = ACB9B8802E98717CBF0CF019F0AC320A /* Observable+Bind.swift */; }; + 70FEC06F54286257E1BA1ECA0C99198D /* Image.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14A111B0125B3332DD41B6A107BC684A /* Image.swift */; }; + 71D5BDF4D210C1DC54AB197B1D2E9D13 /* ControlEvent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 765DADAEB790057019DB04648364475A /* ControlEvent.swift */; }; + 737E35F9D90D0B01AFE31C8117921E38 /* ConnectableObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C273B8A937511063AE9B77E767FAAA5 /* ConnectableObservableType.swift */; }; + 74511229A00BD203485536B1A2FE6A52 /* ObserverType.swift in Sources */ = {isa = PBXBuildFile; fileRef = D325C9B40C9E92EB3BA6895BB5219220 /* ObserverType.swift */; }; + 74CA2DBA0EA27472257A1A84BCE469A2 /* Amb.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84695897916E17EA92CD7925F8D684B /* Amb.swift */; }; + 7546574D3674274B467AEBA286D42F9F /* Zip+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0EE5D91BA47B0C0B75F882C976E151A3 /* Zip+Collection.swift */; }; + 76B214E73D30F27066985B87131AAD1F /* Reactive.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA43120ABE0220521B0FACEC3679E559 /* Reactive.swift */; }; + 77FE06C54FDBF0EC6AA641C26F174953 /* Observable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 21A69AAF600A098645D61F1F7A7DFD77 /* Observable.swift */; }; + 78B25E6EFEBD7B467363581B07A681E8 /* Map.swift in Sources */ = {isa = PBXBuildFile; fileRef = EFAF4638E04D6A613483A18195CCB8C5 /* Map.swift */; }; + 78B5CD94C6FA08D4E72CA298DED2F4E2 /* DelaySubscription.swift in Sources */ = {isa = PBXBuildFile; fileRef = 509BFA3A2F815D66AE5490E0D9B15E5C /* DelaySubscription.swift */; }; + 79CE0CB43605620DF5B8C9991CFD064A /* SingleAssignmentDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4224FF8BA20495FDD3B5C29557D3B96A /* SingleAssignmentDisposable.swift */; }; + 7BEF420E8F9099C5079845A9BE4DCA63 /* RxWKNavigationDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3F24826DDE7D64BFC7A0BCA4DF3B6978 /* RxWKNavigationDelegateProxy.swift */; }; + 7C0DC741562A17F09F60EB9329DDA7CD /* ControlEvent+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31EFB9EE3C11EADCE4C7DB67CFD4308D /* ControlEvent+Driver.swift */; }; + 7C7418FF01DD7BB909719682B634A8A5 /* SessionDataTask.swift in Sources */ = {isa = PBXBuildFile; fileRef = C898643E7C365B2110EEECE2E024FF59 /* SessionDataTask.swift */; }; + 7D69A909D084D6287BDD0FCEBEC34E0D /* CombineLatest+Collection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5F19834A1B62B273FB9DE568FB7B1D19 /* CombineLatest+Collection.swift */; }; + 7E3402342205B2DC03468A7FD95F61A9 /* NSTextStorage+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46557E1582E320EB12560AA106A3EF3F /* NSTextStorage+Rx.swift */; }; + 7EEED39CE5F3611AB4D7205FD038021E /* NSObject+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 299B19C83AA437DF51807FF8A0116A15 /* NSObject+Rx.swift */; }; + 7F2E9C8F62ED31B2A725167BC98A7A0F /* Generate.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD533D32A57348C33C62BA74428478AF /* Generate.swift */; }; + 7F60B371FE78073E7DFDD621FFC482CE /* URLSession+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02E99B14DAE00C21F19A5379E03C9F79 /* URLSession+Rx.swift */; }; + 7FFE4021A4F14124342AD41CE1117B3E /* KFAnimatedImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = B8708766B4E86A2178888E688318B7A6 /* KFAnimatedImage.swift */; }; + 80738D8956C9987CCCEDF551961E5069 /* ImageDataProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC5CE11A43BCD442A68F715BC4F23064 /* ImageDataProcessor.swift */; }; + 808077857F59E5C539F97944692D0DAD /* Infallible+Create.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9B29DBF0770DA52AB49477DFDB5600F /* Infallible+Create.swift */; }; + 81A394201D240F032A6108ED479B427A /* UITextField+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1160C2BAB6A3EA880AA1801140ED996C /* UITextField+Rx.swift */; }; + 841FBD1EB10F9112D309BB28BD10CF1D /* SharedSequence+Operators+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = F611ED177B5CCA74A94808C6F8CEB616 /* SharedSequence+Operators+arity.swift */; }; + 84830EA28F2245CEC7F64F510522400A /* Pods-Nasa-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = DD44EA86799AAB2D629CF2C684F4F639 /* Pods-Nasa-dummy.m */; }; + 8527110343D87F5878FA0CFEDCF8127C /* Range.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93FA7D29AAB8705F01F5B0D66AD537E5 /* Range.swift */; }; + 85F3507E1003F051784AEE2EDDD79CE3 /* SchedulerServices+Emulation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05A835A78CBC37235B8A9803C4D5C2D1 /* SchedulerServices+Emulation.swift */; }; + 878180FF94F4BA823AA65468500D5BA4 /* AsMaybe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ECFDDF445685ACA15D40D07E6CC60CF /* AsMaybe.swift */; }; + 87FDDD76563F9CDFD1461E61884B3626 /* Never.swift in Sources */ = {isa = PBXBuildFile; fileRef = 53CAB4283845A13ABA4F3657A92430AE /* Never.swift */; }; + 881A35B28D93C56E46E305F6138B1A76 /* ImageDownloaderDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78B54A567196097C12B5651EB5CAE227 /* ImageDownloaderDelegate.swift */; }; + 8829BB4B90C734DC9A98316F5133D43F /* Event.swift in Sources */ = {isa = PBXBuildFile; fileRef = FDF0B19FC15BA90936BA5BF3D2F306A2 /* Event.swift */; }; + 894BF76C4272C38C9E17385110BF4A41 /* _RXKVOObserver.m in Sources */ = {isa = PBXBuildFile; fileRef = DA73B22488E82AD4752410DB45D68584 /* _RXKVOObserver.m */; }; + 89D54B82F748F0FCBFFCBEEE2C060E0C /* VirtualTimeConverterType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 877C6EC3C797F8A700D0FF9EAF958D19 /* VirtualTimeConverterType.swift */; }; + 8AEF0775CDF920AC2DBE0C725B59EC96 /* UIStepper+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7ED2066564452073563FAFF29121A419 /* UIStepper+Rx.swift */; }; + 8B7686A732E13434E997809196B15955 /* UIRefreshControl+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52AC685178073CE2C546491DC631D838 /* UIRefreshControl+Rx.swift */; }; + 8D8C2C771785DC4DA1762E259A7EB99A /* GroupBy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13A0DF8765781203921620F29EDB0C14 /* GroupBy.swift */; }; + 8EA5CC7EF28B004A8A813925E4F17F93 /* WKWebView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E6679A12C19FCB8C599445AC992D79E /* WKWebView+Rx.swift */; }; + 8F711FCC712DF6B2EB35CB9039C4BD6D /* Pods-Nasa-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = AB9D6840C14D5277550F97807BD7568A /* Pods-Nasa-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + 8FE0BD68EA39B931E49D9C038BE80B65 /* UIDatePicker+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 770F21ADC933DC7B515BE3B743647A1B /* UIDatePicker+Rx.swift */; }; + 90B552B8FD6CED4AA33BABCC26CD1636 /* Platform.Linux.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DDC4DAFE1E58071E663D24DA336250B /* Platform.Linux.swift */; }; + 9106C93AF453AE86FB40B8269DD07623 /* Debug.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9391EED99BAEB46C2049400C2CDA233 /* Debug.swift */; }; + 91A2335C5506EBC38DD438FEC729799A /* AtomicInt.swift in Sources */ = {isa = PBXBuildFile; fileRef = E518FC6FFB06E6E9102B10C1147BD69B /* AtomicInt.swift */; }; + 92CA5C88C88C68BFF8F0125CA48E20BC /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + 938B46EF411204D0BEE0A56A7D584D51 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F5761FF7A726E317BBACFE95BAA632C7 /* RxCollectionViewDataSourcePrefetchingProxy.swift */; }; + 945DBBCB62542CD24B29F83FAFEF13B1 /* NSObject+Rx+KVORepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 659C95F6167047A371AE813DDE268CED /* NSObject+Rx+KVORepresentable.swift */; }; + 94A8D65E45C085A877A5470503B8DFF6 /* Do.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11E45EF449E27B13A73285473A5E7B7E /* Do.swift */; }; + 95181366D610146E29AD34636DB9EFB7 /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = DA9B86EAD60DB14CF3BDC2844C5ABC41 /* Platform.Darwin.swift */; }; + 95D5EE81CAE35CDDA64E2A0CA4B1DC22 /* BehaviorSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 141E846C1992FC3B824497B4C31E9283 /* BehaviorSubject.swift */; }; + 96F67E76F9DBD3690A25894F1FE499DE /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + 9850A80051F5259DF4BD9060DEFE783F /* BehaviorRelay+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1328BA8F1A85D005BF68F4079DCACA23 /* BehaviorRelay+Driver.swift */; }; + 987304A3D1F19D442787D16D84FF3997 /* Sink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 26E5FA57DDDD1DFB317C5ED60769E52B /* Sink.swift */; }; + 9B0A78AC22E7EDA755F51D86527E2D9C /* Source.swift in Sources */ = {isa = PBXBuildFile; fileRef = C005B6108292C74048FE29FDBB3A6811 /* Source.swift */; }; + 9B6D684A7CCF9470B92E10267E3987CA /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9EF660346736D08210EC9837FDDF26E /* DispatchQueue+Extensions.swift */; }; + 9C3504156FD220881BE7D5C20D2B3476 /* ShareReplayScope.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4FC25F6C3C493911AFC553ED0B080E71 /* ShareReplayScope.swift */; }; + 9CA691C106799A02C3AB7D059BA1218D /* HistoricalSchedulerTimeConverter.swift in Sources */ = {isa = PBXBuildFile; fileRef = BD1A81FD6B7E87F397606D9ADFB89C85 /* HistoricalSchedulerTimeConverter.swift */; }; + 9DB4A288E7875E7346EAB537875222D8 /* SharedSequence+Operators.swift in Sources */ = {isa = PBXBuildFile; fileRef = 313CBC199D9C144DC0550B1BBAAE89F3 /* SharedSequence+Operators.swift */; }; + 9DD9C0E721DD2BA2BB1A65CC36A853FD /* Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DC4726BFD306141702DA64D7CA622A0 /* Rx.swift */; }; + 9E9E7202016CCEE8F776A5174691BFDF /* Platform.Darwin.swift in Sources */ = {isa = PBXBuildFile; fileRef = 54CA1986B4B7E04F0B4124B8C0B1515D /* Platform.Darwin.swift */; }; + 9EDCD950572BAABB6B6C562D2EAF0BBB /* Disposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 017D63D87A6E8E266C74671DED987366 /* Disposable.swift */; }; + 9F2A7A46B6788182F54B1B981938B6E5 /* Take.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EEF33A950F5444D1A6C3863129551A6 /* Take.swift */; }; + 9F5FE22DA95B66B8DC21CB13BE25EC9B /* WKInterfaceImage+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7CD2494752BF402630EBF199135EBDF7 /* WKInterfaceImage+Kingfisher.swift */; }; + A03818F258B2596221C3D55B8960D2FA /* Delay.swift in Sources */ = {isa = PBXBuildFile; fileRef = ED130067DDB9BD1CCD1077798386C986 /* Delay.swift */; }; + A10CA44E513635FB638DA96BCD41CF11 /* TailRecursiveSink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 190D0B1290B83B5F6C9A62481F5B6539 /* TailRecursiveSink.swift */; }; + A1194BE78FCE2929CDA65C95CA310EAF /* RxPickerViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65DAAE0320F729A067CD23F6A910069A /* RxPickerViewDataSourceProxy.swift */; }; + A1985C2CC5030AB984FFA33B94E1E39D /* ControlProperty+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAF9F38612D4CB9C9702024036CE7D17 /* ControlProperty+Driver.swift */; }; + A2020CB303E5DC515FB24444B9A90418 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + A2B7773B46906EF93E44C457E9762CE5 /* First.swift in Sources */ = {isa = PBXBuildFile; fileRef = 178FBC0CAD4510CF099006E3D61CED3D /* First.swift */; }; + A2BABA3A0A7259042C76634239AC9700 /* GroupedObservable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 97B5A42988E1A0A9D562043D29D13732 /* GroupedObservable.swift */; }; + A2C2E9A7817336BA783ABC7C897D7AFB /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E5B11A6C7AA615DB9480FA1ECE82D98 /* Bag.swift */; }; + A2F7FF2AEFF21D78671543FA8CB6A8B3 /* NSObject+Rx+RawRepresentable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 72807B39E40B38A0B9BF0FE82115D701 /* NSObject+Rx+RawRepresentable.swift */; }; + A314A7F05FBFAF439E2E1DF9814D15D8 /* ObservableType+PrimitiveSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = CBA24D30B5FD414A1CAB6D0DE390BFD2 /* ObservableType+PrimitiveSequence.swift */; }; + A316388A35648CB2987E761771456087 /* KFOptionsSetter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 173CCF61D3B200198ED44DBF6E14A6C4 /* KFOptionsSetter.swift */; }; + A3423ADEDFB20D72E2C608221A26D3C6 /* UICollectionView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AB1B319B15ADC03FE14A5722C666C97 /* UICollectionView+Rx.swift */; }; + A37D3661369446F3AA978C8FD342A83A /* UIActivityIndicatorView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 880411AA04678912F31750B286549944 /* UIActivityIndicatorView+Rx.swift */; }; + A39D3555EC8B45B7D6B9505DDAF0F117 /* Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = D965E448753D59388378FF252200AE28 /* Kingfisher.swift */; }; + A3BA9015009ADD44E04BBB2074550BA7 /* TakeLast.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6077A495BA175BE283E5433B37F9CB7C /* TakeLast.swift */; }; + A435E4B3FF0B326E880502C6FD3FC987 /* KVORepresentable+Swift.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C7D77586C026EBDD88A96FFC838083C /* KVORepresentable+Swift.swift */; }; + A5B0A0AFB5C7D852611CEBA072AF7D01 /* Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 487016C43A9C696EF689DB1E07400631 /* Infallible.swift */; }; + A6D090BA4BBBA08BC6BBEF116C285FB4 /* TakeWithPredicate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 11CCB2B8C905F7BB21519F1AC17D356D /* TakeWithPredicate.swift */; }; + A88A844D5356E1690E445024CB796E09 /* Result.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCAD0BEC0DDFCCEE5BD14F65FA4757D5 /* Result.swift */; }; + A8F33D774CCFF1BF6570CB62E85EE7FA /* Enumerated.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80196883EA6E29278366559EFB614235 /* Enumerated.swift */; }; + AA7BBD3390AF2ECAFA1AD576BB69CE15 /* RxScrollViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D702F28288858BA18D04ECD25FC32EB5 /* RxScrollViewDelegateProxy.swift */; }; + AAC2AA6895DE07EB4F655B9A54AC4288 /* BinaryDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3CD1DB6F70625F317E2AAE03A05BB56F /* BinaryDisposable.swift */; }; + AB4875CA5028C3C32274EC2CCDFE9066 /* NSSlider+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 255952E0493402482EF3A6856781EB26 /* NSSlider+Rx.swift */; }; + ACB44BCE1A196930E1A4F5142521A663 /* ReplaySubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3742D4F3A812DEDA45D7587BFA16A37A /* ReplaySubject.swift */; }; + ADE53937ED877CC7327490B8C29AC440 /* Pods-NasaTests-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 2DBC19243FA5BCBBB47A8134B7CAAD9E /* Pods-NasaTests-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + AF6DB912CA426F93811EBEC30249C1B9 /* InvocableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = E61E740BDB8328C95E2FC735D07F2DF3 /* InvocableType.swift */; }; + B091CBCEA9C722C95A2C4D6C425F3487 /* BehaviorRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0B44943E43480310387EA9E42DDF970 /* BehaviorRelay.swift */; }; + B2251C3E16EFC789C45A236A231D703D /* CompositeDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = F70F3CA7F64F8E6BED39B3C117FA9ABF /* CompositeDisposable.swift */; }; + B25E07EA645911443A38DA1E68166156 /* Box.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1660268DDCE579590238085654AC6112 /* Box.swift */; }; + B283E0B7BB5A5910188B1B4C7B15FF53 /* ObservableConvertibleType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2AF530F70F556F38DF940D440404373C /* ObservableConvertibleType+SharedSequence.swift */; }; + B4778F823B87F7C8661123F4E13E64A6 /* ObservableConvertibleType+Infallible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0121CA18F76DBA229576FE20F51CC20E /* ObservableConvertibleType+Infallible.swift */; }; + B73D4D0288F5437D0B46BFD7B00CB3D3 /* Zip+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DC5E11560B6B3A7A08289CB51A77341 /* Zip+arity.swift */; }; + B8E27E8D24CBE6DB22F38E06FFBDB710 /* _RX.m in Sources */ = {isa = PBXBuildFile; fileRef = 2FDAEF959C217E3AAE4B7E563231E365 /* _RX.m */; }; + BA225CB88C5E94F83E8C83D40813063F /* InvocableScheduledItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8C2E909CF60AB440E70AC0741A4F2AA /* InvocableScheduledItem.swift */; }; + BAFE36491C2BEF6B5C023FBF506E12E2 /* SynchronizedDisposeType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A09EBD7676C0F16F630021DEB6C615D4 /* SynchronizedDisposeType.swift */; }; + BAFE9BCC959743F69B4FC5C11C5AFAD2 /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = A4026CC76C5C4D10BB5E1621462E50F0 /* Errors.swift */; }; + BB019F48ED71BE9E9056495550AFF6C2 /* Just.swift in Sources */ = {isa = PBXBuildFile; fileRef = B2EB90401C075B62E9BE003E5C247C47 /* Just.swift */; }; + BB75BCF76F22254E3302085A5A6A4B48 /* SchedulerType+SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76F6B571F692833993F0EE21BBBD5B33 /* SchedulerType+SharedSequence.swift */; }; + BC18682BD8437EC691E553070C540FAC /* DisposeBase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 168B034469C3020A01BD7EB19B8C3409 /* DisposeBase.swift */; }; + BD382E78580D295D10100678D4F66A76 /* String+MD5.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF0090EDDDE993069035E68659AB6DE8 /* String+MD5.swift */; }; + BED3C4158B505B8F85889E5E28918967 /* SubscriptionDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = C356B6347ADB2656B46F6F0144959071 /* SubscriptionDisposable.swift */; }; + BEFE617EABAE8B434A580CCD4179C04E /* TextInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9718ADF3B40EBC380D55C19C95DEEB2D /* TextInput.swift */; }; + C4088D41E491408954E951A09E01B675 /* Zip.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18C52394FF76FB38E57C3225739FE247 /* Zip.swift */; }; + C4D350D569A2B6567E087ED515A93EE2 /* RxTableViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8D54F3EFCD78F700D10C91447B6D7923 /* RxTableViewDataSourceType.swift */; }; + C56A14C84CF05A1A96D8B92E16E0CBFB /* SectionedViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9CF06B6FBB5DBB1F4D6D0739F0346BE6 /* SectionedViewDataSourceType.swift */; }; + C66C4E3E67C26B960FABBC8F1B0C056A /* RxTextViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4D795950640DB4AC7E639CD530137D7 /* RxTextViewDelegateProxy.swift */; }; + C6A9F4EBAFDDF84D305B430316360AF1 /* Window.swift in Sources */ = {isa = PBXBuildFile; fileRef = 981D9449308470332443FF6AEEA4BD3E /* Window.swift */; }; + CAB964E0FCE2D7C94C0FFF77C793CE74 /* Pods-NasaTests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = BF29D6E4B87309849D2B3CAC69F428ED /* Pods-NasaTests-dummy.m */; }; + CC93EE3296F80DAA1790810622FD239F /* Lock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7DD04BCB8E9C26011C133ED0222369CB /* Lock.swift */; }; + CCE8548CB0EC76CBFFB5A6BC4DC3259D /* AnonymousObserver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4EC0E80CF040EEF1CEEF6C403832653D /* AnonymousObserver.swift */; }; + CD7AC3E1C98EA54F7C05C36C52805220 /* CacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = C719A4208504FBE21E15E8FD30265002 /* CacheSerializer.swift */; }; + CE4A963C9646C4A4DF444833737E8CE5 /* SchedulerType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9E99D160193CCBB23FC861A1641D07DA /* SchedulerType.swift */; }; + CF9DAAEC618DE435A7DF19579DE30AA2 /* PriorityQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 631FC8F669F041C47F44CB1BAC72887C /* PriorityQueue.swift */; }; + D05116642C20C568B926B4025B6EF995 /* UISwitch+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1AD4F36B88F678AEADAB02A2EC1C325 /* UISwitch+Rx.swift */; }; + D1DE14077A54174F00E887101A48AE8A /* RxTarget.swift in Sources */ = {isa = PBXBuildFile; fileRef = D4866ECE2BD7F3325786D2C2BCAF3192 /* RxTarget.swift */; }; + D2DCF994A072EB2C46DD41F92E885951 /* DispatchQueue+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 14677C8E07CB908238683A17ED1B0ACB /* DispatchQueue+Extensions.swift */; }; + D3174D3F6661D8ACEE1D29D7DE636C8C /* CombineLatest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96668307975A303706F47C0B9A0BDA32 /* CombineLatest.swift */; }; + D50A2E52EEEA0518E18582D63236FB61 /* ConcurrentMainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B2AC97752DBF56A8D836C63942A6ACB /* ConcurrentMainScheduler.swift */; }; + D5504813E976DA19C5FD8EDA59CC6B94 /* Catch.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2D3C1F7EC6E18E56276BC08423EC09F9 /* Catch.swift */; }; + D583F8FC3BFE7CE7368F5FE75679F388 /* RxTableViewDataSourceProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5645B2FDDA74EFD8B513313430E182DB /* RxTableViewDataSourceProxy.swift */; }; + D603AA58EF97D461A57B2B1BCB883868 /* AVAssetImageDataProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2123CB53EEEB503948A4474AACCB3C9E /* AVAssetImageDataProvider.swift */; }; + D68527405AA172C43B7F0FA120A02CE8 /* Decode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E373816BBB6C36165EF92E2B027BB44 /* Decode.swift */; }; + D69CF928FC4DDAA1A5D0372E530041DD /* SwitchIfEmpty.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C1B5CC2BA7AEB06BDAFF8440716FF8F /* SwitchIfEmpty.swift */; }; + D709A58FF6A694878122F7D24B4A9913 /* Bag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 57B05CAB9374BE0B393DCBDF166CA277 /* Bag.swift */; }; + D72264C517560E7A2FD582F9D6B4118B /* AnonymousDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = 605A26EBFB5CB5DD153C584A76FCF2AF /* AnonymousDisposable.swift */; }; + D8A4FE44301CF797B3E9655FA9F80FA6 /* _RXObjCRuntime.h in Headers */ = {isa = PBXBuildFile; fileRef = 363D470EA28CDC7BCECB8137F65A2201 /* _RXObjCRuntime.h */; settings = {ATTRIBUTES = (Public, ); }; }; + DAFC6CE6321395CF4523DD66DADBB9BA /* ImageDrawing.swift in Sources */ = {isa = PBXBuildFile; fileRef = A0F720C753C91D9209605C6EF0700D76 /* ImageDrawing.swift */; }; + DBB8088E14A2ADEDB1CD840BAC835267 /* CPListItem+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5CE9357E1A67B25C9FE1F8E09BCB188F /* CPListItem+Kingfisher.swift */; }; + DC854B01B452498F9EAD1C28E7B0DED2 /* CurrentThreadScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4887851A3282354968E9864A4B0F4077 /* CurrentThreadScheduler.swift */; }; + DD724165EF3D8F209BD6EA6EEAA7EA0A /* RxSearchBarDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2233BBABA6487519797C148891EA0BB /* RxSearchBarDelegateProxy.swift */; }; + DD72DC30CF19FFC81AB19CD0B074000D /* ImageDownloader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8310D3804BBCE7E2222FA286EAB90A10 /* ImageDownloader.swift */; }; + DDA352AB1CDF6337CFFD9B10121D645F /* Producer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858C397A6FBC0B0E3D7738867844CC /* Producer.swift */; }; + DDEF2B45CC47E733C9FCCD38F0BF6857 /* UIPickerView+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = B4CF72BD8B8045B24FA6E1809818AA38 /* UIPickerView+Rx.swift */; }; + DE532EF7D50A9CF68587DAD4C1A02BD7 /* FormatIndicatedCacheSerializer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7BA40FE37EBE7C8A2600A0D47E953ADB /* FormatIndicatedCacheSerializer.swift */; }; + DF4563832C19B8582C810BF502A5CA29 /* KF.swift in Sources */ = {isa = PBXBuildFile; fileRef = 969DB90E32B1D987FF5B6A47A8684A36 /* KF.swift */; }; + DF7BD87A7AA4A1D1D0FA7D153CC45150 /* ObserveOn.swift in Sources */ = {isa = PBXBuildFile; fileRef = F965D68950E22ADD709D34E78FA9C631 /* ObserveOn.swift */; }; + DFCDE4638265B4CCD494ECA5D560DBEE /* Indicator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74D47EC0B111D55E1C5BA1EBACDAED47 /* Indicator.swift */; }; + DFD30F96D602E6476B57BB16FF1785D2 /* SharedSequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 16A72B04D50D8F6C820F4A91C64E440F /* SharedSequence.swift */; }; + DFEDD9705BACB387CEB43C55A8D094CB /* ObservableType.swift in Sources */ = {isa = PBXBuildFile; fileRef = A249417112017333EFE8B667A7F7BA29 /* ObservableType.swift */; }; + E014B1AAB0FE20A47556484F4890C2EC /* SkipUntil.swift in Sources */ = {isa = PBXBuildFile; fileRef = 423FC353DC78844A93CB4BE73ABF83B6 /* SkipUntil.swift */; }; + E265565C244D8AB0E9A8DF4A2F71B170 /* ReplayRelay.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF67A85F485522B5F5548FE67FDC2D2E /* ReplayRelay.swift */; }; + E2EE60D641A784A98A937A9DB57C6FBF /* Queue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3449B1ED3620A7995593EDBBB1A8FF36 /* Queue.swift */; }; + E325FBE64C7EAE36B7485D3015719C4D /* RxSwift-umbrella.h in Headers */ = {isa = PBXBuildFile; fileRef = 8F2FD26566A807497EDC01AA580EF703 /* RxSwift-umbrella.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E5B664771063F1A9A372519A8466860B /* ImageView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4E20DD5C3CA00ECE9097F38C59F35FC5 /* ImageView+Kingfisher.swift */; }; + E6A1BF57511CE77AE62E000F61A5F48F /* _RXDelegateProxy.h in Headers */ = {isa = PBXBuildFile; fileRef = 4AD61FFEA9BE7E0D078DE9B5B06826F3 /* _RXDelegateProxy.h */; settings = {ATTRIBUTES = (Public, ); }; }; + E6A207EE08EA44841EBF3E5E6C21E341 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */; }; + E6D6C7D5E458A05CC736C340F853E9F6 /* ImageFormat.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8189375A0C7040CC85F487DF8DDD07F8 /* ImageFormat.swift */; }; + E719A3B025B9DACE693130120BD9B927 /* Accelerate.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 52554E1C9731D5352FDE9E63F8C5466B /* Accelerate.framework */; }; + E80D3EAA0259F3FF3F0F3689A3FB0CAB /* AsyncSubject.swift in Sources */ = {isa = PBXBuildFile; fileRef = B617539948E4DB5E99495236BCDC4C10 /* AsyncSubject.swift */; }; + E85A348CBE05F09872013FEB3BC58260 /* Infallible+CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = DBB37C6077770A848A001B71DD3B61C7 /* Infallible+CombineLatest+arity.swift */; }; + E931DE06D8C8C59EF029F904A1CFFB69 /* Scan.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1D23F5C136F055CF503012DEDD515E92 /* Scan.swift */; }; + EA9A86994FD60ACCBD1BA962A04E5CFD /* SerialDispatchQueueScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE2C2EECA1E2992ECEE36CDDD0D2D4AC /* SerialDispatchQueueScheduler.swift */; }; + EABF745B6F9EC4CC4BDE22085C5BD0AA /* MainScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2CA0B0B9146454EC23A31F2C346DF3E6 /* MainScheduler.swift */; }; + EB276B66D2562F17B084C0D83B9D8F27 /* UISearchBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 42E60FDDEB87F1E0AB28E697D2D7E18C /* UISearchBar+Rx.swift */; }; + EB6F2FDEACD788322B2E28311943E7B7 /* AsSingle.swift in Sources */ = {isa = PBXBuildFile; fileRef = FF6FC2B162B74ED0DF07FF5E553F25AF /* AsSingle.swift */; }; + EBB32304E8DD4BA115454E0050D47DED /* Runtime.swift in Sources */ = {isa = PBXBuildFile; fileRef = 800601AF004FCC2E83F7E9FE2F9FEC22 /* Runtime.swift */; }; + ECBFCBFA5AB28DD7B0981FF11C63A188 /* SingleAsync.swift in Sources */ = {isa = PBXBuildFile; fileRef = 93CF262711162BF6AC485B334DC9B37F /* SingleAsync.swift */; }; + ED0C8BA7560D7324587B353E0960479F /* ImageCache.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1B175696C3EE0E048FA7942F2D65B04 /* ImageCache.swift */; }; + ED8365B521BFF4D70FBFE3FCCFEB3BCD /* Filter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6D9736BF14210970F37A7A776C2C0942 /* Filter.swift */; }; + EE80E1376D7F9E22682AE05EE3054388 /* UITabBar+Rx.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6363D082F4B2E3974215EBBD51813FF2 /* UITabBar+Rx.swift */; }; + EED41045A58EC4616734150746621CCA /* BooleanDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B49892E2C02C5AE916F5B783094249BD /* BooleanDisposable.swift */; }; + EF9C4588CDA85AED8BBCF77451B2A35B /* ImageProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = D3BD5DF969085678D2AD058864789972 /* ImageProcessor.swift */; }; + F059BB2BD4F7B156353739A55AEBE2A3 /* ObservableConvertibleType+Driver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C31E6720EEA23CA54E7215B97271E2CA /* ObservableConvertibleType+Driver.swift */; }; + F17B1F8F2B6580343025237455A29D61 /* TVMonogramView+Kingfisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 666EDC6F462EC56433A275A25AE0A312 /* TVMonogramView+Kingfisher.swift */; }; + F19BCAAD57603E28D9C9902CEA822BAA /* RecursiveLock.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9C935BCECC9A0F510E3678B2DEF96E74 /* RecursiveLock.swift */; }; + F1CA26207E3EE137292D02EF9A752AD2 /* CombineLatest+arity.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEC695C4BAC15CC194BCF9DBE877584E /* CombineLatest+arity.swift */; }; + F1DA873728D70AB358E831F18AF284ED /* RxPickerViewDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = DEC40EF887E88BEE381B6A1C11C227DC /* RxPickerViewDelegateProxy.swift */; }; + F2073564BC492BDE23BFFA81C68E7F01 /* RefCountDisposable.swift in Sources */ = {isa = PBXBuildFile; fileRef = B22B26E71CE50B9005F7DC7A1836C1CB /* RefCountDisposable.swift */; }; + F219C2A0B49D73B93CEC939FEF1E7AB2 /* RxSearchControllerDelegateProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3DA599EFBD1FDCDB6D6514262DB105F5 /* RxSearchControllerDelegateProxy.swift */; }; + F24021BDE9B42D604E3341CAD8E34759 /* GIFAnimatedImage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8783EAE5B7FBAD9F83129629AC9B5D7E /* GIFAnimatedImage.swift */; }; + F387475B1EC3C098254F62698129B612 /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADC3ACC413B1279C66724360A72CA50 /* RxCocoaObjCRuntimeError+Extensions.swift */; }; + F3F9D494D3005899EDCC6CE9A7CF87A1 /* DisposeBag.swift in Sources */ = {isa = PBXBuildFile; fileRef = 76327D49CD25C8AAB3B6D9A0443996E2 /* DisposeBag.swift */; }; + F5414F8A5B40521D0E4AEEB28378CB49 /* ImageContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 95D8F643085C53A1ECEB528A1FEA2DF7 /* ImageContext.swift */; }; + F54DE563418B1783D6EC491A0C3A05DB /* ImageModifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = B14AD7EC93901D8E7BA191534B92A603 /* ImageModifier.swift */; }; + F6E1B45243EF2546837B9099C53770E2 /* RxTableViewReactiveArrayDataSource.swift in Sources */ = {isa = PBXBuildFile; fileRef = 09DE430262BDAAA66289105E0EF31980 /* RxTableViewReactiveArrayDataSource.swift */; }; + F6F9C34492E47A611E31D2D63F476F13 /* ItemEvents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2331321DA7B50BFA00A86FECACFC7850 /* ItemEvents.swift */; }; + F7250640EF71B23A578D47417480240B /* Timeout.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F92350A86AE47AFC761F7D81387757B /* Timeout.swift */; }; + F7C3BDD52B3C9222621025CBD1447E2E /* ToArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E5266CB42414BE09BC701E201C85AAF /* ToArray.swift */; }; + F89C351693522F78C6E85B6AAF7B76C4 /* RxCollectionViewDataSourceType.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99A31E40D67BC43BC1AC643E81E41AF6 /* RxCollectionViewDataSourceType.swift */; }; + F9537B023E24AC4A724E301F7E372491 /* KFImageProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5C2FB870012F9A9F06B36C9892BD2495 /* KFImageProtocol.swift */; }; + FA9FC218B9751BE5A9E9262A57EE9AC8 /* ObservableType+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1F04451837217FD4AE5DFEE23B4CB6B3 /* ObservableType+Extensions.swift */; }; + FC788CC1807407D607BC5102895D31F5 /* HistoricalScheduler.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5E45054A36FFD8A2439E6032FE9CAC4 /* HistoricalScheduler.swift */; }; + FDB6B50F3AF189818D8962D74E37D552 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */ = {isa = PBXBuildFile; fileRef = D658DD511799A6D4218F9B9BB5B5F200 /* RxTableViewDataSourcePrefetchingProxy.swift */; }; + FDD9978BA4D886BA722A68E110F92960 /* Sequence.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA33790E41B94863150898938627F8C9 /* Sequence.swift */; }; + FE28DDABA4223991BF4B39E291899EC1 /* Pods-Nasa-NasaUITests-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 2118DD01B1A6FC92E1E902D1C1A28F66 /* Pods-Nasa-NasaUITests-dummy.m */; }; + FE4011EF34F7ECDF74BD74E5BF6C7BC9 /* Optional.swift in Sources */ = {isa = PBXBuildFile; fileRef = D5FA7C58097A05AAE49FD6F11436E279 /* Optional.swift */; }; + FF09824309346665E2F1F7F5A45FB10F /* CallbackQueue.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1963CF85C64A6FC35B9C305D5FCBDE9 /* CallbackQueue.swift */; }; + FFA38111EFF544C8B04BF95703FD7D62 /* RxRelay-dummy.m in Sources */ = {isa = PBXBuildFile; fileRef = 9787B8B668795376E1710C2864466F71 /* RxRelay-dummy.m */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 0CFE11329CD34D4A0D7050C813DB2BC0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 0D0A4F250EC6A9EEBA45E42EB0C83196 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8022D22FAA6690B5E1C379C1BCE1491; + remoteInfo = Kingfisher; + }; + 263B46AA724788B9C72FF8C7719DF893 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = E8022D22FAA6690B5E1C379C1BCE1491; + remoteInfo = Kingfisher; + }; + 439EBE25AEFBAA5BC20F9099F7C69F1E /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; + 5595B3D223167804FC98397C4536EB89 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; + 6B8D90F2EB61286F0DD4C7DC35A28553 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + AA2A58CC35F58189739CFCB9CB1744F0 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6; + remoteInfo = RxCocoa; + }; + AEDA40EDA5F621AB289E21A5288DEEC5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + B0F42041C2C6D6146329B048A5904ED6 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + D630FA3585DA150E5749E6BF0532AE8F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = F889E6876E3193B7BFC4912BB2571351; + remoteInfo = "Pods-Nasa"; + }; + D7A5EB60227DFFAE59DB6ADB5D194F24 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = EA9EA43B3B503823EE36C60D9C8A865F; + remoteInfo = RxSwift; + }; + E030F31829B5758861A7572EBEB50676 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = BFDFE7DC352907FC980B868725387E98 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 4622BFEF3DC16E8BD15EEFC30D4D0084; + remoteInfo = RxRelay; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 006AD59A1FDED35C1684D1987A01272D /* PublishRelay+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PublishRelay+Signal.swift"; path = "RxCocoa/Traits/Signal/PublishRelay+Signal.swift"; sourceTree = ""; }; + 0121CA18F76DBA229576FE20F51CC20E /* ObservableConvertibleType+Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Infallible.swift"; path = "RxSwift/Traits/Infallible/ObservableConvertibleType+Infallible.swift"; sourceTree = ""; }; + 017D63D87A6E8E266C74671DED987366 /* Disposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposable.swift; path = RxSwift/Disposable.swift; sourceTree = ""; }; + 02D56418189CE2180CD551B09EE03069 /* Storage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Storage.swift; path = Sources/Cache/Storage.swift; sourceTree = ""; }; + 02E99B14DAE00C21F19A5379E03C9F79 /* URLSession+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "URLSession+Rx.swift"; path = "RxCocoa/Foundation/URLSession+Rx.swift"; sourceTree = ""; }; + 035700EF14CCE6A36A07A5D604252056 /* SessionDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDelegate.swift; path = Sources/Networking/SessionDelegate.swift; sourceTree = ""; }; + 038539E8C2329F87853CB519948BE64D /* MemoryStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MemoryStorage.swift; path = Sources/Cache/MemoryStorage.swift; sourceTree = ""; }; + 0397017297B9CF552EDB2CBB2EB4D702 /* KFImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImage.swift; path = Sources/SwiftUI/KFImage.swift; sourceTree = ""; }; + 05A835A78CBC37235B8A9803C4D5C2D1 /* SchedulerServices+Emulation.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerServices+Emulation.swift"; path = "RxSwift/Schedulers/SchedulerServices+Emulation.swift"; sourceTree = ""; }; + 066CAD6EFE30AE8BD17C67089662A828 /* AddRef.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AddRef.swift; path = RxSwift/Observables/AddRef.swift; sourceTree = ""; }; + 066EA749DDAE608EC1C2512673A8CE66 /* UISearchController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchController+Rx.swift"; path = "RxCocoa/iOS/UISearchController+Rx.swift"; sourceTree = ""; }; + 086CB9F323A5A9B4A6BF898353D4E952 /* Using.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Using.swift; path = RxSwift/Observables/Using.swift; sourceTree = ""; }; + 09DE430262BDAAA66289105E0EF31980 /* RxTableViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift; sourceTree = ""; }; + 0A2F3DC44E81F53D72DFFAA215A85B11 /* UISlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISlider+Rx.swift"; path = "RxCocoa/iOS/UISlider+Rx.swift"; sourceTree = ""; }; + 0B800EF9A2F71AC4B18D0F78B55B7F48 /* Pods-Nasa-NasaUITests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Nasa-NasaUITests.modulemap"; sourceTree = ""; }; + 0C2577FC9887D8705C76D78D1C5B985E /* NSControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSControl+Rx.swift"; path = "RxCocoa/macOS/NSControl+Rx.swift"; sourceTree = ""; }; + 0C4B711F5F67AC1D5168CCDA2F79619D /* KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KVORepresentable.swift; path = RxCocoa/Foundation/KVORepresentable.swift; sourceTree = ""; }; + 0D5313A20F617A6A0FFE42F2B9FA8E31 /* Reduce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reduce.swift; path = RxSwift/Observables/Reduce.swift; sourceTree = ""; }; + 0DB55FE8C794B5AA61DC95770B9C14DB /* Pods-Nasa-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Nasa-Info.plist"; sourceTree = ""; }; + 0DC5E11560B6B3A7A08289CB51A77341 /* Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+arity.swift"; path = "RxSwift/Observables/Zip+arity.swift"; sourceTree = ""; }; + 0DDC4DAFE1E58071E663D24DA336250B /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 0EE5D91BA47B0C0B75F882C976E151A3 /* Zip+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Zip+Collection.swift"; path = "RxSwift/Observables/Zip+Collection.swift"; sourceTree = ""; }; + 0F3EFD230ACBFF33D75339D80A4DBCF2 /* PublishRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishRelay.swift; path = RxRelay/PublishRelay.swift; sourceTree = ""; }; + 1160C2BAB6A3EA880AA1801140ED996C /* UITextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextField+Rx.swift"; path = "RxCocoa/iOS/UITextField+Rx.swift"; sourceTree = ""; }; + 11CCB2B8C905F7BB21519F1AC17D356D /* TakeWithPredicate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeWithPredicate.swift; path = RxSwift/Observables/TakeWithPredicate.swift; sourceTree = ""; }; + 11E45EF449E27B13A73285473A5E7B7E /* Do.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Do.swift; path = RxSwift/Observables/Do.swift; sourceTree = ""; }; + 1328BA8F1A85D005BF68F4079DCACA23 /* BehaviorRelay+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "BehaviorRelay+Driver.swift"; path = "RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift"; sourceTree = ""; }; + 13A0DF8765781203921620F29EDB0C14 /* GroupBy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupBy.swift; path = RxSwift/Observables/GroupBy.swift; sourceTree = ""; }; + 13A194DA04F1FAE32DF8451C7EC0397A /* DefaultIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DefaultIfEmpty.swift; path = RxSwift/Observables/DefaultIfEmpty.swift; sourceTree = ""; }; + 141E846C1992FC3B824497B4C31E9283 /* BehaviorSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorSubject.swift; path = RxSwift/Subjects/BehaviorSubject.swift; sourceTree = ""; }; + 14677C8E07CB908238683A17ED1B0ACB /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + 14A111B0125B3332DD41B6A107BC684A /* Image.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Image.swift; path = Sources/Image/Image.swift; sourceTree = ""; }; + 14C07AEFCB83FD479726E58A485E7F8C /* Skip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Skip.swift; path = RxSwift/Observables/Skip.swift; sourceTree = ""; }; + 157AA11C789EA2B3DD909BC67B10C2C3 /* Pods-Nasa-NasaUITests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Nasa-NasaUITests-acknowledgements.markdown"; sourceTree = ""; }; + 1660268DDCE579590238085654AC6112 /* Box.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Box.swift; path = Sources/Utility/Box.swift; sourceTree = ""; }; + 168B034469C3020A01BD7EB19B8C3409 /* DisposeBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBase.swift; path = RxSwift/Disposables/DisposeBase.swift; sourceTree = ""; }; + 168DC811C7106944BF69EDADA98FD6D0 /* Pods-NasaTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-NasaTests.debug.xcconfig"; sourceTree = ""; }; + 16A72B04D50D8F6C820F4A91C64E440F /* SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SharedSequence.swift; path = RxCocoa/Traits/SharedSequence/SharedSequence.swift; sourceTree = ""; }; + 173CCF61D3B200198ED44DBF6E14A6C4 /* KFOptionsSetter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFOptionsSetter.swift; path = Sources/General/KFOptionsSetter.swift; sourceTree = ""; }; + 178FBC0CAD4510CF099006E3D61CED3D /* First.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = First.swift; path = RxSwift/Observables/First.swift; sourceTree = ""; }; + 17D24989F7C78CBD46A2F964A4A8A477 /* Dematerialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Dematerialize.swift; path = RxSwift/Observables/Dematerialize.swift; sourceTree = ""; }; + 18C52394FF76FB38E57C3225739FE247 /* Zip.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Zip.swift; path = RxSwift/Observables/Zip.swift; sourceTree = ""; }; + 190D0B1290B83B5F6C9A62481F5B6539 /* TailRecursiveSink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TailRecursiveSink.swift; path = RxSwift/Observers/TailRecursiveSink.swift; sourceTree = ""; }; + 194DE807E02F7FCF6F24AF3BE9651CA4 /* Sample.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sample.swift; path = RxSwift/Observables/Sample.swift; sourceTree = ""; }; + 19633EC1F09BD3DF99FDB112C14031A0 /* RxRelay.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.debug.xcconfig; sourceTree = ""; }; + 19C61AA1D29DF02DA1DBE6FED144C917 /* Single.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Single.swift; path = RxSwift/Traits/PrimitiveSequence/Single.swift; sourceTree = ""; }; + 1A00EC4EC537E97430E2B41CCA99FD75 /* SynchronizedUnsubscribeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedUnsubscribeType.swift; path = RxSwift/Concurrency/SynchronizedUnsubscribeType.swift; sourceTree = ""; }; + 1AC15CC5C4A22DE8A1AD51D3064CF0C2 /* Pods-Nasa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Nasa.debug.xcconfig"; sourceTree = ""; }; + 1D23F5C136F055CF503012DEDD515E92 /* Scan.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Scan.swift; path = RxSwift/Observables/Scan.swift; sourceTree = ""; }; + 1F04451837217FD4AE5DFEE23B4CB6B3 /* ObservableType+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+Extensions.swift"; path = "RxSwift/ObservableType+Extensions.swift"; sourceTree = ""; }; + 1F5A54A9DA49163C7145C76F8355D1C6 /* ScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItem.swift; path = RxSwift/Schedulers/Internal/ScheduledItem.swift; sourceTree = ""; }; + 1F6A91146050496D447EBB82EA7EB0FA /* Buffer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Buffer.swift; path = RxSwift/Observables/Buffer.swift; sourceTree = ""; }; + 1F89590B2C85F3BD4C81FEBC2F44E282 /* Debounce.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debounce.swift; path = RxSwift/Observables/Debounce.swift; sourceTree = ""; }; + 204DC3001AB65CBF63130DB17A9EC6D2 /* PublishSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PublishSubject.swift; path = RxSwift/Subjects/PublishSubject.swift; sourceTree = ""; }; + 2118DD01B1A6FC92E1E902D1C1A28F66 /* Pods-Nasa-NasaUITests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Nasa-NasaUITests-dummy.m"; sourceTree = ""; }; + 2123CB53EEEB503948A4474AACCB3C9E /* AVAssetImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AVAssetImageDataProvider.swift; path = Sources/General/ImageSource/AVAssetImageDataProvider.swift; sourceTree = ""; }; + 21A69AAF600A098645D61F1F7A7DFD77 /* Observable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Observable.swift; path = RxSwift/Observable.swift; sourceTree = ""; }; + 2331321DA7B50BFA00A86FECACFC7850 /* ItemEvents.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ItemEvents.swift; path = RxCocoa/iOS/Events/ItemEvents.swift; sourceTree = ""; }; + 24115E491FA4BD6A1F000508B25E41C6 /* RxMutableBox.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxMutableBox.swift; path = RxSwift/RxMutableBox.swift; sourceTree = ""; }; + 241691F359B733E2056B8DC609B60F37 /* ControlTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlTarget.swift; path = RxCocoa/Common/ControlTarget.swift; sourceTree = ""; }; + 2444CB36080B3F8C9F26783D03E1EF90 /* ConcurrentDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentDispatchQueueScheduler.swift; path = RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift; sourceTree = ""; }; + 2464C1376934D750B723647A48B6C83F /* ScheduledItemType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledItemType.swift; path = RxSwift/Schedulers/Internal/ScheduledItemType.swift; sourceTree = ""; }; + 253489F1B29D39562DA60549EC7D1056 /* Pods-Nasa-NasaUITests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Nasa-NasaUITests-acknowledgements.plist"; sourceTree = ""; }; + 254D9E505B6D1A753C59BFE304EB1BE1 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 255952E0493402482EF3A6856781EB26 /* NSSlider+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSSlider+Rx.swift"; path = "RxCocoa/macOS/NSSlider+Rx.swift"; sourceTree = ""; }; + 256D1BE267826C7A5B0D21E89829F186 /* ObservableConvertibleType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableConvertibleType.swift; path = RxSwift/ObservableConvertibleType.swift; sourceTree = ""; }; + 261267E349D9BE7E2A6FB40337853A81 /* Pods-NasaTests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-NasaTests"; path = Pods_NasaTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 26E15E018D9EED7F4CE32D7EB7E83DF8 /* UIScrollView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIScrollView+Rx.swift"; path = "RxCocoa/iOS/UIScrollView+Rx.swift"; sourceTree = ""; }; + 26E5FA57DDDD1DFB317C5ED60769E52B /* Sink.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sink.swift; path = RxSwift/Observables/Sink.swift; sourceTree = ""; }; + 276504E06EE445B80BAE0BE356B3747A /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 291802E320980241260B0D9115E0DED8 /* Pods-NasaTests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-NasaTests-Info.plist"; sourceTree = ""; }; + 299B19C83AA437DF51807FF8A0116A15 /* NSObject+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx.swift"; path = "RxCocoa/Foundation/NSObject+Rx.swift"; sourceTree = ""; }; + 2A003EE5E2035D78B7EBC111C3CD1E1C /* Date+Dispatch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Date+Dispatch.swift"; path = "RxSwift/Date+Dispatch.swift"; sourceTree = ""; }; + 2A97390210CBA1BCC3E831A2C79397A4 /* _RX.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RX.h; path = RxCocoa/Runtime/include/_RX.h; sourceTree = ""; }; + 2AA01AD91A96C4A92DC718480BF8E4FB /* RxCollectionViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift; sourceTree = ""; }; + 2AF530F70F556F38DF940D440404373C /* ObservableConvertibleType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift"; sourceTree = ""; }; + 2C273B8A937511063AE9B77E767FAAA5 /* ConnectableObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConnectableObservableType.swift; path = RxSwift/ConnectableObservableType.swift; sourceTree = ""; }; + 2CA0B0B9146454EC23A31F2C346DF3E6 /* MainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = MainScheduler.swift; path = RxSwift/Schedulers/MainScheduler.swift; sourceTree = ""; }; + 2D3C1F7EC6E18E56276BC08423EC09F9 /* Catch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Catch.swift; path = RxSwift/Observables/Catch.swift; sourceTree = ""; }; + 2DBC19243FA5BCBBB47A8134B7CAAD9E /* Pods-NasaTests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-NasaTests-umbrella.h"; sourceTree = ""; }; + 2E005D09C75B7939241EBC3ACF8725EF /* ImageTransition.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageTransition.swift; path = Sources/Image/ImageTransition.swift; sourceTree = ""; }; + 2E0CB6EFC6AEA4550CC2852CC870C571 /* RxRelay-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-prefix.pch"; sourceTree = ""; }; + 2F60DF6BE39EB76887AA7E118E700A41 /* RxPickerViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift; sourceTree = ""; }; + 2FDAEF959C217E3AAE4B7E563231E365 /* _RX.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RX.m; path = RxCocoa/Runtime/_RX.m; sourceTree = ""; }; + 300289A8F4020601668E8504FE6E00C4 /* AnyObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnyObserver.swift; path = RxSwift/AnyObserver.swift; sourceTree = ""; }; + 309A7B348C7A018E85DBA902D455347F /* UIButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Kingfisher.swift"; path = "Sources/Extensions/UIButton+Kingfisher.swift"; sourceTree = ""; }; + 313CBC199D9C144DC0550B1BBAAE89F3 /* SharedSequence+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift"; sourceTree = ""; }; + 31EFB9EE3C11EADCE4C7DB67CFD4308D /* ControlEvent+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlEvent+Driver.swift"; sourceTree = ""; }; + 32467DC6BA07C61A2C55C6C511829800 /* RxCocoa-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxCocoa-Info.plist"; sourceTree = ""; }; + 32630B4842C76B01267DF03C2B356519 /* Pods-NasaTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-NasaTests.release.xcconfig"; sourceTree = ""; }; + 32D5973F5B6BE2FD9D6862829F3341B9 /* UINavigationController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UINavigationController+Rx.swift"; path = "RxCocoa/iOS/UINavigationController+Rx.swift"; sourceTree = ""; }; + 32ED16D862E2C699D96329A575941E33 /* RxCocoa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.release.xcconfig; sourceTree = ""; }; + 3449B1ED3620A7995593EDBBB1A8FF36 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 347B29F2635F01233990E9C245FA1DC2 /* Queue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Queue.swift; path = Platform/DataStructures/Queue.swift; sourceTree = ""; }; + 3559CF60499726E5518704F3352488AD /* SynchronizedOnType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedOnType.swift; path = RxSwift/Concurrency/SynchronizedOnType.swift; sourceTree = ""; }; + 363D470EA28CDC7BCECB8137F65A2201 /* _RXObjCRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXObjCRuntime.h; path = RxCocoa/Runtime/include/_RXObjCRuntime.h; sourceTree = ""; }; + 365683D075B5D9565B5FF3C8C946E3BB /* Kingfisher.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = Kingfisher.modulemap; sourceTree = ""; }; + 3742D4F3A812DEDA45D7587BFA16A37A /* ReplaySubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplaySubject.swift; path = RxSwift/Subjects/ReplaySubject.swift; sourceTree = ""; }; + 38732C512E987D0D3209963CDA609519 /* Resource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Resource.swift; path = Sources/General/ImageSource/Resource.swift; sourceTree = ""; }; + 38B418820BDE7F9EAB6033E95EF2DD39 /* KingfisherManager.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherManager.swift; path = Sources/General/KingfisherManager.swift; sourceTree = ""; }; + 39169A0D9A36E134D5B402DFDE82C77E /* UISegmentedControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISegmentedControl+Rx.swift"; path = "RxCocoa/iOS/UISegmentedControl+Rx.swift"; sourceTree = ""; }; + 3B64D3B6DCACA3245426B3DCC4CBEF4E /* ControlEvent+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlEvent+Signal.swift"; path = "RxCocoa/Traits/Signal/ControlEvent+Signal.swift"; sourceTree = ""; }; + 3CD1DB6F70625F317E2AAE03A05BB56F /* BinaryDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BinaryDisposable.swift; path = RxSwift/Disposables/BinaryDisposable.swift; sourceTree = ""; }; + 3DA599EFBD1FDCDB6D6514262DB105F5 /* RxSearchControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift; sourceTree = ""; }; + 3DC4726BFD306141702DA64D7CA622A0 /* Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Rx.swift; path = RxSwift/Rx.swift; sourceTree = ""; }; + 3DD6FFD079EF8A2DDE25C35353EBD004 /* ObserverBase.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverBase.swift; path = RxSwift/Observers/ObserverBase.swift; sourceTree = ""; }; + 3E514D961A1E4FF8A88B9A696859CEF8 /* Utils.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Utils.swift; path = RxRelay/Utils.swift; sourceTree = ""; }; + 3E6679A12C19FCB8C599445AC992D79E /* WKWebView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKWebView+Rx.swift"; path = "RxCocoa/iOS/WKWebView+Rx.swift"; sourceTree = ""; }; + 3EEF33A950F5444D1A6C3863129551A6 /* Take.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Take.swift; path = RxSwift/Observables/Take.swift; sourceTree = ""; }; + 3F24826DDE7D64BFC7A0BCA4DF3B6978 /* RxWKNavigationDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxWKNavigationDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift; sourceTree = ""; }; + 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Foundation.framework; sourceTree = DEVELOPER_DIR; }; + 4224FF8BA20495FDD3B5C29557D3B96A /* SingleAssignmentDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAssignmentDisposable.swift; path = RxSwift/Disposables/SingleAssignmentDisposable.swift; sourceTree = ""; }; + 423FC353DC78844A93CB4BE73ABF83B6 /* SkipUntil.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipUntil.swift; path = RxSwift/Observables/SkipUntil.swift; sourceTree = ""; }; + 42C98E9C3712ADEC843BB1445B0B79DD /* RetryStrategy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryStrategy.swift; path = Sources/Networking/RetryStrategy.swift; sourceTree = ""; }; + 42E60FDDEB87F1E0AB28E697D2D7E18C /* UISearchBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISearchBar+Rx.swift"; path = "RxCocoa/iOS/UISearchBar+Rx.swift"; sourceTree = ""; }; + 45DA6997549500684C8FDCAD08448041 /* KingfisherError.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherError.swift; path = Sources/General/KingfisherError.swift; sourceTree = ""; }; + 46557E1582E320EB12560AA106A3EF3F /* NSTextStorage+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextStorage+Rx.swift"; path = "RxCocoa/iOS/NSTextStorage+Rx.swift"; sourceTree = ""; }; + 47BAF640636860171656B4A3BE35179B /* Throttle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Throttle.swift; path = RxSwift/Observables/Throttle.swift; sourceTree = ""; }; + 47D9D6FB3FB7EB503D7A85011FA19A8C /* PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PrimitiveSequence.swift; path = RxSwift/Traits/PrimitiveSequence/PrimitiveSequence.swift; sourceTree = ""; }; + 487016C43A9C696EF689DB1E07400631 /* Infallible.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Infallible.swift; path = RxSwift/Traits/Infallible/Infallible.swift; sourceTree = ""; }; + 4887851A3282354968E9864A4B0F4077 /* CurrentThreadScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CurrentThreadScheduler.swift; path = RxSwift/Schedulers/CurrentThreadScheduler.swift; sourceTree = ""; }; + 4AD61FFEA9BE7E0D078DE9B5B06826F3 /* _RXDelegateProxy.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXDelegateProxy.h; path = RxCocoa/Runtime/include/_RXDelegateProxy.h; sourceTree = ""; }; + 4BA2EBCF6C82576ECF70AB7D5052288C /* ImageProgressive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProgressive.swift; path = Sources/Image/ImageProgressive.swift; sourceTree = ""; }; + 4C70F8841D47B6108745F20EAF1B7319 /* KFImageRenderer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageRenderer.swift; path = Sources/SwiftUI/KFImageRenderer.swift; sourceTree = ""; }; + 4C7D77586C026EBDD88A96FFC838083C /* KVORepresentable+Swift.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+Swift.swift"; path = "RxCocoa/Foundation/KVORepresentable+Swift.swift"; sourceTree = ""; }; + 4E20DD5C3CA00ECE9097F38C59F35FC5 /* ImageView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ImageView+Kingfisher.swift"; path = "Sources/Extensions/ImageView+Kingfisher.swift"; sourceTree = ""; }; + 4EC0E80CF040EEF1CEEF6C403832653D /* AnonymousObserver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousObserver.swift; path = RxSwift/Observers/AnonymousObserver.swift; sourceTree = ""; }; + 4FC25F6C3C493911AFC553ED0B080E71 /* ShareReplayScope.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ShareReplayScope.swift; path = RxSwift/Observables/ShareReplayScope.swift; sourceTree = ""; }; + 509BFA3A2F815D66AE5490E0D9B15E5C /* DelaySubscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelaySubscription.swift; path = RxSwift/Observables/DelaySubscription.swift; sourceTree = ""; }; + 5141B34991C273AA0F55C8B9C9BAA501 /* UIButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIButton+Rx.swift"; path = "RxCocoa/iOS/UIButton+Rx.swift"; sourceTree = ""; }; + 52554E1C9731D5352FDE9E63F8C5466B /* Accelerate.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Accelerate.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/Accelerate.framework; sourceTree = DEVELOPER_DIR; }; + 52AC685178073CE2C546491DC631D838 /* UIRefreshControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIRefreshControl+Rx.swift"; path = "RxCocoa/iOS/UIRefreshControl+Rx.swift"; sourceTree = ""; }; + 53CAB4283845A13ABA4F3657A92430AE /* Never.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Never.swift; path = RxSwift/Observables/Never.swift; sourceTree = ""; }; + 54CA1986B4B7E04F0B4124B8C0B1515D /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + 551E9EDABFE6F6C3985087A678D24DD3 /* RxTableViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift; sourceTree = ""; }; + 5645B2FDDA74EFD8B513313430E182DB /* RxTableViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift; sourceTree = ""; }; + 56D4E7ECD516A37F2AEE8978B3B5DF76 /* Pods-Nasa-NasaUITests-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Nasa-NasaUITests-umbrella.h"; sourceTree = ""; }; + 56EEDAC142A8697D3F3369C0CB954CE7 /* RxRelay.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxRelay.release.xcconfig; sourceTree = ""; }; + 573926B12A41731C6B0AAA5F1394ACF7 /* ObservableConvertibleType+Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Signal.swift"; path = "RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift"; sourceTree = ""; }; + 57B05CAB9374BE0B393DCBDF166CA277 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + 57C02CC9D716ABE836FC698744C40162 /* DelegateProxyType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxyType.swift; path = RxCocoa/Common/DelegateProxyType.swift; sourceTree = ""; }; + 58DF78FBCC8D025608AFCDB64E94B7F6 /* Multicast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Multicast.swift; path = RxSwift/Observables/Multicast.swift; sourceTree = ""; }; + 593DACEE9DD963E86B9A4C9355EC9529 /* DispatchQueueConfiguration.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DispatchQueueConfiguration.swift; path = RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift; sourceTree = ""; }; + 594877CA38F712D12ED1A3BFBBEB35F4 /* GraphicsContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GraphicsContext.swift; path = Sources/Image/GraphicsContext.swift; sourceTree = ""; }; + 5A47D822D952110CECC562981840EAEE /* Bag+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Bag+Rx.swift"; path = "RxSwift/Extensions/Bag+Rx.swift"; sourceTree = ""; }; + 5B026EECB48C75BB8D4373B876D5D757 /* NSButton+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Kingfisher.swift"; path = "Sources/Extensions/NSButton+Kingfisher.swift"; sourceTree = ""; }; + 5C2FB870012F9A9F06B36C9892BD2495 /* KFImageProtocol.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageProtocol.swift; path = Sources/SwiftUI/KFImageProtocol.swift; sourceTree = ""; }; + 5CE33896B5F0FA3F4B2DE04BBED0806C /* SizeExtensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SizeExtensions.swift; path = Sources/Utility/SizeExtensions.swift; sourceTree = ""; }; + 5CE9357E1A67B25C9FE1F8E09BCB188F /* CPListItem+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CPListItem+Kingfisher.swift"; path = "Sources/Extensions/CPListItem+Kingfisher.swift"; sourceTree = ""; }; + 5D5B9644894C489A87BE27ABAD388DE8 /* Infallible+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Zip+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+Zip+arity.swift"; sourceTree = ""; }; + 5F19834A1B62B273FB9DE568FB7B1D19 /* CombineLatest+Collection.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+Collection.swift"; path = "RxSwift/Observables/CombineLatest+Collection.swift"; sourceTree = ""; }; + 605A26EBFB5CB5DD153C584A76FCF2AF /* AnonymousDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnonymousDisposable.swift; path = RxSwift/Disposables/AnonymousDisposable.swift; sourceTree = ""; }; + 6077A495BA175BE283E5433B37F9CB7C /* TakeLast.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TakeLast.swift; path = RxSwift/Observables/TakeLast.swift; sourceTree = ""; }; + 61D85AF8FA6907C8221FFE1E3C7567A4 /* RxRelay.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxRelay.modulemap; sourceTree = ""; }; + 631FC8F669F041C47F44CB1BAC72887C /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 6363D082F4B2E3974215EBBD51813FF2 /* UITabBar+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBar+Rx.swift"; path = "RxCocoa/iOS/UITabBar+Rx.swift"; sourceTree = ""; }; + 659C95F6167047A371AE813DDE268CED /* NSObject+Rx+KVORepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+KVORepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift"; sourceTree = ""; }; + 65DAAE0320F729A067CD23F6A910069A /* RxPickerViewDataSourceProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDataSourceProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift; sourceTree = ""; }; + 665C9746CC0234EFDDEBB59D0A6200AF /* InfiniteSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InfiniteSequence.swift; path = Platform/DataStructures/InfiniteSequence.swift; sourceTree = ""; }; + 666EDC6F462EC56433A275A25AE0A312 /* TVMonogramView+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "TVMonogramView+Kingfisher.swift"; path = "Sources/Extensions/TVMonogramView+Kingfisher.swift"; sourceTree = ""; }; + 671F3730AFF17DD82C3672D14F4D8D10 /* NSTextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextView+Rx.swift"; path = "RxCocoa/macOS/NSTextView+Rx.swift"; sourceTree = ""; }; + 67591D311B21307172FABF417357CEC1 /* NSView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSView+Rx.swift"; path = "RxCocoa/macOS/NSView+Rx.swift"; sourceTree = ""; }; + 689BA627F03E170B29DF442DCBE59791 /* Pods-Nasa-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-Nasa-acknowledgements.markdown"; sourceTree = ""; }; + 68C563B3EFD584330BB6C2F9AF354DFA /* Pods-Nasa-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Nasa-frameworks.sh"; sourceTree = ""; }; + 6990B2F815BED4524E85E6D963A49D0A /* Pods-Nasa-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Nasa-acknowledgements.plist"; sourceTree = ""; }; + 6B35C4107E8F589E3345F787F1A1F303 /* Switch.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Switch.swift; path = RxSwift/Observables/Switch.swift; sourceTree = ""; }; + 6C32BE0FBF23366538EC38133C3B4761 /* ControlProperty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlProperty.swift; path = RxCocoa/Traits/ControlProperty.swift; sourceTree = ""; }; + 6C8DE69DEBEF6E67F64F0F670A5C73E4 /* RxCocoa.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxCocoa.modulemap; sourceTree = ""; }; + 6CA18C31ED77D7EA8DCE74634CBF93DA /* Infallible+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Bind.swift"; path = "RxCocoa/Common/Infallible+Bind.swift"; sourceTree = ""; }; + 6CF11E4E091F4DF262DBF2E02B8339EB /* Signal+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Signal+Subscription.swift"; path = "RxCocoa/Traits/Signal/Signal+Subscription.swift"; sourceTree = ""; }; + 6D9736BF14210970F37A7A776C2C0942 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = RxSwift/Observables/Filter.swift; sourceTree = ""; }; + 6E373816BBB6C36165EF92E2B027BB44 /* Decode.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Decode.swift; path = RxSwift/Observables/Decode.swift; sourceTree = ""; }; + 6F92350A86AE47AFC761F7D81387757B /* Timeout.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timeout.swift; path = RxSwift/Observables/Timeout.swift; sourceTree = ""; }; + 711A1FB5D3CEBDB29D84C91569DBC787 /* _RXObjCRuntime.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXObjCRuntime.m; path = RxCocoa/Runtime/_RXObjCRuntime.m; sourceTree = ""; }; + 72807B39E40B38A0B9BF0FE82115D701 /* NSObject+Rx+RawRepresentable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSObject+Rx+RawRepresentable.swift"; path = "RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift"; sourceTree = ""; }; + 72CD3A7E60C3A4A7E20AEBE4D9F79954 /* VirtualTimeScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeScheduler.swift; path = RxSwift/Schedulers/VirtualTimeScheduler.swift; sourceTree = ""; }; + 731DA7559774054AC732C32D2D466D36 /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxCocoa/Common/Observable+Bind.swift"; sourceTree = ""; }; + 73282384CDDE200004F6A2A982D8F9C0 /* RequestModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RequestModifier.swift; path = Sources/Networking/RequestModifier.swift; sourceTree = ""; }; + 74611FF6E108D51044FDACBEDCEA272C /* Platform.Linux.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Linux.swift; path = Platform/Platform.Linux.swift; sourceTree = ""; }; + 74858C397A6FBC0B0E3D7738867844CC /* Producer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Producer.swift; path = RxSwift/Observables/Producer.swift; sourceTree = ""; }; + 74D47EC0B111D55E1C5BA1EBACDAED47 /* Indicator.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Indicator.swift; path = Sources/Views/Indicator.swift; sourceTree = ""; }; + 753CD1C6CC020253A407CE3A8E5EB836 /* AuthenticationChallengeResponsable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AuthenticationChallengeResponsable.swift; path = Sources/Networking/AuthenticationChallengeResponsable.swift; sourceTree = ""; }; + 75567979F42C7049A3177B96B09F1FD1 /* Signal.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Signal.swift; path = RxCocoa/Traits/Signal/Signal.swift; sourceTree = ""; }; + 76327D49CD25C8AAB3B6D9A0443996E2 /* DisposeBag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DisposeBag.swift; path = RxSwift/Disposables/DisposeBag.swift; sourceTree = ""; }; + 7638CD1C41EA2C2D4C359A360E13A543 /* RxSwift-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxSwift-dummy.m"; sourceTree = ""; }; + 765DADAEB790057019DB04648364475A /* ControlEvent.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ControlEvent.swift; path = RxCocoa/Traits/ControlEvent.swift; sourceTree = ""; }; + 76F6B571F692833993F0EE21BBBD5B33 /* SchedulerType+SharedSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SchedulerType+SharedSequence.swift"; path = "RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift"; sourceTree = ""; }; + 770F21ADC933DC7B515BE3B743647A1B /* UIDatePicker+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIDatePicker+Rx.swift"; path = "RxCocoa/iOS/UIDatePicker+Rx.swift"; sourceTree = ""; }; + 78B54A567196097C12B5651EB5CAE227 /* ImageDownloaderDelegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloaderDelegate.swift; path = Sources/Networking/ImageDownloaderDelegate.swift; sourceTree = ""; }; + 78BBC08AB3F71A56C70C1D83460673B1 /* RetryWhen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RetryWhen.swift; path = RxSwift/Observables/RetryWhen.swift; sourceTree = ""; }; + 78DBB9BD0602DF88C96C8874E26D0C27 /* _RXKVOObserver.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = _RXKVOObserver.h; path = RxCocoa/Runtime/include/_RXKVOObserver.h; sourceTree = ""; }; + 79A4AC560B432B2A9F0D7F8562BA173D /* Kingfisher-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Kingfisher-dummy.m"; sourceTree = ""; }; + 79D816301584854A2E79BDCABB77D889 /* Pods-Nasa.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-Nasa.modulemap"; sourceTree = ""; }; + 7A1C2B0C119BAFB3E2F50B4DC1622CB8 /* Pods-Nasa.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Nasa.release.xcconfig"; sourceTree = ""; }; + 7A75B8072A89388F54D328CC33074C05 /* KingfisherOptionsInfo.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KingfisherOptionsInfo.swift; path = Sources/General/KingfisherOptionsInfo.swift; sourceTree = ""; }; + 7B243EFB97DCFEC58BFD68592BE69E99 /* RxTabBarControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift; sourceTree = ""; }; + 7B38A37EDADBCE6A4E37BDA273C433F8 /* RxCocoa.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxCocoa.debug.xcconfig; sourceTree = ""; }; + 7BA40FE37EBE7C8A2600A0D47E953ADB /* FormatIndicatedCacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = FormatIndicatedCacheSerializer.swift; path = Sources/Cache/FormatIndicatedCacheSerializer.swift; sourceTree = ""; }; + 7C1C444C537BD2AF05A4C03C1F164B81 /* Filter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Filter.swift; path = Sources/Image/Filter.swift; sourceTree = ""; }; + 7CD2494752BF402630EBF199135EBDF7 /* WKInterfaceImage+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "WKInterfaceImage+Kingfisher.swift"; path = "Sources/Extensions/WKInterfaceImage+Kingfisher.swift"; sourceTree = ""; }; + 7DD04BCB8E9C26011C133ED0222369CB /* Lock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Lock.swift; path = RxSwift/Concurrency/Lock.swift; sourceTree = ""; }; + 7DF5F64075BE015B0E4A94A4D723C953 /* Merge.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Merge.swift; path = RxSwift/Observables/Merge.swift; sourceTree = ""; }; + 7ED2066564452073563FAFF29121A419 /* UIStepper+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIStepper+Rx.swift"; path = "RxCocoa/iOS/UIStepper+Rx.swift"; sourceTree = ""; }; + 800601AF004FCC2E83F7E9FE2F9FEC22 /* Runtime.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Runtime.swift; path = Sources/Utility/Runtime.swift; sourceTree = ""; }; + 80196883EA6E29278366559EFB614235 /* Enumerated.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Enumerated.swift; path = RxSwift/Observables/Enumerated.swift; sourceTree = ""; }; + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxSwift; path = RxSwift.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 8189375A0C7040CC85F487DF8DDD07F8 /* ImageFormat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageFormat.swift; path = Sources/Image/ImageFormat.swift; sourceTree = ""; }; + 8310D3804BBCE7E2222FA286EAB90A10 /* ImageDownloader.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDownloader.swift; path = Sources/Networking/ImageDownloader.swift; sourceTree = ""; }; + 836FA04B8B9B8C930387B9ACAC062972 /* RxCollectionViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift; sourceTree = ""; }; + 8437ED9F010236021ADDEEF3979217FE /* Pods-NasaTests.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = "Pods-NasaTests.modulemap"; sourceTree = ""; }; + 846DDB743B7772FECA5E9D40134868B5 /* AnimatedImageView.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AnimatedImageView.swift; path = Sources/Views/AnimatedImageView.swift; sourceTree = ""; }; + 86DD172B182805841A3A2061759B42D9 /* NSButton+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSButton+Rx.swift"; path = "RxCocoa/macOS/NSButton+Rx.swift"; sourceTree = ""; }; + 872D7EFA572ECEE8EF993C27196E16DD /* CFNetwork.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CFNetwork.framework; path = Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS14.0.sdk/System/Library/Frameworks/CFNetwork.framework; sourceTree = DEVELOPER_DIR; }; + 877C6EC3C797F8A700D0FF9EAF958D19 /* VirtualTimeConverterType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = VirtualTimeConverterType.swift; path = RxSwift/Schedulers/VirtualTimeConverterType.swift; sourceTree = ""; }; + 8783EAE5B7FBAD9F83129629AC9B5D7E /* GIFAnimatedImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GIFAnimatedImage.swift; path = Sources/Image/GIFAnimatedImage.swift; sourceTree = ""; }; + 87E9B0EC98D89A8043AA03EBF3AADF89 /* Cancelable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Cancelable.swift; path = RxSwift/Cancelable.swift; sourceTree = ""; }; + 87EE52438F504132352D1A803B540129 /* RedirectHandler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RedirectHandler.swift; path = Sources/Networking/RedirectHandler.swift; sourceTree = ""; }; + 87FE5AE82D1B317B99D0BBC417C13EA5 /* Binder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Binder.swift; path = RxSwift/Binder.swift; sourceTree = ""; }; + 880411AA04678912F31750B286549944 /* UIActivityIndicatorView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIActivityIndicatorView+Rx.swift"; path = "RxCocoa/iOS/UIActivityIndicatorView+Rx.swift"; sourceTree = ""; }; + 8976B65457E61E8AD7899E4D740FDDBF /* NSTextAttachment+Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextAttachment+Kingfisher.swift"; path = "Sources/Extensions/NSTextAttachment+Kingfisher.swift"; sourceTree = ""; }; + 89D58D454E656EB201E21C9EF37A70E6 /* SubscribeOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscribeOn.swift; path = RxSwift/Observables/SubscribeOn.swift; sourceTree = ""; }; + 8A3A20480CFDF96D43D7E6857FBEA137 /* Kingfisher.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.release.xcconfig; sourceTree = ""; }; + 8A77EA2F4CBF8F9530A462A4AA2C5489 /* ImageBinder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageBinder.swift; path = Sources/SwiftUI/ImageBinder.swift; sourceTree = ""; }; + 8AB1B319B15ADC03FE14A5722C666C97 /* UICollectionView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UICollectionView+Rx.swift"; path = "RxCocoa/iOS/UICollectionView+Rx.swift"; sourceTree = ""; }; + 8B2AC97752DBF56A8D836C63942A6ACB /* ConcurrentMainScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ConcurrentMainScheduler.swift; path = RxSwift/Schedulers/ConcurrentMainScheduler.swift; sourceTree = ""; }; + 8BAD8AFCC4A45BB686B716BE51FBB9C5 /* KFImageOptions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFImageOptions.swift; path = Sources/SwiftUI/KFImageOptions.swift; sourceTree = ""; }; + 8D54F3EFCD78F700D10C91447B6D7923 /* RxTableViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift; sourceTree = ""; }; + 8DECDBB7D351E4436AFF57C154B6D604 /* SwiftSupport.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwiftSupport.swift; path = RxSwift/SwiftSupport/SwiftSupport.swift; sourceTree = ""; }; + 8E278B10D48A31495A483A772250AF3F /* WithLatestFrom.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithLatestFrom.swift; path = RxSwift/Observables/WithLatestFrom.swift; sourceTree = ""; }; + 8E5266CB42414BE09BC701E201C85AAF /* ToArray.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ToArray.swift; path = RxSwift/Observables/ToArray.swift; sourceTree = ""; }; + 8E55E337DAF3B45894CF50E3D4D83EC9 /* RxTabBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTabBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift; sourceTree = ""; }; + 8ECFDDF445685ACA15D40D07E6CC60CF /* AsMaybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsMaybe.swift; path = RxSwift/Observables/AsMaybe.swift; sourceTree = ""; }; + 8F2FD26566A807497EDC01AA580EF703 /* RxSwift-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-umbrella.h"; sourceTree = ""; }; + 90BCDFDC98BBC5BC4011B4BD2767E409 /* Pods-Nasa-NasaUITests-frameworks.sh */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.script.sh; path = "Pods-Nasa-NasaUITests-frameworks.sh"; sourceTree = ""; }; + 90DFD528941DB2E45A03A9B1FA741E64 /* Materialize.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Materialize.swift; path = RxSwift/Observables/Materialize.swift; sourceTree = ""; }; + 917D5B05E05F1095E9C9666C8A87701F /* RxSwift.modulemap */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.module; path = RxSwift.modulemap; sourceTree = ""; }; + 9204F68E3EC8D088420BE817820C9224 /* ElementAt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ElementAt.swift; path = RxSwift/Observables/ElementAt.swift; sourceTree = ""; }; + 930C79BF985FF7032A75C1449AB1A9C9 /* Kingfisher-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Kingfisher-Info.plist"; sourceTree = ""; }; + 9384A9D594BA0B3ABADCA346461AE61E /* ScheduledDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ScheduledDisposable.swift; path = RxSwift/Disposables/ScheduledDisposable.swift; sourceTree = ""; }; + 93CF262711162BF6AC485B334DC9B37F /* SingleAsync.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SingleAsync.swift; path = RxSwift/Observables/SingleAsync.swift; sourceTree = ""; }; + 93D1A993428B6200A1864B6895B46059 /* Deferred.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Deferred.swift; path = RxSwift/Observables/Deferred.swift; sourceTree = ""; }; + 93FA7D29AAB8705F01F5B0D66AD537E5 /* Range.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Range.swift; path = RxSwift/Observables/Range.swift; sourceTree = ""; }; + 942E6CE9A41E65156A28227D9167A46B /* RxSwift-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxSwift-Info.plist"; sourceTree = ""; }; + 95AE13711B328E40447B5559B99BF4C4 /* RxRelay-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "RxRelay-Info.plist"; sourceTree = ""; }; + 95D8F643085C53A1ECEB528A1FEA2DF7 /* ImageContext.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageContext.swift; path = Sources/SwiftUI/ImageContext.swift; sourceTree = ""; }; + 96668307975A303706F47C0B9A0BDA32 /* CombineLatest.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CombineLatest.swift; path = RxSwift/Observables/CombineLatest.swift; sourceTree = ""; }; + 96770B0B10FC006B31FA2E9FF84EE421 /* Pods-Nasa */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-Nasa"; path = Pods_Nasa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 969DB90E32B1D987FF5B6A47A8684A36 /* KF.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KF.swift; path = Sources/General/KF.swift; sourceTree = ""; }; + 9718ADF3B40EBC380D55C19C95DEEB2D /* TextInput.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = TextInput.swift; path = RxCocoa/Common/TextInput.swift; sourceTree = ""; }; + 9787B8B668795376E1710C2864466F71 /* RxRelay-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxRelay-dummy.m"; sourceTree = ""; }; + 979FABB5D4BD34FCD495B3AC7A02A963 /* RxSwift-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxSwift-prefix.pch"; sourceTree = ""; }; + 97B5A42988E1A0A9D562043D29D13732 /* GroupedObservable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = GroupedObservable.swift; path = RxSwift/GroupedObservable.swift; sourceTree = ""; }; + 981D9449308470332443FF6AEEA4BD3E /* Window.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Window.swift; path = RxSwift/Observables/Window.swift; sourceTree = ""; }; + 9852B9017511004032B9FF1F04C8A653 /* RxCocoa-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "RxCocoa-dummy.m"; sourceTree = ""; }; + 991A2A3F38D320429C0AF533CCC1A2DA /* NSTextField+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NSTextField+Rx.swift"; path = "RxCocoa/macOS/NSTextField+Rx.swift"; sourceTree = ""; }; + 99A31E40D67BC43BC1AC643E81E41AF6 /* RxCollectionViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourceType.swift; path = RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift; sourceTree = ""; }; + 9BE0B00707E6FF026FD1C832618D8245 /* UIGestureRecognizer+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIGestureRecognizer+Rx.swift"; path = "RxCocoa/iOS/UIGestureRecognizer+Rx.swift"; sourceTree = ""; }; + 9C1B5CC2BA7AEB06BDAFF8440716FF8F /* SwitchIfEmpty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SwitchIfEmpty.swift; path = RxSwift/Observables/SwitchIfEmpty.swift; sourceTree = ""; }; + 9C56FDD70B5E9F43C3796E6AB1585BEE /* Repeat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Repeat.swift; path = RxSwift/Observables/Repeat.swift; sourceTree = ""; }; + 9C935BCECC9A0F510E3678B2DEF96E74 /* RecursiveLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveLock.swift; path = Platform/RecursiveLock.swift; sourceTree = ""; }; + 9CF06B6FBB5DBB1F4D6D0739F0346BE6 /* SectionedViewDataSourceType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SectionedViewDataSourceType.swift; path = RxCocoa/Common/SectionedViewDataSourceType.swift; sourceTree = ""; }; + 9D4E24F8810B9D1C4F328503EFC58863 /* UITextView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITextView+Rx.swift"; path = "RxCocoa/iOS/UITextView+Rx.swift"; sourceTree = ""; }; + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */ = {isa = PBXFileReference; explicitFileType = text.script.ruby; includeInIndex = 1; indentWidth = 2; lastKnownFileType = text; name = Podfile; path = ../Podfile; sourceTree = SOURCE_ROOT; tabWidth = 2; xcLanguageSpecificationIdentifier = xcode.lang.ruby; }; + 9DBE86666C4C7C00176BD62714FC2B60 /* PriorityQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = PriorityQueue.swift; path = Platform/DataStructures/PriorityQueue.swift; sourceTree = ""; }; + 9E5B11A6C7AA615DB9480FA1ECE82D98 /* Bag.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Bag.swift; path = Platform/DataStructures/Bag.swift; sourceTree = ""; }; + 9E99D160193CCBB23FC861A1641D07DA /* SchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SchedulerType.swift; path = RxSwift/SchedulerType.swift; sourceTree = ""; }; + A09EBD7676C0F16F630021DEB6C615D4 /* SynchronizedDisposeType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SynchronizedDisposeType.swift; path = RxSwift/Concurrency/SynchronizedDisposeType.swift; sourceTree = ""; }; + A0F720C753C91D9209605C6EF0700D76 /* ImageDrawing.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDrawing.swift; path = Sources/Image/ImageDrawing.swift; sourceTree = ""; }; + A14E61A58E8566B4B358AD4CB44FCFB3 /* UITabBarController+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITabBarController+Rx.swift"; path = "RxCocoa/iOS/UITabBarController+Rx.swift"; sourceTree = ""; }; + A1E2761EE1212BC4BB8E539BC93D7842 /* RxPickerViewAdapter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewAdapter.swift; path = RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift; sourceTree = ""; }; + A249417112017333EFE8B667A7F7BA29 /* ObservableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObservableType.swift; path = RxSwift/ObservableType.swift; sourceTree = ""; }; + A29091995433007CC3BDB7701C59607B /* Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Driver.swift; path = RxCocoa/Traits/Driver/Driver.swift; sourceTree = ""; }; + A2E2CDC3BC75BD1863C73AA5362FD273 /* NotificationCenter+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "NotificationCenter+Rx.swift"; path = "RxCocoa/Foundation/NotificationCenter+Rx.swift"; sourceTree = ""; }; + A4026CC76C5C4D10BB5E1621462E50F0 /* Errors.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Errors.swift; path = RxSwift/Errors.swift; sourceTree = ""; }; + A44DE42418669BA60C6BFDC99A41FF77 /* WithUnretained.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = WithUnretained.swift; path = RxSwift/Observables/WithUnretained.swift; sourceTree = ""; }; + A5950202FDF9773C66FA3213D36FD1C5 /* Concat.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Concat.swift; path = RxSwift/Observables/Concat.swift; sourceTree = ""; }; + A887DFD8B864789ABC116EA35FECBD49 /* UIControl+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIControl+Rx.swift"; path = "RxCocoa/iOS/UIControl+Rx.swift"; sourceTree = ""; }; + A935D27A5DA9A4B25D2649B10D85666C /* Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Create.swift; path = RxSwift/Observables/Create.swift; sourceTree = ""; }; + A9FE34A16F0C6916FF506BA129C5B821 /* Pods-Nasa-NasaUITests */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = "Pods-Nasa-NasaUITests"; path = Pods_Nasa_NasaUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + AA089C793A7294C12FC5B8F5C501B129 /* Disposables.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Disposables.swift; path = RxSwift/Disposables/Disposables.swift; sourceTree = ""; }; + AA91BB1404869D1480754831C6E82168 /* Maybe.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Maybe.swift; path = RxSwift/Traits/PrimitiveSequence/Maybe.swift; sourceTree = ""; }; + AABE5D7EBB5C1664F6279707E9AA7519 /* RxCocoa-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-umbrella.h"; sourceTree = ""; }; + AB9D6840C14D5277550F97807BD7568A /* Pods-Nasa-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Pods-Nasa-umbrella.h"; sourceTree = ""; }; + ACB9B8802E98717CBF0CF019F0AC320A /* Observable+Bind.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Observable+Bind.swift"; path = "RxRelay/Observable+Bind.swift"; sourceTree = ""; }; + AF0090EDDDE993069035E68659AB6DE8 /* String+MD5.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "String+MD5.swift"; path = "Sources/Utility/String+MD5.swift"; sourceTree = ""; }; + AF422F832F0B72ABF641D5B011E1ADF2 /* Placeholder.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Placeholder.swift; path = Sources/Image/Placeholder.swift; sourceTree = ""; }; + AF67A85F485522B5F5548FE67FDC2D2E /* ReplayRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ReplayRelay.swift; path = RxRelay/ReplayRelay.swift; sourceTree = ""; }; + B1208B59E06C649DFE5FE192D877C55B /* DelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DelegateProxy.swift; path = RxCocoa/Common/DelegateProxy.swift; sourceTree = ""; }; + B14AD7EC93901D8E7BA191534B92A603 /* ImageModifier.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageModifier.swift; path = Sources/Networking/ImageModifier.swift; sourceTree = ""; }; + B22B26E71CE50B9005F7DC7A1836C1CB /* RefCountDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RefCountDisposable.swift; path = RxSwift/Disposables/RefCountDisposable.swift; sourceTree = ""; }; + B2D01C452CC574D02C19716426A6EB94 /* RxCollectionViewReactiveArrayDataSource.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewReactiveArrayDataSource.swift; path = RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift; sourceTree = ""; }; + B2EB90401C075B62E9BE003E5C247C47 /* Just.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Just.swift; path = RxSwift/Observables/Just.swift; sourceTree = ""; }; + B44BEF8F0C8D5BE9C952898810B8CB65 /* RxSwift.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.release.xcconfig; sourceTree = ""; }; + B49892E2C02C5AE916F5B783094249BD /* BooleanDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BooleanDisposable.swift; path = RxSwift/Disposables/BooleanDisposable.swift; sourceTree = ""; }; + B4CF72BD8B8045B24FA6E1809818AA38 /* UIPickerView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIPickerView+Rx.swift"; path = "RxCocoa/iOS/UIPickerView+Rx.swift"; sourceTree = ""; }; + B5F64313A3B683BB975F6D4390CFF18B /* Pods-Nasa-NasaUITests-Info.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-Nasa-NasaUITests-Info.plist"; sourceTree = ""; }; + B617539948E4DB5E99495236BCDC4C10 /* AsyncSubject.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncSubject.swift; path = RxSwift/Subjects/AsyncSubject.swift; sourceTree = ""; }; + B7FCD356D832308B24DE9B50105999F0 /* Kingfisher-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-umbrella.h"; sourceTree = ""; }; + B8708766B4E86A2178888E688318B7A6 /* KFAnimatedImage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = KFAnimatedImage.swift; path = Sources/SwiftUI/KFAnimatedImage.swift; sourceTree = ""; }; + B9B29DBF0770DA52AB49477DFDB5600F /* Infallible+Create.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Create.swift"; path = "RxSwift/Traits/Infallible/Infallible+Create.swift"; sourceTree = ""; }; + BB9C3817F7DB7846D93C1B48A7A44FB4 /* DistinctUntilChanged.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DistinctUntilChanged.swift; path = RxSwift/Observables/DistinctUntilChanged.swift; sourceTree = ""; }; + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxCocoa; path = RxCocoa.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + BD1A81FD6B7E87F397606D9ADFB89C85 /* HistoricalSchedulerTimeConverter.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalSchedulerTimeConverter.swift; path = RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift; sourceTree = ""; }; + BE2C2EECA1E2992ECEE36CDDD0D2D4AC /* SerialDispatchQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDispatchQueueScheduler.swift; path = RxSwift/Schedulers/SerialDispatchQueueScheduler.swift; sourceTree = ""; }; + BE3CAC3B8C77ADA995F99AB865199E01 /* RxSwift.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = RxSwift.debug.xcconfig; sourceTree = ""; }; + BF29D6E4B87309849D2B3CAC69F428ED /* Pods-NasaTests-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-NasaTests-dummy.m"; sourceTree = ""; }; + C005B6108292C74048FE29FDBB3A6811 /* Source.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Source.swift; path = Sources/General/ImageSource/Source.swift; sourceTree = ""; }; + C018D93FEE06CD7CFB3BD348FA7B9967 /* KVORepresentable+CoreGraphics.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "KVORepresentable+CoreGraphics.swift"; path = "RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift"; sourceTree = ""; }; + C099B50BD50310DBD0C05306CF6C398A /* ImagePrefetcher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImagePrefetcher.swift; path = Sources/Networking/ImagePrefetcher.swift; sourceTree = ""; }; + C0B44943E43480310387EA9E42DDF970 /* BehaviorRelay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = BehaviorRelay.swift; path = RxRelay/BehaviorRelay.swift; sourceTree = ""; }; + C1AD4F36B88F678AEADAB02A2EC1C325 /* UISwitch+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UISwitch+Rx.swift"; path = "RxCocoa/iOS/UISwitch+Rx.swift"; sourceTree = ""; }; + C1B32AA07CD3797FDE701EFB2722FCCA /* _RXDelegateProxy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXDelegateProxy.m; path = RxCocoa/Runtime/_RXDelegateProxy.m; sourceTree = ""; }; + C31E6720EEA23CA54E7215B97271E2CA /* ObservableConvertibleType+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableConvertibleType+Driver.swift"; path = "RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift"; sourceTree = ""; }; + C356B6347ADB2656B46F6F0144959071 /* SubscriptionDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubscriptionDisposable.swift; path = RxSwift/Disposables/SubscriptionDisposable.swift; sourceTree = ""; }; + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = Kingfisher; path = Kingfisher.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + C43F792D341DC15CC5E9465474368107 /* Pods-NasaTests-acknowledgements.markdown */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text; path = "Pods-NasaTests-acknowledgements.markdown"; sourceTree = ""; }; + C4D795950640DB4AC7E639CD530137D7 /* RxTextViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift; sourceTree = ""; }; + C5025FB5B6C0E58DC26EBDD4C7CF6539 /* NopDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = NopDisposable.swift; path = RxSwift/Disposables/NopDisposable.swift; sourceTree = ""; }; + C719A4208504FBE21E15E8FD30265002 /* CacheSerializer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CacheSerializer.swift; path = Sources/Cache/CacheSerializer.swift; sourceTree = ""; }; + C73D792E956EB3F2432C8962719CBC4E /* Delegate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delegate.swift; path = Sources/Utility/Delegate.swift; sourceTree = ""; }; + C898643E7C365B2110EEECE2E024FF59 /* SessionDataTask.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SessionDataTask.swift; path = Sources/Networking/SessionDataTask.swift; sourceTree = ""; }; + C8C2E909CF60AB440E70AC0741A4F2AA /* InvocableScheduledItem.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableScheduledItem.swift; path = RxSwift/Schedulers/Internal/InvocableScheduledItem.swift; sourceTree = ""; }; + CA33790E41B94863150898938627F8C9 /* Sequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Sequence.swift; path = RxSwift/Observables/Sequence.swift; sourceTree = ""; }; + CAEBF98EC58EF180B60F1F9E548B6B15 /* SkipWhile.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SkipWhile.swift; path = RxSwift/Observables/SkipWhile.swift; sourceTree = ""; }; + CBA24D30B5FD414A1CAB6D0DE390BFD2 /* ObservableType+PrimitiveSequence.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ObservableType+PrimitiveSequence.swift"; path = "RxSwift/Traits/PrimitiveSequence/ObservableType+PrimitiveSequence.swift"; sourceTree = ""; }; + CD1B450DD691AE08E1A8E779A484C1CE /* StartWith.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = StartWith.swift; path = RxSwift/Observables/StartWith.swift; sourceTree = ""; }; + CD67C50AD918E1F87C31C64E32A17C9D /* Timer.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Timer.swift; path = RxSwift/Observables/Timer.swift; sourceTree = ""; }; + CD9386FFA38863D2A3273C631322F7E9 /* ExtensionHelpers.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ExtensionHelpers.swift; path = Sources/Utility/ExtensionHelpers.swift; sourceTree = ""; }; + D0A406BF90BFD060A507BFE227FC9730 /* UITableView+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UITableView+Rx.swift"; path = "RxCocoa/iOS/UITableView+Rx.swift"; sourceTree = ""; }; + D1963CF85C64A6FC35B9C305D5FCBDE9 /* CallbackQueue.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CallbackQueue.swift; path = Sources/Utility/CallbackQueue.swift; sourceTree = ""; }; + D1BB12986CDCDB89DFABBF6054D06FEC /* UIBarButtonItem+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIBarButtonItem+Rx.swift"; path = "RxCocoa/iOS/UIBarButtonItem+Rx.swift"; sourceTree = ""; }; + D2233BBABA6487519797C148891EA0BB /* RxSearchBarDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxSearchBarDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift; sourceTree = ""; }; + D325C9B40C9E92EB3BA6895BB5219220 /* ObserverType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserverType.swift; path = RxSwift/ObserverType.swift; sourceTree = ""; }; + D386DA1FDD9D54279A85E31A698B2037 /* Empty.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Empty.swift; path = RxSwift/Observables/Empty.swift; sourceTree = ""; }; + D3BD5DF969085678D2AD058864789972 /* ImageProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageProcessor.swift; path = Sources/Image/ImageProcessor.swift; sourceTree = ""; }; + D3F20DF84A10C6732F7675B9AE55FCEF /* ImageDataProvider.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProvider.swift; path = Sources/General/ImageSource/ImageDataProvider.swift; sourceTree = ""; }; + D4866ECE2BD7F3325786D2C2BCAF3192 /* RxTarget.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTarget.swift; path = RxCocoa/Common/RxTarget.swift; sourceTree = ""; }; + D50B144E67E3FEDDD925A1E80FDF5EE4 /* RxTextStorageDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTextStorageDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift; sourceTree = ""; }; + D54F3220BCF82B5E9D8BB59B599EFEFA /* Completable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Completable.swift; path = RxSwift/Traits/PrimitiveSequence/Completable.swift; sourceTree = ""; }; + D5E45054A36FFD8A2439E6032FE9CAC4 /* HistoricalScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = HistoricalScheduler.swift; path = RxSwift/Schedulers/HistoricalScheduler.swift; sourceTree = ""; }; + D5FA7C58097A05AAE49FD6F11436E279 /* Optional.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Optional.swift; path = RxSwift/Observables/Optional.swift; sourceTree = ""; }; + D658DD511799A6D4218F9B9BB5B5F200 /* RxTableViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxTableViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + D67C27EE7920EE4807F35105298280E8 /* PrimitiveSequence+Zip+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "PrimitiveSequence+Zip+arity.swift"; path = "RxSwift/Traits/PrimitiveSequence/PrimitiveSequence+Zip+arity.swift"; sourceTree = ""; }; + D702F28288858BA18D04ECD25FC32EB5 /* RxScrollViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxScrollViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift; sourceTree = ""; }; + D965E448753D59388378FF252200AE28 /* Kingfisher.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Kingfisher.swift; path = Sources/General/Kingfisher.swift; sourceTree = ""; }; + D9E44D0D599D5C8440E7F76599046945 /* Error.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Error.swift; path = RxSwift/Observables/Error.swift; sourceTree = ""; }; + D9EF660346736D08210EC9837FDDF26E /* DispatchQueue+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "DispatchQueue+Extensions.swift"; path = "Platform/DispatchQueue+Extensions.swift"; sourceTree = ""; }; + DA73B22488E82AD4752410DB45D68584 /* _RXKVOObserver.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; name = _RXKVOObserver.m; path = RxCocoa/Runtime/_RXKVOObserver.m; sourceTree = ""; }; + DA9B86EAD60DB14CF3BDC2844C5ABC41 /* Platform.Darwin.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Platform.Darwin.swift; path = Platform/Platform.Darwin.swift; sourceTree = ""; }; + DAF9F38612D4CB9C9702024036CE7D17 /* ControlProperty+Driver.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "ControlProperty+Driver.swift"; path = "RxCocoa/Traits/Driver/ControlProperty+Driver.swift"; sourceTree = ""; }; + DB1621D1356737AD361FF017ACCEE879 /* DiskStorage.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = DiskStorage.swift; path = Sources/Cache/DiskStorage.swift; sourceTree = ""; }; + DB24EF4D5E4A05A01CF1697F16A3C908 /* Infallible+Operators.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+Operators.swift"; path = "RxSwift/Traits/Infallible/Infallible+Operators.swift"; sourceTree = ""; }; + DBB37C6077770A848A001B71DD3B61C7 /* Infallible+CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Infallible+CombineLatest+arity.swift"; path = "RxSwift/Traits/Infallible/Infallible+CombineLatest+arity.swift"; sourceTree = ""; }; + DC025C53C49665C068F28F5ED6E9BA35 /* RxCocoa.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCocoa.swift; path = RxCocoa/RxCocoa.swift; sourceTree = ""; }; + DC3023A9A8291E6F79715071B06F3D3A /* RecursiveScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RecursiveScheduler.swift; path = RxSwift/Schedulers/RecursiveScheduler.swift; sourceTree = ""; }; + DCAD0BEC0DDFCCEE5BD14F65FA4757D5 /* Result.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Result.swift; path = Sources/Utility/Result.swift; sourceTree = ""; }; + DD44EA86799AAB2D629CF2C684F4F639 /* Pods-Nasa-dummy.m */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.objc; path = "Pods-Nasa-dummy.m"; sourceTree = ""; }; + DD533D32A57348C33C62BA74428478AF /* Generate.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Generate.swift; path = RxSwift/Observables/Generate.swift; sourceTree = ""; }; + DEC40EF887E88BEE381B6A1C11C227DC /* RxPickerViewDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxPickerViewDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift; sourceTree = ""; }; + DF89586982E8DDA74AE0768A268EAC0A /* Pods-NasaTests-acknowledgements.plist */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.plist.xml; path = "Pods-NasaTests-acknowledgements.plist"; sourceTree = ""; }; + DFCA8B0CFBD32671E34A95012FF08B62 /* AsyncLock.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsyncLock.swift; path = RxSwift/Concurrency/AsyncLock.swift; sourceTree = ""; }; + E207E575E852821818CF45151A7B9EA5 /* OperationQueueScheduler.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = OperationQueueScheduler.swift; path = RxSwift/Schedulers/OperationQueueScheduler.swift; sourceTree = ""; }; + E26E49C79C3DCD957B46E8A42A534405 /* ImmediateSchedulerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImmediateSchedulerType.swift; path = RxSwift/ImmediateSchedulerType.swift; sourceTree = ""; }; + E518FC6FFB06E6E9102B10C1147BD69B /* AtomicInt.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AtomicInt.swift; path = Platform/AtomicInt.swift; sourceTree = ""; }; + E58790ED179A147D4141D43416EC9FCA /* RxCocoa-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxCocoa-prefix.pch"; sourceTree = ""; }; + E61E740BDB8328C95E2FC735D07F2DF3 /* InvocableType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = InvocableType.swift; path = RxSwift/Schedulers/Internal/InvocableType.swift; sourceTree = ""; }; + E84695897916E17EA92CD7925F8D684B /* Amb.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Amb.swift; path = RxSwift/Observables/Amb.swift; sourceTree = ""; }; + E9391EED99BAEB46C2049400C2CDA233 /* Debug.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Debug.swift; path = RxSwift/Observables/Debug.swift; sourceTree = ""; }; + EBAFF86672E46BDCF016A36E670BA43A /* Kingfisher.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = Kingfisher.debug.xcconfig; sourceTree = ""; }; + EC05C3D15F4398DDB4E958C53D4E4116 /* Completable+AndThen.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Completable+AndThen.swift"; path = "RxSwift/Traits/PrimitiveSequence/Completable+AndThen.swift"; sourceTree = ""; }; + EC5CE11A43BCD442A68F715BC4F23064 /* ImageDataProcessor.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageDataProcessor.swift; path = Sources/Networking/ImageDataProcessor.swift; sourceTree = ""; }; + EC794D94362E616CA4F9E48C102DF492 /* UIApplication+Rx.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "UIApplication+Rx.swift"; path = "RxCocoa/iOS/UIApplication+Rx.swift"; sourceTree = ""; }; + ED130067DDB9BD1CCD1077798386C986 /* Delay.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Delay.swift; path = RxSwift/Observables/Delay.swift; sourceTree = ""; }; + EFAF4638E04D6A613483A18195CCB8C5 /* Map.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Map.swift; path = RxSwift/Observables/Map.swift; sourceTree = ""; }; + F00D34E61FAAFF1A804BFAE8B34F51D2 /* SubjectType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SubjectType.swift; path = RxSwift/Subjects/SubjectType.swift; sourceTree = ""; }; + F0CCA805B17A3F518CEB94F5A9E17141 /* SerialDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SerialDisposable.swift; path = RxSwift/Disposables/SerialDisposable.swift; sourceTree = ""; }; + F1B175696C3EE0E048FA7942F2D65B04 /* ImageCache.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ImageCache.swift; path = Sources/Cache/ImageCache.swift; sourceTree = ""; }; + F1E8840266C690A49D91682712E72B9F /* LockOwnerType.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = LockOwnerType.swift; path = RxSwift/Concurrency/LockOwnerType.swift; sourceTree = ""; }; + F4E1DA88CDEB6032902BF148F263C418 /* RxCocoaRuntime.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoaRuntime.h; path = RxCocoa/Runtime/include/RxCocoaRuntime.h; sourceTree = ""; }; + F5761FF7A726E317BBACFE95BAA632C7 /* RxCollectionViewDataSourcePrefetchingProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxCollectionViewDataSourcePrefetchingProxy.swift; path = RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift; sourceTree = ""; }; + F5E1AF0DBAEBDBF51E2454A51D0E0912 /* Pods-Nasa-NasaUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Nasa-NasaUITests.release.xcconfig"; sourceTree = ""; }; + F611ED177B5CCA74A94808C6F8CEB616 /* SharedSequence+Operators+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "SharedSequence+Operators+arity.swift"; path = "RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift"; sourceTree = ""; }; + F619746893827D94BB14FA4D4F57DB5C /* CompactMap.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompactMap.swift; path = RxSwift/Observables/CompactMap.swift; sourceTree = ""; }; + F70F3CA7F64F8E6BED39B3C117FA9ABF /* CompositeDisposable.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = CompositeDisposable.swift; path = RxSwift/Disposables/CompositeDisposable.swift; sourceTree = ""; }; + F965D68950E22ADD709D34E78FA9C631 /* ObserveOn.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = ObserveOn.swift; path = RxSwift/Observables/ObserveOn.swift; sourceTree = ""; }; + FA43120ABE0220521B0FACEC3679E559 /* Reactive.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Reactive.swift; path = RxSwift/Reactive.swift; sourceTree = ""; }; + FADB38E9C9FD65A133C879209C9C2021 /* RxRelay-umbrella.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "RxRelay-umbrella.h"; sourceTree = ""; }; + FADC3ACC413B1279C66724360A72CA50 /* RxCocoaObjCRuntimeError+Extensions.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "RxCocoaObjCRuntimeError+Extensions.swift"; path = "RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift"; sourceTree = ""; }; + FB2668BDC38D0808ABCC0AFD272DBBF8 /* RxCocoa.h */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; name = RxCocoa.h; path = RxCocoa/RxCocoa.h; sourceTree = ""; }; + FB493FA46A5123A0276CD8F3494A8BF2 /* Kingfisher-prefix.pch */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.c.h; path = "Kingfisher-prefix.pch"; sourceTree = ""; }; + FD3DFA4324F53EFF292E97C31F7D3E78 /* Pods-Nasa-NasaUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; path = "Pods-Nasa-NasaUITests.debug.xcconfig"; sourceTree = ""; }; + FDF0B19FC15BA90936BA5BF3D2F306A2 /* Event.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = Event.swift; path = RxSwift/Event.swift; sourceTree = ""; }; + FEC695C4BAC15CC194BCF9DBE877584E /* CombineLatest+arity.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "CombineLatest+arity.swift"; path = "RxSwift/Observables/CombineLatest+arity.swift"; sourceTree = ""; }; + FF59433812B9DC199478694D9B4B1246 /* Driver+Subscription.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = "Driver+Subscription.swift"; path = "RxCocoa/Traits/Driver/Driver+Subscription.swift"; sourceTree = ""; }; + FF6797F3F6131A47B2E90FE2F5657783 /* RxNavigationControllerDelegateProxy.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = RxNavigationControllerDelegateProxy.swift; path = RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift; sourceTree = ""; }; + FF6FC2B162B74ED0DF07FF5E553F25AF /* AsSingle.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = AsSingle.swift; path = RxSwift/Observables/AsSingle.swift; sourceTree = ""; }; + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; name = RxRelay; path = RxRelay.framework; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0B2DEE70C6D6B3A1DFFCDD138F4B02E5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 96F67E76F9DBD3690A25894F1FE499DE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 22163383E9B72995E87D3CD9654FD971 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 92CA5C88C88C68BFF8F0125CA48E20BC /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 4DAD51760C3A529B5ACA9477FDA8E31A /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 04B2DDDF8C3C5DAE8952E85BD4ECF6CE /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 81DB1665E1495609510BA493822E5A85 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E719A3B025B9DACE693130120BD9B927 /* Accelerate.framework in Frameworks */, + 420C200A05BB29E1D299D1BADE9139D2 /* CFNetwork.framework in Frameworks */, + 3AD5DBB915C2623991F7DBACD173BBB4 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A37D984C9C15FAC466569401CE96920F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + A2020CB303E5DC515FB24444B9A90418 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C20E50D4AB3493E8ADF683FE3A690EFD /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 0975174D3CF422126D1C65414D463B5B /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + C7D08BE715F3F3A083EB3B03F42D58DF /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E6A207EE08EA44841EBF3E5E6C21E341 /* Foundation.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 027508ADB37DD9E3D330F29565CF213F /* RxCocoa */ = { + isa = PBXGroup; + children = ( + 2A97390210CBA1BCC3E831A2C79397A4 /* _RX.h */, + 2FDAEF959C217E3AAE4B7E563231E365 /* _RX.m */, + 4AD61FFEA9BE7E0D078DE9B5B06826F3 /* _RXDelegateProxy.h */, + C1B32AA07CD3797FDE701EFB2722FCCA /* _RXDelegateProxy.m */, + 78DBB9BD0602DF88C96C8874E26D0C27 /* _RXKVOObserver.h */, + DA73B22488E82AD4752410DB45D68584 /* _RXKVOObserver.m */, + 363D470EA28CDC7BCECB8137F65A2201 /* _RXObjCRuntime.h */, + 711A1FB5D3CEBDB29D84C91569DBC787 /* _RXObjCRuntime.m */, + 57B05CAB9374BE0B393DCBDF166CA277 /* Bag.swift */, + 1328BA8F1A85D005BF68F4079DCACA23 /* BehaviorRelay+Driver.swift */, + 765DADAEB790057019DB04648364475A /* ControlEvent.swift */, + 31EFB9EE3C11EADCE4C7DB67CFD4308D /* ControlEvent+Driver.swift */, + 3B64D3B6DCACA3245426B3DCC4CBEF4E /* ControlEvent+Signal.swift */, + 6C32BE0FBF23366538EC38133C3B4761 /* ControlProperty.swift */, + DAF9F38612D4CB9C9702024036CE7D17 /* ControlProperty+Driver.swift */, + 241691F359B733E2056B8DC609B60F37 /* ControlTarget.swift */, + B1208B59E06C649DFE5FE192D877C55B /* DelegateProxy.swift */, + 57C02CC9D716ABE836FC698744C40162 /* DelegateProxyType.swift */, + D9EF660346736D08210EC9837FDDF26E /* DispatchQueue+Extensions.swift */, + A29091995433007CC3BDB7701C59607B /* Driver.swift */, + FF59433812B9DC199478694D9B4B1246 /* Driver+Subscription.swift */, + 6CA18C31ED77D7EA8DCE74634CBF93DA /* Infallible+Bind.swift */, + 276504E06EE445B80BAE0BE356B3747A /* InfiniteSequence.swift */, + 2331321DA7B50BFA00A86FECACFC7850 /* ItemEvents.swift */, + 0C4B711F5F67AC1D5168CCDA2F79619D /* KVORepresentable.swift */, + C018D93FEE06CD7CFB3BD348FA7B9967 /* KVORepresentable+CoreGraphics.swift */, + 4C7D77586C026EBDD88A96FFC838083C /* KVORepresentable+Swift.swift */, + A2E2CDC3BC75BD1863C73AA5362FD273 /* NotificationCenter+Rx.swift */, + 86DD172B182805841A3A2061759B42D9 /* NSButton+Rx.swift */, + 0C2577FC9887D8705C76D78D1C5B985E /* NSControl+Rx.swift */, + 299B19C83AA437DF51807FF8A0116A15 /* NSObject+Rx.swift */, + 659C95F6167047A371AE813DDE268CED /* NSObject+Rx+KVORepresentable.swift */, + 72807B39E40B38A0B9BF0FE82115D701 /* NSObject+Rx+RawRepresentable.swift */, + 255952E0493402482EF3A6856781EB26 /* NSSlider+Rx.swift */, + 991A2A3F38D320429C0AF533CCC1A2DA /* NSTextField+Rx.swift */, + 46557E1582E320EB12560AA106A3EF3F /* NSTextStorage+Rx.swift */, + 671F3730AFF17DD82C3672D14F4D8D10 /* NSTextView+Rx.swift */, + 67591D311B21307172FABF417357CEC1 /* NSView+Rx.swift */, + 731DA7559774054AC732C32D2D466D36 /* Observable+Bind.swift */, + C31E6720EEA23CA54E7215B97271E2CA /* ObservableConvertibleType+Driver.swift */, + 2AF530F70F556F38DF940D440404373C /* ObservableConvertibleType+SharedSequence.swift */, + 573926B12A41731C6B0AAA5F1394ACF7 /* ObservableConvertibleType+Signal.swift */, + DA9B86EAD60DB14CF3BDC2844C5ABC41 /* Platform.Darwin.swift */, + 74611FF6E108D51044FDACBEDCEA272C /* Platform.Linux.swift */, + 631FC8F669F041C47F44CB1BAC72887C /* PriorityQueue.swift */, + 006AD59A1FDED35C1684D1987A01272D /* PublishRelay+Signal.swift */, + 347B29F2635F01233990E9C245FA1DC2 /* Queue.swift */, + 254D9E505B6D1A753C59BFE304EB1BE1 /* RecursiveLock.swift */, + FB2668BDC38D0808ABCC0AFD272DBBF8 /* RxCocoa.h */, + DC025C53C49665C068F28F5ED6E9BA35 /* RxCocoa.swift */, + FADC3ACC413B1279C66724360A72CA50 /* RxCocoaObjCRuntimeError+Extensions.swift */, + F4E1DA88CDEB6032902BF148F263C418 /* RxCocoaRuntime.h */, + F5761FF7A726E317BBACFE95BAA632C7 /* RxCollectionViewDataSourcePrefetchingProxy.swift */, + 2AA01AD91A96C4A92DC718480BF8E4FB /* RxCollectionViewDataSourceProxy.swift */, + 99A31E40D67BC43BC1AC643E81E41AF6 /* RxCollectionViewDataSourceType.swift */, + 836FA04B8B9B8C930387B9ACAC062972 /* RxCollectionViewDelegateProxy.swift */, + B2D01C452CC574D02C19716426A6EB94 /* RxCollectionViewReactiveArrayDataSource.swift */, + FF6797F3F6131A47B2E90FE2F5657783 /* RxNavigationControllerDelegateProxy.swift */, + A1E2761EE1212BC4BB8E539BC93D7842 /* RxPickerViewAdapter.swift */, + 65DAAE0320F729A067CD23F6A910069A /* RxPickerViewDataSourceProxy.swift */, + 2F60DF6BE39EB76887AA7E118E700A41 /* RxPickerViewDataSourceType.swift */, + DEC40EF887E88BEE381B6A1C11C227DC /* RxPickerViewDelegateProxy.swift */, + D702F28288858BA18D04ECD25FC32EB5 /* RxScrollViewDelegateProxy.swift */, + D2233BBABA6487519797C148891EA0BB /* RxSearchBarDelegateProxy.swift */, + 3DA599EFBD1FDCDB6D6514262DB105F5 /* RxSearchControllerDelegateProxy.swift */, + 7B243EFB97DCFEC58BFD68592BE69E99 /* RxTabBarControllerDelegateProxy.swift */, + 8E55E337DAF3B45894CF50E3D4D83EC9 /* RxTabBarDelegateProxy.swift */, + D658DD511799A6D4218F9B9BB5B5F200 /* RxTableViewDataSourcePrefetchingProxy.swift */, + 5645B2FDDA74EFD8B513313430E182DB /* RxTableViewDataSourceProxy.swift */, + 8D54F3EFCD78F700D10C91447B6D7923 /* RxTableViewDataSourceType.swift */, + 551E9EDABFE6F6C3985087A678D24DD3 /* RxTableViewDelegateProxy.swift */, + 09DE430262BDAAA66289105E0EF31980 /* RxTableViewReactiveArrayDataSource.swift */, + D4866ECE2BD7F3325786D2C2BCAF3192 /* RxTarget.swift */, + D50B144E67E3FEDDD925A1E80FDF5EE4 /* RxTextStorageDelegateProxy.swift */, + C4D795950640DB4AC7E639CD530137D7 /* RxTextViewDelegateProxy.swift */, + 3F24826DDE7D64BFC7A0BCA4DF3B6978 /* RxWKNavigationDelegateProxy.swift */, + 76F6B571F692833993F0EE21BBBD5B33 /* SchedulerType+SharedSequence.swift */, + 9CF06B6FBB5DBB1F4D6D0739F0346BE6 /* SectionedViewDataSourceType.swift */, + 16A72B04D50D8F6C820F4A91C64E440F /* SharedSequence.swift */, + 313CBC199D9C144DC0550B1BBAAE89F3 /* SharedSequence+Operators.swift */, + F611ED177B5CCA74A94808C6F8CEB616 /* SharedSequence+Operators+arity.swift */, + 75567979F42C7049A3177B96B09F1FD1 /* Signal.swift */, + 6CF11E4E091F4DF262DBF2E02B8339EB /* Signal+Subscription.swift */, + 9718ADF3B40EBC380D55C19C95DEEB2D /* TextInput.swift */, + 880411AA04678912F31750B286549944 /* UIActivityIndicatorView+Rx.swift */, + EC794D94362E616CA4F9E48C102DF492 /* UIApplication+Rx.swift */, + D1BB12986CDCDB89DFABBF6054D06FEC /* UIBarButtonItem+Rx.swift */, + 5141B34991C273AA0F55C8B9C9BAA501 /* UIButton+Rx.swift */, + 8AB1B319B15ADC03FE14A5722C666C97 /* UICollectionView+Rx.swift */, + A887DFD8B864789ABC116EA35FECBD49 /* UIControl+Rx.swift */, + 770F21ADC933DC7B515BE3B743647A1B /* UIDatePicker+Rx.swift */, + 9BE0B00707E6FF026FD1C832618D8245 /* UIGestureRecognizer+Rx.swift */, + 32D5973F5B6BE2FD9D6862829F3341B9 /* UINavigationController+Rx.swift */, + B4CF72BD8B8045B24FA6E1809818AA38 /* UIPickerView+Rx.swift */, + 52AC685178073CE2C546491DC631D838 /* UIRefreshControl+Rx.swift */, + 26E15E018D9EED7F4CE32D7EB7E83DF8 /* UIScrollView+Rx.swift */, + 42E60FDDEB87F1E0AB28E697D2D7E18C /* UISearchBar+Rx.swift */, + 066EA749DDAE608EC1C2512673A8CE66 /* UISearchController+Rx.swift */, + 39169A0D9A36E134D5B402DFDE82C77E /* UISegmentedControl+Rx.swift */, + 0A2F3DC44E81F53D72DFFAA215A85B11 /* UISlider+Rx.swift */, + 7ED2066564452073563FAFF29121A419 /* UIStepper+Rx.swift */, + C1AD4F36B88F678AEADAB02A2EC1C325 /* UISwitch+Rx.swift */, + 6363D082F4B2E3974215EBBD51813FF2 /* UITabBar+Rx.swift */, + A14E61A58E8566B4B358AD4CB44FCFB3 /* UITabBarController+Rx.swift */, + D0A406BF90BFD060A507BFE227FC9730 /* UITableView+Rx.swift */, + 1160C2BAB6A3EA880AA1801140ED996C /* UITextField+Rx.swift */, + 9D4E24F8810B9D1C4F328503EFC58863 /* UITextView+Rx.swift */, + 02E99B14DAE00C21F19A5379E03C9F79 /* URLSession+Rx.swift */, + 3E6679A12C19FCB8C599445AC992D79E /* WKWebView+Rx.swift */, + 8475D0F7A2B0606084B0D312E1AE48A2 /* Support Files */, + ); + name = RxCocoa; + path = RxCocoa; + sourceTree = ""; + }; + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 5EE21CBB8EFB615AB450D209E054FAE6 /* iOS */, + ); + name = Frameworks; + sourceTree = ""; + }; + 2ACFA9E1812EEF8DB54E12467D37634E /* RxSwift */ = { + isa = PBXGroup; + children = ( + 066CAD6EFE30AE8BD17C67089662A828 /* AddRef.swift */, + E84695897916E17EA92CD7925F8D684B /* Amb.swift */, + 605A26EBFB5CB5DD153C584A76FCF2AF /* AnonymousDisposable.swift */, + 4EC0E80CF040EEF1CEEF6C403832653D /* AnonymousObserver.swift */, + 300289A8F4020601668E8504FE6E00C4 /* AnyObserver.swift */, + 8ECFDDF445685ACA15D40D07E6CC60CF /* AsMaybe.swift */, + FF6FC2B162B74ED0DF07FF5E553F25AF /* AsSingle.swift */, + DFCA8B0CFBD32671E34A95012FF08B62 /* AsyncLock.swift */, + B617539948E4DB5E99495236BCDC4C10 /* AsyncSubject.swift */, + E518FC6FFB06E6E9102B10C1147BD69B /* AtomicInt.swift */, + 9E5B11A6C7AA615DB9480FA1ECE82D98 /* Bag.swift */, + 5A47D822D952110CECC562981840EAEE /* Bag+Rx.swift */, + 141E846C1992FC3B824497B4C31E9283 /* BehaviorSubject.swift */, + 3CD1DB6F70625F317E2AAE03A05BB56F /* BinaryDisposable.swift */, + 87FE5AE82D1B317B99D0BBC417C13EA5 /* Binder.swift */, + B49892E2C02C5AE916F5B783094249BD /* BooleanDisposable.swift */, + 1F6A91146050496D447EBB82EA7EB0FA /* Buffer.swift */, + 87E9B0EC98D89A8043AA03EBF3AADF89 /* Cancelable.swift */, + 2D3C1F7EC6E18E56276BC08423EC09F9 /* Catch.swift */, + 96668307975A303706F47C0B9A0BDA32 /* CombineLatest.swift */, + FEC695C4BAC15CC194BCF9DBE877584E /* CombineLatest+arity.swift */, + 5F19834A1B62B273FB9DE568FB7B1D19 /* CombineLatest+Collection.swift */, + F619746893827D94BB14FA4D4F57DB5C /* CompactMap.swift */, + D54F3220BCF82B5E9D8BB59B599EFEFA /* Completable.swift */, + EC05C3D15F4398DDB4E958C53D4E4116 /* Completable+AndThen.swift */, + F70F3CA7F64F8E6BED39B3C117FA9ABF /* CompositeDisposable.swift */, + A5950202FDF9773C66FA3213D36FD1C5 /* Concat.swift */, + 2444CB36080B3F8C9F26783D03E1EF90 /* ConcurrentDispatchQueueScheduler.swift */, + 8B2AC97752DBF56A8D836C63942A6ACB /* ConcurrentMainScheduler.swift */, + 2C273B8A937511063AE9B77E767FAAA5 /* ConnectableObservableType.swift */, + A935D27A5DA9A4B25D2649B10D85666C /* Create.swift */, + 4887851A3282354968E9864A4B0F4077 /* CurrentThreadScheduler.swift */, + 2A003EE5E2035D78B7EBC111C3CD1E1C /* Date+Dispatch.swift */, + 1F89590B2C85F3BD4C81FEBC2F44E282 /* Debounce.swift */, + E9391EED99BAEB46C2049400C2CDA233 /* Debug.swift */, + 6E373816BBB6C36165EF92E2B027BB44 /* Decode.swift */, + 13A194DA04F1FAE32DF8451C7EC0397A /* DefaultIfEmpty.swift */, + 93D1A993428B6200A1864B6895B46059 /* Deferred.swift */, + ED130067DDB9BD1CCD1077798386C986 /* Delay.swift */, + 509BFA3A2F815D66AE5490E0D9B15E5C /* DelaySubscription.swift */, + 17D24989F7C78CBD46A2F964A4A8A477 /* Dematerialize.swift */, + 14677C8E07CB908238683A17ED1B0ACB /* DispatchQueue+Extensions.swift */, + 593DACEE9DD963E86B9A4C9355EC9529 /* DispatchQueueConfiguration.swift */, + 017D63D87A6E8E266C74671DED987366 /* Disposable.swift */, + AA089C793A7294C12FC5B8F5C501B129 /* Disposables.swift */, + 76327D49CD25C8AAB3B6D9A0443996E2 /* DisposeBag.swift */, + 168B034469C3020A01BD7EB19B8C3409 /* DisposeBase.swift */, + BB9C3817F7DB7846D93C1B48A7A44FB4 /* DistinctUntilChanged.swift */, + 11E45EF449E27B13A73285473A5E7B7E /* Do.swift */, + 9204F68E3EC8D088420BE817820C9224 /* ElementAt.swift */, + D386DA1FDD9D54279A85E31A698B2037 /* Empty.swift */, + 80196883EA6E29278366559EFB614235 /* Enumerated.swift */, + D9E44D0D599D5C8440E7F76599046945 /* Error.swift */, + A4026CC76C5C4D10BB5E1621462E50F0 /* Errors.swift */, + FDF0B19FC15BA90936BA5BF3D2F306A2 /* Event.swift */, + 6D9736BF14210970F37A7A776C2C0942 /* Filter.swift */, + 178FBC0CAD4510CF099006E3D61CED3D /* First.swift */, + DD533D32A57348C33C62BA74428478AF /* Generate.swift */, + 13A0DF8765781203921620F29EDB0C14 /* GroupBy.swift */, + 97B5A42988E1A0A9D562043D29D13732 /* GroupedObservable.swift */, + D5E45054A36FFD8A2439E6032FE9CAC4 /* HistoricalScheduler.swift */, + BD1A81FD6B7E87F397606D9ADFB89C85 /* HistoricalSchedulerTimeConverter.swift */, + E26E49C79C3DCD957B46E8A42A534405 /* ImmediateSchedulerType.swift */, + 487016C43A9C696EF689DB1E07400631 /* Infallible.swift */, + DBB37C6077770A848A001B71DD3B61C7 /* Infallible+CombineLatest+arity.swift */, + B9B29DBF0770DA52AB49477DFDB5600F /* Infallible+Create.swift */, + DB24EF4D5E4A05A01CF1697F16A3C908 /* Infallible+Operators.swift */, + 5D5B9644894C489A87BE27ABAD388DE8 /* Infallible+Zip+arity.swift */, + 665C9746CC0234EFDDEBB59D0A6200AF /* InfiniteSequence.swift */, + C8C2E909CF60AB440E70AC0741A4F2AA /* InvocableScheduledItem.swift */, + E61E740BDB8328C95E2FC735D07F2DF3 /* InvocableType.swift */, + B2EB90401C075B62E9BE003E5C247C47 /* Just.swift */, + 7DD04BCB8E9C26011C133ED0222369CB /* Lock.swift */, + F1E8840266C690A49D91682712E72B9F /* LockOwnerType.swift */, + 2CA0B0B9146454EC23A31F2C346DF3E6 /* MainScheduler.swift */, + EFAF4638E04D6A613483A18195CCB8C5 /* Map.swift */, + 90DFD528941DB2E45A03A9B1FA741E64 /* Materialize.swift */, + AA91BB1404869D1480754831C6E82168 /* Maybe.swift */, + 7DF5F64075BE015B0E4A94A4D723C953 /* Merge.swift */, + 58DF78FBCC8D025608AFCDB64E94B7F6 /* Multicast.swift */, + 53CAB4283845A13ABA4F3657A92430AE /* Never.swift */, + C5025FB5B6C0E58DC26EBDD4C7CF6539 /* NopDisposable.swift */, + 21A69AAF600A098645D61F1F7A7DFD77 /* Observable.swift */, + 256D1BE267826C7A5B0D21E89829F186 /* ObservableConvertibleType.swift */, + 0121CA18F76DBA229576FE20F51CC20E /* ObservableConvertibleType+Infallible.swift */, + A249417112017333EFE8B667A7F7BA29 /* ObservableType.swift */, + 1F04451837217FD4AE5DFEE23B4CB6B3 /* ObservableType+Extensions.swift */, + CBA24D30B5FD414A1CAB6D0DE390BFD2 /* ObservableType+PrimitiveSequence.swift */, + F965D68950E22ADD709D34E78FA9C631 /* ObserveOn.swift */, + 3DD6FFD079EF8A2DDE25C35353EBD004 /* ObserverBase.swift */, + D325C9B40C9E92EB3BA6895BB5219220 /* ObserverType.swift */, + E207E575E852821818CF45151A7B9EA5 /* OperationQueueScheduler.swift */, + D5FA7C58097A05AAE49FD6F11436E279 /* Optional.swift */, + 54CA1986B4B7E04F0B4124B8C0B1515D /* Platform.Darwin.swift */, + 0DDC4DAFE1E58071E663D24DA336250B /* Platform.Linux.swift */, + 47D9D6FB3FB7EB503D7A85011FA19A8C /* PrimitiveSequence.swift */, + D67C27EE7920EE4807F35105298280E8 /* PrimitiveSequence+Zip+arity.swift */, + 9DBE86666C4C7C00176BD62714FC2B60 /* PriorityQueue.swift */, + 74858C397A6FBC0B0E3D7738867844CC /* Producer.swift */, + 204DC3001AB65CBF63130DB17A9EC6D2 /* PublishSubject.swift */, + 3449B1ED3620A7995593EDBBB1A8FF36 /* Queue.swift */, + 93FA7D29AAB8705F01F5B0D66AD537E5 /* Range.swift */, + FA43120ABE0220521B0FACEC3679E559 /* Reactive.swift */, + 9C935BCECC9A0F510E3678B2DEF96E74 /* RecursiveLock.swift */, + DC3023A9A8291E6F79715071B06F3D3A /* RecursiveScheduler.swift */, + 0D5313A20F617A6A0FFE42F2B9FA8E31 /* Reduce.swift */, + B22B26E71CE50B9005F7DC7A1836C1CB /* RefCountDisposable.swift */, + 9C56FDD70B5E9F43C3796E6AB1585BEE /* Repeat.swift */, + 3742D4F3A812DEDA45D7587BFA16A37A /* ReplaySubject.swift */, + 78BBC08AB3F71A56C70C1D83460673B1 /* RetryWhen.swift */, + 3DC4726BFD306141702DA64D7CA622A0 /* Rx.swift */, + 24115E491FA4BD6A1F000508B25E41C6 /* RxMutableBox.swift */, + 194DE807E02F7FCF6F24AF3BE9651CA4 /* Sample.swift */, + 1D23F5C136F055CF503012DEDD515E92 /* Scan.swift */, + 9384A9D594BA0B3ABADCA346461AE61E /* ScheduledDisposable.swift */, + 1F5A54A9DA49163C7145C76F8355D1C6 /* ScheduledItem.swift */, + 2464C1376934D750B723647A48B6C83F /* ScheduledItemType.swift */, + 05A835A78CBC37235B8A9803C4D5C2D1 /* SchedulerServices+Emulation.swift */, + 9E99D160193CCBB23FC861A1641D07DA /* SchedulerType.swift */, + CA33790E41B94863150898938627F8C9 /* Sequence.swift */, + BE2C2EECA1E2992ECEE36CDDD0D2D4AC /* SerialDispatchQueueScheduler.swift */, + F0CCA805B17A3F518CEB94F5A9E17141 /* SerialDisposable.swift */, + 4FC25F6C3C493911AFC553ED0B080E71 /* ShareReplayScope.swift */, + 19C61AA1D29DF02DA1DBE6FED144C917 /* Single.swift */, + 4224FF8BA20495FDD3B5C29557D3B96A /* SingleAssignmentDisposable.swift */, + 93CF262711162BF6AC485B334DC9B37F /* SingleAsync.swift */, + 26E5FA57DDDD1DFB317C5ED60769E52B /* Sink.swift */, + 14C07AEFCB83FD479726E58A485E7F8C /* Skip.swift */, + 423FC353DC78844A93CB4BE73ABF83B6 /* SkipUntil.swift */, + CAEBF98EC58EF180B60F1F9E548B6B15 /* SkipWhile.swift */, + CD1B450DD691AE08E1A8E779A484C1CE /* StartWith.swift */, + F00D34E61FAAFF1A804BFAE8B34F51D2 /* SubjectType.swift */, + 89D58D454E656EB201E21C9EF37A70E6 /* SubscribeOn.swift */, + C356B6347ADB2656B46F6F0144959071 /* SubscriptionDisposable.swift */, + 8DECDBB7D351E4436AFF57C154B6D604 /* SwiftSupport.swift */, + 6B35C4107E8F589E3345F787F1A1F303 /* Switch.swift */, + 9C1B5CC2BA7AEB06BDAFF8440716FF8F /* SwitchIfEmpty.swift */, + A09EBD7676C0F16F630021DEB6C615D4 /* SynchronizedDisposeType.swift */, + 3559CF60499726E5518704F3352488AD /* SynchronizedOnType.swift */, + 1A00EC4EC537E97430E2B41CCA99FD75 /* SynchronizedUnsubscribeType.swift */, + 190D0B1290B83B5F6C9A62481F5B6539 /* TailRecursiveSink.swift */, + 3EEF33A950F5444D1A6C3863129551A6 /* Take.swift */, + 6077A495BA175BE283E5433B37F9CB7C /* TakeLast.swift */, + 11CCB2B8C905F7BB21519F1AC17D356D /* TakeWithPredicate.swift */, + 47BAF640636860171656B4A3BE35179B /* Throttle.swift */, + 6F92350A86AE47AFC761F7D81387757B /* Timeout.swift */, + CD67C50AD918E1F87C31C64E32A17C9D /* Timer.swift */, + 8E5266CB42414BE09BC701E201C85AAF /* ToArray.swift */, + 086CB9F323A5A9B4A6BF898353D4E952 /* Using.swift */, + 877C6EC3C797F8A700D0FF9EAF958D19 /* VirtualTimeConverterType.swift */, + 72CD3A7E60C3A4A7E20AEBE4D9F79954 /* VirtualTimeScheduler.swift */, + 981D9449308470332443FF6AEEA4BD3E /* Window.swift */, + 8E278B10D48A31495A483A772250AF3F /* WithLatestFrom.swift */, + A44DE42418669BA60C6BFDC99A41FF77 /* WithUnretained.swift */, + 18C52394FF76FB38E57C3225739FE247 /* Zip.swift */, + 0DC5E11560B6B3A7A08289CB51A77341 /* Zip+arity.swift */, + 0EE5D91BA47B0C0B75F882C976E151A3 /* Zip+Collection.swift */, + A5CC64F8D8C95DF5DD041DEE9D327D8D /* Support Files */, + ); + name = RxSwift; + path = RxSwift; + sourceTree = ""; + }; + 44EFFC69ABD05878DE3AB5CDCCE663B8 /* Pods */ = { + isa = PBXGroup; + children = ( + 82B9418FC740377266C89B55CF21AC69 /* Kingfisher */, + 027508ADB37DD9E3D330F29565CF213F /* RxCocoa */, + F8461427E92F2639D770B7116935D392 /* RxRelay */, + 2ACFA9E1812EEF8DB54E12467D37634E /* RxSwift */, + ); + name = Pods; + sourceTree = ""; + }; + 527D0FCD2E336B08C82B4AEAC26A6D56 /* Pods-NasaTests */ = { + isa = PBXGroup; + children = ( + 8437ED9F010236021ADDEEF3979217FE /* Pods-NasaTests.modulemap */, + C43F792D341DC15CC5E9465474368107 /* Pods-NasaTests-acknowledgements.markdown */, + DF89586982E8DDA74AE0768A268EAC0A /* Pods-NasaTests-acknowledgements.plist */, + BF29D6E4B87309849D2B3CAC69F428ED /* Pods-NasaTests-dummy.m */, + 291802E320980241260B0D9115E0DED8 /* Pods-NasaTests-Info.plist */, + 2DBC19243FA5BCBBB47A8134B7CAAD9E /* Pods-NasaTests-umbrella.h */, + 168DC811C7106944BF69EDADA98FD6D0 /* Pods-NasaTests.debug.xcconfig */, + 32630B4842C76B01267DF03C2B356519 /* Pods-NasaTests.release.xcconfig */, + ); + name = "Pods-NasaTests"; + path = "Target Support Files/Pods-NasaTests"; + sourceTree = ""; + }; + 5795C872AD31AE1B6342D8422707186B /* Pods-Nasa-NasaUITests */ = { + isa = PBXGroup; + children = ( + 0B800EF9A2F71AC4B18D0F78B55B7F48 /* Pods-Nasa-NasaUITests.modulemap */, + 157AA11C789EA2B3DD909BC67B10C2C3 /* Pods-Nasa-NasaUITests-acknowledgements.markdown */, + 253489F1B29D39562DA60549EC7D1056 /* Pods-Nasa-NasaUITests-acknowledgements.plist */, + 2118DD01B1A6FC92E1E902D1C1A28F66 /* Pods-Nasa-NasaUITests-dummy.m */, + 90BCDFDC98BBC5BC4011B4BD2767E409 /* Pods-Nasa-NasaUITests-frameworks.sh */, + B5F64313A3B683BB975F6D4390CFF18B /* Pods-Nasa-NasaUITests-Info.plist */, + 56D4E7ECD516A37F2AEE8978B3B5DF76 /* Pods-Nasa-NasaUITests-umbrella.h */, + FD3DFA4324F53EFF292E97C31F7D3E78 /* Pods-Nasa-NasaUITests.debug.xcconfig */, + F5E1AF0DBAEBDBF51E2454A51D0E0912 /* Pods-Nasa-NasaUITests.release.xcconfig */, + ); + name = "Pods-Nasa-NasaUITests"; + path = "Target Support Files/Pods-Nasa-NasaUITests"; + sourceTree = ""; + }; + 5EE21CBB8EFB615AB450D209E054FAE6 /* iOS */ = { + isa = PBXGroup; + children = ( + 52554E1C9731D5352FDE9E63F8C5466B /* Accelerate.framework */, + 872D7EFA572ECEE8EF993C27196E16DD /* CFNetwork.framework */, + 4207BEE6DFA63E5CF69828DD467E9674 /* Foundation.framework */, + ); + name = iOS; + sourceTree = ""; + }; + 82B9418FC740377266C89B55CF21AC69 /* Kingfisher */ = { + isa = PBXGroup; + children = ( + 846DDB743B7772FECA5E9D40134868B5 /* AnimatedImageView.swift */, + 753CD1C6CC020253A407CE3A8E5EB836 /* AuthenticationChallengeResponsable.swift */, + 2123CB53EEEB503948A4474AACCB3C9E /* AVAssetImageDataProvider.swift */, + 1660268DDCE579590238085654AC6112 /* Box.swift */, + C719A4208504FBE21E15E8FD30265002 /* CacheSerializer.swift */, + D1963CF85C64A6FC35B9C305D5FCBDE9 /* CallbackQueue.swift */, + 5CE9357E1A67B25C9FE1F8E09BCB188F /* CPListItem+Kingfisher.swift */, + C73D792E956EB3F2432C8962719CBC4E /* Delegate.swift */, + DB1621D1356737AD361FF017ACCEE879 /* DiskStorage.swift */, + CD9386FFA38863D2A3273C631322F7E9 /* ExtensionHelpers.swift */, + 7C1C444C537BD2AF05A4C03C1F164B81 /* Filter.swift */, + 7BA40FE37EBE7C8A2600A0D47E953ADB /* FormatIndicatedCacheSerializer.swift */, + 8783EAE5B7FBAD9F83129629AC9B5D7E /* GIFAnimatedImage.swift */, + 594877CA38F712D12ED1A3BFBBEB35F4 /* GraphicsContext.swift */, + 14A111B0125B3332DD41B6A107BC684A /* Image.swift */, + 8A77EA2F4CBF8F9530A462A4AA2C5489 /* ImageBinder.swift */, + F1B175696C3EE0E048FA7942F2D65B04 /* ImageCache.swift */, + 95D8F643085C53A1ECEB528A1FEA2DF7 /* ImageContext.swift */, + EC5CE11A43BCD442A68F715BC4F23064 /* ImageDataProcessor.swift */, + D3F20DF84A10C6732F7675B9AE55FCEF /* ImageDataProvider.swift */, + 8310D3804BBCE7E2222FA286EAB90A10 /* ImageDownloader.swift */, + 78B54A567196097C12B5651EB5CAE227 /* ImageDownloaderDelegate.swift */, + A0F720C753C91D9209605C6EF0700D76 /* ImageDrawing.swift */, + 8189375A0C7040CC85F487DF8DDD07F8 /* ImageFormat.swift */, + B14AD7EC93901D8E7BA191534B92A603 /* ImageModifier.swift */, + C099B50BD50310DBD0C05306CF6C398A /* ImagePrefetcher.swift */, + D3BD5DF969085678D2AD058864789972 /* ImageProcessor.swift */, + 4BA2EBCF6C82576ECF70AB7D5052288C /* ImageProgressive.swift */, + 2E005D09C75B7939241EBC3ACF8725EF /* ImageTransition.swift */, + 4E20DD5C3CA00ECE9097F38C59F35FC5 /* ImageView+Kingfisher.swift */, + 74D47EC0B111D55E1C5BA1EBACDAED47 /* Indicator.swift */, + 969DB90E32B1D987FF5B6A47A8684A36 /* KF.swift */, + B8708766B4E86A2178888E688318B7A6 /* KFAnimatedImage.swift */, + 0397017297B9CF552EDB2CBB2EB4D702 /* KFImage.swift */, + 8BAD8AFCC4A45BB686B716BE51FBB9C5 /* KFImageOptions.swift */, + 5C2FB870012F9A9F06B36C9892BD2495 /* KFImageProtocol.swift */, + 4C70F8841D47B6108745F20EAF1B7319 /* KFImageRenderer.swift */, + 173CCF61D3B200198ED44DBF6E14A6C4 /* KFOptionsSetter.swift */, + D965E448753D59388378FF252200AE28 /* Kingfisher.swift */, + 45DA6997549500684C8FDCAD08448041 /* KingfisherError.swift */, + 38B418820BDE7F9EAB6033E95EF2DD39 /* KingfisherManager.swift */, + 7A75B8072A89388F54D328CC33074C05 /* KingfisherOptionsInfo.swift */, + 038539E8C2329F87853CB519948BE64D /* MemoryStorage.swift */, + 5B026EECB48C75BB8D4373B876D5D757 /* NSButton+Kingfisher.swift */, + 8976B65457E61E8AD7899E4D740FDDBF /* NSTextAttachment+Kingfisher.swift */, + AF422F832F0B72ABF641D5B011E1ADF2 /* Placeholder.swift */, + 87EE52438F504132352D1A803B540129 /* RedirectHandler.swift */, + 73282384CDDE200004F6A2A982D8F9C0 /* RequestModifier.swift */, + 38732C512E987D0D3209963CDA609519 /* Resource.swift */, + DCAD0BEC0DDFCCEE5BD14F65FA4757D5 /* Result.swift */, + 42C98E9C3712ADEC843BB1445B0B79DD /* RetryStrategy.swift */, + 800601AF004FCC2E83F7E9FE2F9FEC22 /* Runtime.swift */, + C898643E7C365B2110EEECE2E024FF59 /* SessionDataTask.swift */, + 035700EF14CCE6A36A07A5D604252056 /* SessionDelegate.swift */, + 5CE33896B5F0FA3F4B2DE04BBED0806C /* SizeExtensions.swift */, + C005B6108292C74048FE29FDBB3A6811 /* Source.swift */, + 02D56418189CE2180CD551B09EE03069 /* Storage.swift */, + AF0090EDDDE993069035E68659AB6DE8 /* String+MD5.swift */, + 666EDC6F462EC56433A275A25AE0A312 /* TVMonogramView+Kingfisher.swift */, + 309A7B348C7A018E85DBA902D455347F /* UIButton+Kingfisher.swift */, + 7CD2494752BF402630EBF199135EBDF7 /* WKInterfaceImage+Kingfisher.swift */, + 8C53F42400662010863BF5F0C5B6B039 /* Support Files */, + ); + name = Kingfisher; + path = Kingfisher; + sourceTree = ""; + }; + 8475D0F7A2B0606084B0D312E1AE48A2 /* Support Files */ = { + isa = PBXGroup; + children = ( + 6C8DE69DEBEF6E67F64F0F670A5C73E4 /* RxCocoa.modulemap */, + 9852B9017511004032B9FF1F04C8A653 /* RxCocoa-dummy.m */, + 32467DC6BA07C61A2C55C6C511829800 /* RxCocoa-Info.plist */, + E58790ED179A147D4141D43416EC9FCA /* RxCocoa-prefix.pch */, + AABE5D7EBB5C1664F6279707E9AA7519 /* RxCocoa-umbrella.h */, + 7B38A37EDADBCE6A4E37BDA273C433F8 /* RxCocoa.debug.xcconfig */, + 32ED16D862E2C699D96329A575941E33 /* RxCocoa.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxCocoa"; + sourceTree = ""; + }; + 87EA9EE1D4B48F1FD235180C2CADBCA9 /* Products */ = { + isa = PBXGroup; + children = ( + C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */, + 96770B0B10FC006B31FA2E9FF84EE421 /* Pods-Nasa */, + A9FE34A16F0C6916FF506BA129C5B821 /* Pods-Nasa-NasaUITests */, + 261267E349D9BE7E2A6FB40337853A81 /* Pods-NasaTests */, + BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */, + FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */, + 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */, + ); + name = Products; + sourceTree = ""; + }; + 8C53F42400662010863BF5F0C5B6B039 /* Support Files */ = { + isa = PBXGroup; + children = ( + 365683D075B5D9565B5FF3C8C946E3BB /* Kingfisher.modulemap */, + 79A4AC560B432B2A9F0D7F8562BA173D /* Kingfisher-dummy.m */, + 930C79BF985FF7032A75C1449AB1A9C9 /* Kingfisher-Info.plist */, + FB493FA46A5123A0276CD8F3494A8BF2 /* Kingfisher-prefix.pch */, + B7FCD356D832308B24DE9B50105999F0 /* Kingfisher-umbrella.h */, + EBAFF86672E46BDCF016A36E670BA43A /* Kingfisher.debug.xcconfig */, + 8A3A20480CFDF96D43D7E6857FBEA137 /* Kingfisher.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/Kingfisher"; + sourceTree = ""; + }; + A5CC64F8D8C95DF5DD041DEE9D327D8D /* Support Files */ = { + isa = PBXGroup; + children = ( + 917D5B05E05F1095E9C9666C8A87701F /* RxSwift.modulemap */, + 7638CD1C41EA2C2D4C359A360E13A543 /* RxSwift-dummy.m */, + 942E6CE9A41E65156A28227D9167A46B /* RxSwift-Info.plist */, + 979FABB5D4BD34FCD495B3AC7A02A963 /* RxSwift-prefix.pch */, + 8F2FD26566A807497EDC01AA580EF703 /* RxSwift-umbrella.h */, + BE3CAC3B8C77ADA995F99AB865199E01 /* RxSwift.debug.xcconfig */, + B44BEF8F0C8D5BE9C952898810B8CB65 /* RxSwift.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxSwift"; + sourceTree = ""; + }; + AEADAFCA8C4EEA48E04B28E74EC1ED77 /* Pods-Nasa */ = { + isa = PBXGroup; + children = ( + 79D816301584854A2E79BDCABB77D889 /* Pods-Nasa.modulemap */, + 689BA627F03E170B29DF442DCBE59791 /* Pods-Nasa-acknowledgements.markdown */, + 6990B2F815BED4524E85E6D963A49D0A /* Pods-Nasa-acknowledgements.plist */, + DD44EA86799AAB2D629CF2C684F4F639 /* Pods-Nasa-dummy.m */, + 68C563B3EFD584330BB6C2F9AF354DFA /* Pods-Nasa-frameworks.sh */, + 0DB55FE8C794B5AA61DC95770B9C14DB /* Pods-Nasa-Info.plist */, + AB9D6840C14D5277550F97807BD7568A /* Pods-Nasa-umbrella.h */, + 1AC15CC5C4A22DE8A1AD51D3064CF0C2 /* Pods-Nasa.debug.xcconfig */, + 7A1C2B0C119BAFB3E2F50B4DC1622CB8 /* Pods-Nasa.release.xcconfig */, + ); + name = "Pods-Nasa"; + path = "Target Support Files/Pods-Nasa"; + sourceTree = ""; + }; + CF1408CF629C7361332E53B88F7BD30C = { + isa = PBXGroup; + children = ( + 9D940727FF8FB9C785EB98E56350EF41 /* Podfile */, + 03C5C200A0787E300053CFA8F53CA094 /* Frameworks */, + 44EFFC69ABD05878DE3AB5CDCCE663B8 /* Pods */, + 87EA9EE1D4B48F1FD235180C2CADBCA9 /* Products */, + FA8735F6FB9C5CE3E74107A4DA27551C /* Targets Support Files */, + ); + sourceTree = ""; + }; + E4AACEFCA765BC30E0459AA99C4975B6 /* Support Files */ = { + isa = PBXGroup; + children = ( + 61D85AF8FA6907C8221FFE1E3C7567A4 /* RxRelay.modulemap */, + 9787B8B668795376E1710C2864466F71 /* RxRelay-dummy.m */, + 95AE13711B328E40447B5559B99BF4C4 /* RxRelay-Info.plist */, + 2E0CB6EFC6AEA4550CC2852CC870C571 /* RxRelay-prefix.pch */, + FADB38E9C9FD65A133C879209C9C2021 /* RxRelay-umbrella.h */, + 19633EC1F09BD3DF99FDB112C14031A0 /* RxRelay.debug.xcconfig */, + 56EEDAC142A8697D3F3369C0CB954CE7 /* RxRelay.release.xcconfig */, + ); + name = "Support Files"; + path = "../Target Support Files/RxRelay"; + sourceTree = ""; + }; + F8461427E92F2639D770B7116935D392 /* RxRelay */ = { + isa = PBXGroup; + children = ( + C0B44943E43480310387EA9E42DDF970 /* BehaviorRelay.swift */, + ACB9B8802E98717CBF0CF019F0AC320A /* Observable+Bind.swift */, + 0F3EFD230ACBFF33D75339D80A4DBCF2 /* PublishRelay.swift */, + AF67A85F485522B5F5548FE67FDC2D2E /* ReplayRelay.swift */, + 3E514D961A1E4FF8A88B9A696859CEF8 /* Utils.swift */, + E4AACEFCA765BC30E0459AA99C4975B6 /* Support Files */, + ); + name = RxRelay; + path = RxRelay; + sourceTree = ""; + }; + FA8735F6FB9C5CE3E74107A4DA27551C /* Targets Support Files */ = { + isa = PBXGroup; + children = ( + AEADAFCA8C4EEA48E04B28E74EC1ED77 /* Pods-Nasa */, + 5795C872AD31AE1B6342D8422707186B /* Pods-Nasa-NasaUITests */, + 527D0FCD2E336B08C82B4AEAC26A6D56 /* Pods-NasaTests */, + ); + name = "Targets Support Files"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + 1636FCAD17E4800F64DBA2B1BA737C7D /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 1AF3BF0EDE10F429386594F787838C1B /* _RX.h in Headers */, + E6A1BF57511CE77AE62E000F61A5F48F /* _RXDelegateProxy.h in Headers */, + 0422FC5745E406CB752E9497A2F56EA9 /* _RXKVOObserver.h in Headers */, + D8A4FE44301CF797B3E9655FA9F80FA6 /* _RXObjCRuntime.h in Headers */, + 3AFEA39C21C700AAB86C4ACD9436D357 /* RxCocoa.h in Headers */, + 59691189B7A014BB0230561AC0A489A6 /* RxCocoa-umbrella.h in Headers */, + 4994F1CABB9926703D82BA0D9D66321C /* RxCocoaRuntime.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 433499DD7668F5EF9EBDC6638A968C11 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E325FBE64C7EAE36B7485D3015719C4D /* RxSwift-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 5CEC4F3B8A3FAADF39C399D24B7779B1 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 2CE4463435DA3DA87408995F74475409 /* Pods-Nasa-NasaUITests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7AE52B176E9872452FD890FC7F460CE1 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 122980E44B15C64CF0B14DC94D7EB5C9 /* Kingfisher-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A9A154111F1EED92700DA0CC634E3C6B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + ADE53937ED877CC7327490B8C29AC440 /* Pods-NasaTests-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E0B97B21890499C3D4B8287BD3511214 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 278EB57FA625A697EB8B7A0D8124AC38 /* RxRelay-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + ED7987EDCD59AFC463BA740D14371478 /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + 8F711FCC712DF6B2EB35CB9039C4BD6D /* Pods-Nasa-umbrella.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */ = { + isa = PBXNativeTarget; + buildConfigurationList = A65D81D102BEC6604A21F09FF2C80B0C /* Build configuration list for PBXNativeTarget "RxRelay" */; + buildPhases = ( + E0B97B21890499C3D4B8287BD3511214 /* Headers */, + A54F0392D8662DF0C21911032C9B5F28 /* Sources */, + C20E50D4AB3493E8ADF683FE3A690EFD /* Frameworks */, + 9323127D466B2018E0C3ADE4E1B07F1A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + AFA24F454A287547C7E0D60144D4A0D0 /* PBXTargetDependency */, + ); + name = RxRelay; + productName = RxRelay; + productReference = FF8B264DFE802855D5D67E7CDDABFC3C /* RxRelay */; + productType = "com.apple.product-type.framework"; + }; + 4E8075B1A51ABE23AC12835F54826A67 /* Pods-NasaTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 1DCA7609A5ED259FE6835035578C6D52 /* Build configuration list for PBXNativeTarget "Pods-NasaTests" */; + buildPhases = ( + A9A154111F1EED92700DA0CC634E3C6B /* Headers */, + CD745B6F6D2759C313FEADD4E7CE4AE4 /* Sources */, + 22163383E9B72995E87D3CD9654FD971 /* Frameworks */, + A096D720A2AB844C2FBD4B28EA10AC61 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 6DEB3C1ABB560ABB8CAAD4B49165EDAD /* PBXTargetDependency */, + ); + name = "Pods-NasaTests"; + productName = Pods_NasaTests; + productReference = 261267E349D9BE7E2A6FB40337853A81 /* Pods-NasaTests */; + productType = "com.apple.product-type.framework"; + }; + 740C6653FCAC2CB4D1FEC05F81E04550 /* Pods-Nasa-NasaUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 3A14D11DE6D57CFFF29284B2A5A41C7D /* Build configuration list for PBXNativeTarget "Pods-Nasa-NasaUITests" */; + buildPhases = ( + 5CEC4F3B8A3FAADF39C399D24B7779B1 /* Headers */, + 2537CF3034574D7CDF6311D776AF82EA /* Sources */, + C7D08BE715F3F3A083EB3B03F42D58DF /* Frameworks */, + 07D5D9B00C1AA5B339F26BCC07E2970A /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + F04293B702898D187579F1B07E95E929 /* PBXTargetDependency */, + 36DF872A6FDDE70718F7FAD72D0BC0C6 /* PBXTargetDependency */, + C0921B6A0AF92D468064CB0E0E013426 /* PBXTargetDependency */, + 6FF007392584F2444B28F075A57B324B /* PBXTargetDependency */, + ); + name = "Pods-Nasa-NasaUITests"; + productName = Pods_Nasa_NasaUITests; + productReference = A9FE34A16F0C6916FF506BA129C5B821 /* Pods-Nasa-NasaUITests */; + productType = "com.apple.product-type.framework"; + }; + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */ = { + isa = PBXNativeTarget; + buildConfigurationList = 25AE2A8304AA799A1A0A4FD6C1577310 /* Build configuration list for PBXNativeTarget "RxCocoa" */; + buildPhases = ( + 1636FCAD17E4800F64DBA2B1BA737C7D /* Headers */, + F3A28FDE156C7CAA6CA5FC5646AD34F4 /* Sources */, + 4DAD51760C3A529B5ACA9477FDA8E31A /* Frameworks */, + A8D6AD1BD6863B21A8AB1DB161659DB8 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + BF2EDCAB42AFE4FE61D849C7599D6400 /* PBXTargetDependency */, + FAFDD3DF82FA08744030F2830C5E1F4F /* PBXTargetDependency */, + ); + name = RxCocoa; + productName = RxCocoa; + productReference = BC432FD48A5932251F1CAFBC4BF74894 /* RxCocoa */; + productType = "com.apple.product-type.framework"; + }; + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */ = { + isa = PBXNativeTarget; + buildConfigurationList = 69ACD8654734266A348C6FF68E734010 /* Build configuration list for PBXNativeTarget "Kingfisher" */; + buildPhases = ( + 7AE52B176E9872452FD890FC7F460CE1 /* Headers */, + 3C1DA515D615F8CE75565ACE14378882 /* Sources */, + 81DB1665E1495609510BA493822E5A85 /* Frameworks */, + CFEB3E9FD20A01120B40D65B82D8F26F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Kingfisher; + productName = Kingfisher; + productReference = C3F44C782D64D7EB20B61CE3844EBFAD /* Kingfisher */; + productType = "com.apple.product-type.framework"; + }; + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */ = { + isa = PBXNativeTarget; + buildConfigurationList = 6A19B0B51830991FE5CDD4E8FD5C0CB4 /* Build configuration list for PBXNativeTarget "RxSwift" */; + buildPhases = ( + 433499DD7668F5EF9EBDC6638A968C11 /* Headers */, + 7CE717C26BA7D3CCF57401D88165B15D /* Sources */, + 0B2DEE70C6D6B3A1DFFCDD138F4B02E5 /* Frameworks */, + 9BA6709BA8BF6666E470AB5BFF732F39 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = RxSwift; + productName = RxSwift; + productReference = 809C5FAB588354C9BA37DC3EAB8CB45C /* RxSwift */; + productType = "com.apple.product-type.framework"; + }; + F889E6876E3193B7BFC4912BB2571351 /* Pods-Nasa */ = { + isa = PBXNativeTarget; + buildConfigurationList = E08BCE0FEFD2DE1C60BC6919223BC216 /* Build configuration list for PBXNativeTarget "Pods-Nasa" */; + buildPhases = ( + ED7987EDCD59AFC463BA740D14371478 /* Headers */, + 9343226019B9E714ED2DC0E158026C82 /* Sources */, + A37D984C9C15FAC466569401CE96920F /* Frameworks */, + 444ECC1A4401D9386F5F015540C88D51 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 4DD515A7790615A3022120D28FD1F0D0 /* PBXTargetDependency */, + 066FF6E7D2AD331E0AE036243A462001 /* PBXTargetDependency */, + ACA1636861EA193B8331F57D55AE11ED /* PBXTargetDependency */, + 3ECD2D538CECDA0F3E6C17C7A165C070 /* PBXTargetDependency */, + ); + name = "Pods-Nasa"; + productName = Pods_Nasa; + productReference = 96770B0B10FC006B31FA2E9FF84EE421 /* Pods-Nasa */; + productType = "com.apple.product-type.framework"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + BFDFE7DC352907FC980B868725387E98 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1240; + LastUpgradeCheck = 1240; + }; + buildConfigurationList = 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */; + compatibilityVersion = "Xcode 13.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + Base, + en, + ); + mainGroup = CF1408CF629C7361332E53B88F7BD30C; + productRefGroup = 87EA9EE1D4B48F1FD235180C2CADBCA9 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */, + F889E6876E3193B7BFC4912BB2571351 /* Pods-Nasa */, + 740C6653FCAC2CB4D1FEC05F81E04550 /* Pods-Nasa-NasaUITests */, + 4E8075B1A51ABE23AC12835F54826A67 /* Pods-NasaTests */, + 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */, + 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */, + EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 07D5D9B00C1AA5B339F26BCC07E2970A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 444ECC1A4401D9386F5F015540C88D51 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9323127D466B2018E0C3ADE4E1B07F1A /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9BA6709BA8BF6666E470AB5BFF732F39 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A096D720A2AB844C2FBD4B28EA10AC61 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A8D6AD1BD6863B21A8AB1DB161659DB8 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CFEB3E9FD20A01120B40D65B82D8F26F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2537CF3034574D7CDF6311D776AF82EA /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + FE28DDABA4223991BF4B39E291899EC1 /* Pods-Nasa-NasaUITests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 3C1DA515D615F8CE75565ACE14378882 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 1952485AFF7A1BCCA4D4B142E82FE627 /* AnimatedImageView.swift in Sources */, + 243D7CFE1D56ED80ACB2B3E71B4CB603 /* AuthenticationChallengeResponsable.swift in Sources */, + D603AA58EF97D461A57B2B1BCB883868 /* AVAssetImageDataProvider.swift in Sources */, + B25E07EA645911443A38DA1E68166156 /* Box.swift in Sources */, + CD7AC3E1C98EA54F7C05C36C52805220 /* CacheSerializer.swift in Sources */, + FF09824309346665E2F1F7F5A45FB10F /* CallbackQueue.swift in Sources */, + DBB8088E14A2ADEDB1CD840BAC835267 /* CPListItem+Kingfisher.swift in Sources */, + 457BE444ED617FA7D6851D6DAA9D7234 /* Delegate.swift in Sources */, + 1FEE89BF952BE7ACA46E642DA2E48CA2 /* DiskStorage.swift in Sources */, + 1185A2B40E14F2FCBC761FC99777CAD8 /* ExtensionHelpers.swift in Sources */, + 3AF7DB9AEFF47F1F7F91AF28440E4AC6 /* Filter.swift in Sources */, + DE532EF7D50A9CF68587DAD4C1A02BD7 /* FormatIndicatedCacheSerializer.swift in Sources */, + F24021BDE9B42D604E3341CAD8E34759 /* GIFAnimatedImage.swift in Sources */, + 582D59E0D2EF62E0575933C99B393704 /* GraphicsContext.swift in Sources */, + 70FEC06F54286257E1BA1ECA0C99198D /* Image.swift in Sources */, + 1AA89F327105C026976BF6E831B193A2 /* ImageBinder.swift in Sources */, + ED0C8BA7560D7324587B353E0960479F /* ImageCache.swift in Sources */, + F5414F8A5B40521D0E4AEEB28378CB49 /* ImageContext.swift in Sources */, + 80738D8956C9987CCCEDF551961E5069 /* ImageDataProcessor.swift in Sources */, + 0285857A24F66E925987A5876F0BE63B /* ImageDataProvider.swift in Sources */, + DD72DC30CF19FFC81AB19CD0B074000D /* ImageDownloader.swift in Sources */, + 881A35B28D93C56E46E305F6138B1A76 /* ImageDownloaderDelegate.swift in Sources */, + DAFC6CE6321395CF4523DD66DADBB9BA /* ImageDrawing.swift in Sources */, + E6D6C7D5E458A05CC736C340F853E9F6 /* ImageFormat.swift in Sources */, + F54DE563418B1783D6EC491A0C3A05DB /* ImageModifier.swift in Sources */, + 00BEA6029C428FEE644AC3D42AD83282 /* ImagePrefetcher.swift in Sources */, + EF9C4588CDA85AED8BBCF77451B2A35B /* ImageProcessor.swift in Sources */, + 5F852F38CBC282496CCBE37C51324B2F /* ImageProgressive.swift in Sources */, + 29FF13E23FD52E46D30530549410AD7C /* ImageTransition.swift in Sources */, + E5B664771063F1A9A372519A8466860B /* ImageView+Kingfisher.swift in Sources */, + DFCDE4638265B4CCD494ECA5D560DBEE /* Indicator.swift in Sources */, + DF4563832C19B8582C810BF502A5CA29 /* KF.swift in Sources */, + 7FFE4021A4F14124342AD41CE1117B3E /* KFAnimatedImage.swift in Sources */, + 5E27DD292D3A55657712DD7AFA7B8FCA /* KFImage.swift in Sources */, + 5ADB30DD9A03859018550A999ACB0652 /* KFImageOptions.swift in Sources */, + F9537B023E24AC4A724E301F7E372491 /* KFImageProtocol.swift in Sources */, + 0510E8EA51914CB2176AD0F173937FAB /* KFImageRenderer.swift in Sources */, + A316388A35648CB2987E761771456087 /* KFOptionsSetter.swift in Sources */, + A39D3555EC8B45B7D6B9505DDAF0F117 /* Kingfisher.swift in Sources */, + 4DCA9775E5CCF599460BDB46E77F6FA4 /* Kingfisher-dummy.m in Sources */, + 4F37E521D341C47CE73DDCF21BA95A52 /* KingfisherError.swift in Sources */, + 1FE693B5ACC6AD7320CEFC20B64546E4 /* KingfisherManager.swift in Sources */, + 05228565AAA7FCED4BAFB2B7EF71D53D /* KingfisherOptionsInfo.swift in Sources */, + 1FD2928BC156D990D68B105F518C60B6 /* MemoryStorage.swift in Sources */, + 059639E700DEFAEF08F56484E5F67BE7 /* NSButton+Kingfisher.swift in Sources */, + 59BC9047F4BEBBC06235608D974E230D /* NSTextAttachment+Kingfisher.swift in Sources */, + 506128E1CC424E40E2691546D9547549 /* Placeholder.swift in Sources */, + 2BE89C24BFD3FB663E37C607C289B3B6 /* RedirectHandler.swift in Sources */, + 509490FB1D30FEC59AE4BC21AEEBB7BB /* RequestModifier.swift in Sources */, + 22BD1346F66BFCB129AAA44EEF322AC9 /* Resource.swift in Sources */, + A88A844D5356E1690E445024CB796E09 /* Result.swift in Sources */, + 22216C300C763044344B9DBF97317E63 /* RetryStrategy.swift in Sources */, + EBB32304E8DD4BA115454E0050D47DED /* Runtime.swift in Sources */, + 7C7418FF01DD7BB909719682B634A8A5 /* SessionDataTask.swift in Sources */, + 0ED8FBFD9A86D21BF69137EC9350E575 /* SessionDelegate.swift in Sources */, + 57FC31B14C753B5C63CEF00560F8A6EF /* SizeExtensions.swift in Sources */, + 9B0A78AC22E7EDA755F51D86527E2D9C /* Source.swift in Sources */, + 25FC036BEA33CAB5D80F5A41644535D3 /* Storage.swift in Sources */, + BD382E78580D295D10100678D4F66A76 /* String+MD5.swift in Sources */, + F17B1F8F2B6580343025237455A29D61 /* TVMonogramView+Kingfisher.swift in Sources */, + 082EDC820D76DF95C71A5018112DE512 /* UIButton+Kingfisher.swift in Sources */, + 9F5FE22DA95B66B8DC21CB13BE25EC9B /* WKInterfaceImage+Kingfisher.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 7CE717C26BA7D3CCF57401D88165B15D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 45C55DE926122B7CA9DF1C302B5D7333 /* AddRef.swift in Sources */, + 74CA2DBA0EA27472257A1A84BCE469A2 /* Amb.swift in Sources */, + D72264C517560E7A2FD582F9D6B4118B /* AnonymousDisposable.swift in Sources */, + CCE8548CB0EC76CBFFB5A6BC4DC3259D /* AnonymousObserver.swift in Sources */, + 2E150C92EA41FEC6C98EAA399F2F161F /* AnyObserver.swift in Sources */, + 878180FF94F4BA823AA65468500D5BA4 /* AsMaybe.swift in Sources */, + EB6F2FDEACD788322B2E28311943E7B7 /* AsSingle.swift in Sources */, + 30BD172B405327E404674D436B0B1F2A /* AsyncLock.swift in Sources */, + E80D3EAA0259F3FF3F0F3689A3FB0CAB /* AsyncSubject.swift in Sources */, + 91A2335C5506EBC38DD438FEC729799A /* AtomicInt.swift in Sources */, + A2C2E9A7817336BA783ABC7C897D7AFB /* Bag.swift in Sources */, + 621CFB9D43A48783BC730CFE04CA02CE /* Bag+Rx.swift in Sources */, + 95D5EE81CAE35CDDA64E2A0CA4B1DC22 /* BehaviorSubject.swift in Sources */, + AAC2AA6895DE07EB4F655B9A54AC4288 /* BinaryDisposable.swift in Sources */, + 36594622DE161AE6B8212571B98F6A52 /* Binder.swift in Sources */, + EED41045A58EC4616734150746621CCA /* BooleanDisposable.swift in Sources */, + 183BC936A084A620928D8EDC52132B8C /* Buffer.swift in Sources */, + 3D11D3661303538BCF5F69E28AEA58E6 /* Cancelable.swift in Sources */, + D5504813E976DA19C5FD8EDA59CC6B94 /* Catch.swift in Sources */, + D3174D3F6661D8ACEE1D29D7DE636C8C /* CombineLatest.swift in Sources */, + F1CA26207E3EE137292D02EF9A752AD2 /* CombineLatest+arity.swift in Sources */, + 7D69A909D084D6287BDD0FCEBEC34E0D /* CombineLatest+Collection.swift in Sources */, + 6C2C2663370962E2D50CAE56B42B0F81 /* CompactMap.swift in Sources */, + 39A67C9747B097343EA9D1B7CC8FA14C /* Completable.swift in Sources */, + 071DE38A1044FDA3EC1353CC7B9D6773 /* Completable+AndThen.swift in Sources */, + B2251C3E16EFC789C45A236A231D703D /* CompositeDisposable.swift in Sources */, + 7083081E60074026B4DBACA8BE6E1DD3 /* Concat.swift in Sources */, + 63719AEFBD0D86AE09823E0E223A33DE /* ConcurrentDispatchQueueScheduler.swift in Sources */, + D50A2E52EEEA0518E18582D63236FB61 /* ConcurrentMainScheduler.swift in Sources */, + 737E35F9D90D0B01AFE31C8117921E38 /* ConnectableObservableType.swift in Sources */, + 59E9FDBE2B850DF42485D950735E3AB0 /* Create.swift in Sources */, + DC854B01B452498F9EAD1C28E7B0DED2 /* CurrentThreadScheduler.swift in Sources */, + 116059B3C9097D472A5474217E29A4EA /* Date+Dispatch.swift in Sources */, + 697246690DE02DD236B8CCD3531EF331 /* Debounce.swift in Sources */, + 9106C93AF453AE86FB40B8269DD07623 /* Debug.swift in Sources */, + D68527405AA172C43B7F0FA120A02CE8 /* Decode.swift in Sources */, + 202148F555B1DD5F0AA74F682713B0BF /* DefaultIfEmpty.swift in Sources */, + 29259059754655C94419B9E2810A70B9 /* Deferred.swift in Sources */, + A03818F258B2596221C3D55B8960D2FA /* Delay.swift in Sources */, + 78B5CD94C6FA08D4E72CA298DED2F4E2 /* DelaySubscription.swift in Sources */, + 0B6974B6BDA652DC64A58317C2934C3D /* Dematerialize.swift in Sources */, + D2DCF994A072EB2C46DD41F92E885951 /* DispatchQueue+Extensions.swift in Sources */, + 0BF12117307EAFA50B59A5D057C67DF7 /* DispatchQueueConfiguration.swift in Sources */, + 9EDCD950572BAABB6B6C562D2EAF0BBB /* Disposable.swift in Sources */, + 0D5B9CA194B784F86BC10A145D1B457B /* Disposables.swift in Sources */, + F3F9D494D3005899EDCC6CE9A7CF87A1 /* DisposeBag.swift in Sources */, + BC18682BD8437EC691E553070C540FAC /* DisposeBase.swift in Sources */, + 5BF6B2D545C5849CE38838A7B50F328B /* DistinctUntilChanged.swift in Sources */, + 94A8D65E45C085A877A5470503B8DFF6 /* Do.swift in Sources */, + 16F09B773C24F9947B096E8F1F1CABD9 /* ElementAt.swift in Sources */, + 181A1502BAE999B700D1865E74F0CC48 /* Empty.swift in Sources */, + A8F33D774CCFF1BF6570CB62E85EE7FA /* Enumerated.swift in Sources */, + 28C7C978A5E7DCCAF9F4B229786B3F63 /* Error.swift in Sources */, + BAFE9BCC959743F69B4FC5C11C5AFAD2 /* Errors.swift in Sources */, + 8829BB4B90C734DC9A98316F5133D43F /* Event.swift in Sources */, + ED8365B521BFF4D70FBFE3FCCFEB3BCD /* Filter.swift in Sources */, + A2B7773B46906EF93E44C457E9762CE5 /* First.swift in Sources */, + 7F2E9C8F62ED31B2A725167BC98A7A0F /* Generate.swift in Sources */, + 8D8C2C771785DC4DA1762E259A7EB99A /* GroupBy.swift in Sources */, + A2BABA3A0A7259042C76634239AC9700 /* GroupedObservable.swift in Sources */, + FC788CC1807407D607BC5102895D31F5 /* HistoricalScheduler.swift in Sources */, + 9CA691C106799A02C3AB7D059BA1218D /* HistoricalSchedulerTimeConverter.swift in Sources */, + 2B767CB910375F76560C6F5694609383 /* ImmediateSchedulerType.swift in Sources */, + A5B0A0AFB5C7D852611CEBA072AF7D01 /* Infallible.swift in Sources */, + E85A348CBE05F09872013FEB3BC58260 /* Infallible+CombineLatest+arity.swift in Sources */, + 808077857F59E5C539F97944692D0DAD /* Infallible+Create.swift in Sources */, + 2BC1AD613A135B6EA990426C5DA41E0D /* Infallible+Operators.swift in Sources */, + 1ADC9B7900EB98DFE683CBDEDBE86E1A /* Infallible+Zip+arity.swift in Sources */, + 19999942346C1837E2A7C7024014A164 /* InfiniteSequence.swift in Sources */, + BA225CB88C5E94F83E8C83D40813063F /* InvocableScheduledItem.swift in Sources */, + AF6DB912CA426F93811EBEC30249C1B9 /* InvocableType.swift in Sources */, + BB019F48ED71BE9E9056495550AFF6C2 /* Just.swift in Sources */, + CC93EE3296F80DAA1790810622FD239F /* Lock.swift in Sources */, + 0F394A11701EB823EB92A842A34424A2 /* LockOwnerType.swift in Sources */, + EABF745B6F9EC4CC4BDE22085C5BD0AA /* MainScheduler.swift in Sources */, + 78B25E6EFEBD7B467363581B07A681E8 /* Map.swift in Sources */, + 1E07E7F80F58C41D52DA88B1495D4C58 /* Materialize.swift in Sources */, + 24CD1D4CE6B2BF7F57045D6C4281F17E /* Maybe.swift in Sources */, + 2C82D96E13E491087D3F2EACF9294C8E /* Merge.swift in Sources */, + 32B6121B1923DDF56E9533E23DD0F316 /* Multicast.swift in Sources */, + 87FDDD76563F9CDFD1461E61884B3626 /* Never.swift in Sources */, + 02F9A9BE4E45DB08E4427B95D0BCFA16 /* NopDisposable.swift in Sources */, + 77FE06C54FDBF0EC6AA641C26F174953 /* Observable.swift in Sources */, + 070EC803A862D795256CF9DBA627E810 /* ObservableConvertibleType.swift in Sources */, + B4778F823B87F7C8661123F4E13E64A6 /* ObservableConvertibleType+Infallible.swift in Sources */, + DFEDD9705BACB387CEB43C55A8D094CB /* ObservableType.swift in Sources */, + FA9FC218B9751BE5A9E9262A57EE9AC8 /* ObservableType+Extensions.swift in Sources */, + A314A7F05FBFAF439E2E1DF9814D15D8 /* ObservableType+PrimitiveSequence.swift in Sources */, + DF7BD87A7AA4A1D1D0FA7D153CC45150 /* ObserveOn.swift in Sources */, + 6A90EDE48F6D19587EAD14EB964C9C49 /* ObserverBase.swift in Sources */, + 74511229A00BD203485536B1A2FE6A52 /* ObserverType.swift in Sources */, + 0D6D0C12EBF3178912A92BF632A29303 /* OperationQueueScheduler.swift in Sources */, + FE4011EF34F7ECDF74BD74E5BF6C7BC9 /* Optional.swift in Sources */, + 9E9E7202016CCEE8F776A5174691BFDF /* Platform.Darwin.swift in Sources */, + 90B552B8FD6CED4AA33BABCC26CD1636 /* Platform.Linux.swift in Sources */, + 07E9184E1F7F568434EB37198DF51C3B /* PrimitiveSequence.swift in Sources */, + 00D58ACCBB52B44325EBC30E58CD3EEE /* PrimitiveSequence+Zip+arity.swift in Sources */, + 7008E2EEAA93681AE2BEADA2C12E43AF /* PriorityQueue.swift in Sources */, + DDA352AB1CDF6337CFFD9B10121D645F /* Producer.swift in Sources */, + 1472453F13469248FCFDB7DA56B7F427 /* PublishSubject.swift in Sources */, + E2EE60D641A784A98A937A9DB57C6FBF /* Queue.swift in Sources */, + 8527110343D87F5878FA0CFEDCF8127C /* Range.swift in Sources */, + 76B214E73D30F27066985B87131AAD1F /* Reactive.swift in Sources */, + F19BCAAD57603E28D9C9902CEA822BAA /* RecursiveLock.swift in Sources */, + 4972C5113D037B1515BE33E59008F381 /* RecursiveScheduler.swift in Sources */, + 59C027CC4112D05795E2B870C33A413D /* Reduce.swift in Sources */, + F2073564BC492BDE23BFFA81C68E7F01 /* RefCountDisposable.swift in Sources */, + 4D8777A12EEDEF2F6FE6190C1DD4F569 /* Repeat.swift in Sources */, + ACB44BCE1A196930E1A4F5142521A663 /* ReplaySubject.swift in Sources */, + 690835CAF47F831971F17CC1667C9FC1 /* RetryWhen.swift in Sources */, + 9DD9C0E721DD2BA2BB1A65CC36A853FD /* Rx.swift in Sources */, + 47A5B1B49A2B0FB00EDFBB6C75FD7C26 /* RxMutableBox.swift in Sources */, + 43473298D54EB1C5498C9A404AD68F06 /* RxSwift-dummy.m in Sources */, + 54AABF5F8E6824B98B89B74ADA7CD631 /* Sample.swift in Sources */, + E931DE06D8C8C59EF029F904A1CFFB69 /* Scan.swift in Sources */, + 2992F474C57FDE1E458D833070188A3A /* ScheduledDisposable.swift in Sources */, + 1E3FBC05EB6DACC9EEAD4C0B6B37472F /* ScheduledItem.swift in Sources */, + 4B8BDB6B894C3EBC0E5463298666223C /* ScheduledItemType.swift in Sources */, + 85F3507E1003F051784AEE2EDDD79CE3 /* SchedulerServices+Emulation.swift in Sources */, + CE4A963C9646C4A4DF444833737E8CE5 /* SchedulerType.swift in Sources */, + FDD9978BA4D886BA722A68E110F92960 /* Sequence.swift in Sources */, + EA9A86994FD60ACCBD1BA962A04E5CFD /* SerialDispatchQueueScheduler.swift in Sources */, + 2D0F32108963808871C79483323D7204 /* SerialDisposable.swift in Sources */, + 9C3504156FD220881BE7D5C20D2B3476 /* ShareReplayScope.swift in Sources */, + 2E00D18294EBA1D2232D1AF0E1BE9D41 /* Single.swift in Sources */, + 79CE0CB43605620DF5B8C9991CFD064A /* SingleAssignmentDisposable.swift in Sources */, + ECBFCBFA5AB28DD7B0981FF11C63A188 /* SingleAsync.swift in Sources */, + 987304A3D1F19D442787D16D84FF3997 /* Sink.swift in Sources */, + 557D81659F1902BDDAE21CA1779EE49B /* Skip.swift in Sources */, + E014B1AAB0FE20A47556484F4890C2EC /* SkipUntil.swift in Sources */, + 57DBC03B00EADA274BDF1CF35024AEC7 /* SkipWhile.swift in Sources */, + 472AF39B5C345EDF67E488A0A667AF4E /* StartWith.swift in Sources */, + 3BBFDACF1500DD143119CB084D8DCBFF /* SubjectType.swift in Sources */, + 59449E02883D41EACB918DCE1802711B /* SubscribeOn.swift in Sources */, + BED3C4158B505B8F85889E5E28918967 /* SubscriptionDisposable.swift in Sources */, + 546E291E507CB1DB5C7D19CD100AD7F3 /* SwiftSupport.swift in Sources */, + 42AC1514E62AD73452FBF69C93C53EE4 /* Switch.swift in Sources */, + D69CF928FC4DDAA1A5D0372E530041DD /* SwitchIfEmpty.swift in Sources */, + BAFE36491C2BEF6B5C023FBF506E12E2 /* SynchronizedDisposeType.swift in Sources */, + 22540EA90BD2532208BC8FF0806E0746 /* SynchronizedOnType.swift in Sources */, + 6E4532D5FA4D25F35F98D55053B0E940 /* SynchronizedUnsubscribeType.swift in Sources */, + A10CA44E513635FB638DA96BCD41CF11 /* TailRecursiveSink.swift in Sources */, + 9F2A7A46B6788182F54B1B981938B6E5 /* Take.swift in Sources */, + A3BA9015009ADD44E04BBB2074550BA7 /* TakeLast.swift in Sources */, + A6D090BA4BBBA08BC6BBEF116C285FB4 /* TakeWithPredicate.swift in Sources */, + 17C3DC7D054023FE2C760209BAD655AC /* Throttle.swift in Sources */, + F7250640EF71B23A578D47417480240B /* Timeout.swift in Sources */, + 21D22789C1145C6FED87DC6EA0F4B032 /* Timer.swift in Sources */, + F7C3BDD52B3C9222621025CBD1447E2E /* ToArray.swift in Sources */, + 675E467D99B81FC6698572D9CCFC8335 /* Using.swift in Sources */, + 89D54B82F748F0FCBFFCBEEE2C060E0C /* VirtualTimeConverterType.swift in Sources */, + 32F572FAB2C08AAF6A3E92B80F621E66 /* VirtualTimeScheduler.swift in Sources */, + C6A9F4EBAFDDF84D305B430316360AF1 /* Window.swift in Sources */, + 382F19611B366911F72D5C9C2A83852C /* WithLatestFrom.swift in Sources */, + 2BDB7D759A930390DD50BAEFF87C8328 /* WithUnretained.swift in Sources */, + C4088D41E491408954E951A09E01B675 /* Zip.swift in Sources */, + B73D4D0288F5437D0B46BFD7B00CB3D3 /* Zip+arity.swift in Sources */, + 7546574D3674274B467AEBA286D42F9F /* Zip+Collection.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 9343226019B9E714ED2DC0E158026C82 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 84830EA28F2245CEC7F64F510522400A /* Pods-Nasa-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A54F0392D8662DF0C21911032C9B5F28 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B091CBCEA9C722C95A2C4D6C425F3487 /* BehaviorRelay.swift in Sources */, + 70F121399B82D87F0CAB4400460A337A /* Observable+Bind.swift in Sources */, + 36194766BE6C29E290145F7F0A7C5DA1 /* PublishRelay.swift in Sources */, + E265565C244D8AB0E9A8DF4A2F71B170 /* ReplayRelay.swift in Sources */, + FFA38111EFF544C8B04BF95703FD7D62 /* RxRelay-dummy.m in Sources */, + 2DEBA024E86F1AFC0D4215AD4A74A4F3 /* Utils.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + CD745B6F6D2759C313FEADD4E7CE4AE4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + CAB964E0FCE2D7C94C0FFF77C793CE74 /* Pods-NasaTests-dummy.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + F3A28FDE156C7CAA6CA5FC5646AD34F4 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + B8E27E8D24CBE6DB22F38E06FFBDB710 /* _RX.m in Sources */, + 4878A6C8BDEF6FCC155719CA93BA9586 /* _RXDelegateProxy.m in Sources */, + 894BF76C4272C38C9E17385110BF4A41 /* _RXKVOObserver.m in Sources */, + 529BDA5E8CE104C4B384017447D0DC60 /* _RXObjCRuntime.m in Sources */, + D709A58FF6A694878122F7D24B4A9913 /* Bag.swift in Sources */, + 9850A80051F5259DF4BD9060DEFE783F /* BehaviorRelay+Driver.swift in Sources */, + 71D5BDF4D210C1DC54AB197B1D2E9D13 /* ControlEvent.swift in Sources */, + 7C0DC741562A17F09F60EB9329DDA7CD /* ControlEvent+Driver.swift in Sources */, + 4F744303AF9B5E7CEF8C3A9327E852B9 /* ControlEvent+Signal.swift in Sources */, + 47B48B7531CE161773DEF0B851D08037 /* ControlProperty.swift in Sources */, + A1985C2CC5030AB984FFA33B94E1E39D /* ControlProperty+Driver.swift in Sources */, + 238C4A1EC8BA1D3A575ADA67F68CD09C /* ControlTarget.swift in Sources */, + 2722C9B25CF57D3AE89825729DEA9BED /* DelegateProxy.swift in Sources */, + 03D894819ECA3CA8F42C578E42D08960 /* DelegateProxyType.swift in Sources */, + 9B6D684A7CCF9470B92E10267E3987CA /* DispatchQueue+Extensions.swift in Sources */, + 5291A92FB6C7E3FB265DC22EDD908884 /* Driver.swift in Sources */, + 09997FDBE8364411FFB6F495729608D2 /* Driver+Subscription.swift in Sources */, + 155D953401DF644E75F2ACE729D00DF2 /* Infallible+Bind.swift in Sources */, + 1B402AACD54B2064A7BC86857F2769DD /* InfiniteSequence.swift in Sources */, + F6F9C34492E47A611E31D2D63F476F13 /* ItemEvents.swift in Sources */, + 28DDBE36EE067086F4925C830D668FBA /* KVORepresentable.swift in Sources */, + 50681D70D26BA315A5DDC1365B4CF0BB /* KVORepresentable+CoreGraphics.swift in Sources */, + A435E4B3FF0B326E880502C6FD3FC987 /* KVORepresentable+Swift.swift in Sources */, + 69537EEBAEE542798C9630CB8F96DF8D /* NotificationCenter+Rx.swift in Sources */, + 171A21B0155EA10267C1DE165A6E1500 /* NSButton+Rx.swift in Sources */, + 3B82FB00AD02652E1801233E5684DB1D /* NSControl+Rx.swift in Sources */, + 7EEED39CE5F3611AB4D7205FD038021E /* NSObject+Rx.swift in Sources */, + 945DBBCB62542CD24B29F83FAFEF13B1 /* NSObject+Rx+KVORepresentable.swift in Sources */, + A2F7FF2AEFF21D78671543FA8CB6A8B3 /* NSObject+Rx+RawRepresentable.swift in Sources */, + AB4875CA5028C3C32274EC2CCDFE9066 /* NSSlider+Rx.swift in Sources */, + 4B745396FD1223BA8532DFE2216E043C /* NSTextField+Rx.swift in Sources */, + 7E3402342205B2DC03468A7FD95F61A9 /* NSTextStorage+Rx.swift in Sources */, + 68623BC382EACE93D53213D1D5AAAD3C /* NSTextView+Rx.swift in Sources */, + 6D8CDC66C950346874056F3F45FAB0FC /* NSView+Rx.swift in Sources */, + 38D0534EDDC37793282AD797DF3CF4B0 /* Observable+Bind.swift in Sources */, + F059BB2BD4F7B156353739A55AEBE2A3 /* ObservableConvertibleType+Driver.swift in Sources */, + B283E0B7BB5A5910188B1B4C7B15FF53 /* ObservableConvertibleType+SharedSequence.swift in Sources */, + 04B641288248D3ACC28E7F707058073B /* ObservableConvertibleType+Signal.swift in Sources */, + 95181366D610146E29AD34636DB9EFB7 /* Platform.Darwin.swift in Sources */, + 0F75B8C82523266A3DF606A5974073AA /* Platform.Linux.swift in Sources */, + CF9DAAEC618DE435A7DF19579DE30AA2 /* PriorityQueue.swift in Sources */, + 210E6BE763C894C38888F5B166A2EA64 /* PublishRelay+Signal.swift in Sources */, + 3D42C9D3EEBE1EAD7E365276753FE99E /* Queue.swift in Sources */, + 14D2C2DC6532CC4AAD73F205B9211DB8 /* RecursiveLock.swift in Sources */, + 022DFEBF3DD3B5B1627278F189254A25 /* RxCocoa.swift in Sources */, + 70527867C4C4C965053E4283F3778986 /* RxCocoa-dummy.m in Sources */, + F387475B1EC3C098254F62698129B612 /* RxCocoaObjCRuntimeError+Extensions.swift in Sources */, + 938B46EF411204D0BEE0A56A7D584D51 /* RxCollectionViewDataSourcePrefetchingProxy.swift in Sources */, + 16EB1EAEF9D5FF0D6E4B221ECB397D63 /* RxCollectionViewDataSourceProxy.swift in Sources */, + F89C351693522F78C6E85B6AAF7B76C4 /* RxCollectionViewDataSourceType.swift in Sources */, + 28D5D9EEAE845C76C8079BD1C77BFE82 /* RxCollectionViewDelegateProxy.swift in Sources */, + 3DD9694A6D1F5035C6C400C6912B9E36 /* RxCollectionViewReactiveArrayDataSource.swift in Sources */, + 44AEBB2D29B9FB87530556A0CEC170F7 /* RxNavigationControllerDelegateProxy.swift in Sources */, + 15D5D77E68C8B6AF20B7056602F7AEBF /* RxPickerViewAdapter.swift in Sources */, + A1194BE78FCE2929CDA65C95CA310EAF /* RxPickerViewDataSourceProxy.swift in Sources */, + 1E9033562EACB851BBAB74F033194B48 /* RxPickerViewDataSourceType.swift in Sources */, + F1DA873728D70AB358E831F18AF284ED /* RxPickerViewDelegateProxy.swift in Sources */, + AA7BBD3390AF2ECAFA1AD576BB69CE15 /* RxScrollViewDelegateProxy.swift in Sources */, + DD724165EF3D8F209BD6EA6EEAA7EA0A /* RxSearchBarDelegateProxy.swift in Sources */, + F219C2A0B49D73B93CEC939FEF1E7AB2 /* RxSearchControllerDelegateProxy.swift in Sources */, + 548B9145185925F281D9B1951379E6D1 /* RxTabBarControllerDelegateProxy.swift in Sources */, + 4838B3C8759DACF738F61BF91100379A /* RxTabBarDelegateProxy.swift in Sources */, + FDB6B50F3AF189818D8962D74E37D552 /* RxTableViewDataSourcePrefetchingProxy.swift in Sources */, + D583F8FC3BFE7CE7368F5FE75679F388 /* RxTableViewDataSourceProxy.swift in Sources */, + C4D350D569A2B6567E087ED515A93EE2 /* RxTableViewDataSourceType.swift in Sources */, + 31F0D187BC76DAB3C2DEE8B2CABB0535 /* RxTableViewDelegateProxy.swift in Sources */, + F6E1B45243EF2546837B9099C53770E2 /* RxTableViewReactiveArrayDataSource.swift in Sources */, + D1DE14077A54174F00E887101A48AE8A /* RxTarget.swift in Sources */, + 4FC27FF6DF0328A134393A57E735977B /* RxTextStorageDelegateProxy.swift in Sources */, + C66C4E3E67C26B960FABBC8F1B0C056A /* RxTextViewDelegateProxy.swift in Sources */, + 7BEF420E8F9099C5079845A9BE4DCA63 /* RxWKNavigationDelegateProxy.swift in Sources */, + BB75BCF76F22254E3302085A5A6A4B48 /* SchedulerType+SharedSequence.swift in Sources */, + C56A14C84CF05A1A96D8B92E16E0CBFB /* SectionedViewDataSourceType.swift in Sources */, + DFD30F96D602E6476B57BB16FF1785D2 /* SharedSequence.swift in Sources */, + 9DB4A288E7875E7346EAB537875222D8 /* SharedSequence+Operators.swift in Sources */, + 841FBD1EB10F9112D309BB28BD10CF1D /* SharedSequence+Operators+arity.swift in Sources */, + 3D445FD9D8FFBDD79E0D04BDFE96B0BB /* Signal.swift in Sources */, + 1AD93376D403A851F152D1B804F7BFC0 /* Signal+Subscription.swift in Sources */, + BEFE617EABAE8B434A580CCD4179C04E /* TextInput.swift in Sources */, + A37D3661369446F3AA978C8FD342A83A /* UIActivityIndicatorView+Rx.swift in Sources */, + 4EFD31D7DB8D26D9D031A2225A0C6AEC /* UIApplication+Rx.swift in Sources */, + 09E4A424C9A4B6AF425B42861E50E5F0 /* UIBarButtonItem+Rx.swift in Sources */, + 24C44D889CCC3570C277EB1C3CE505F4 /* UIButton+Rx.swift in Sources */, + A3423ADEDFB20D72E2C608221A26D3C6 /* UICollectionView+Rx.swift in Sources */, + 4EE0F2D2112CE993AEA24549F5DB19BF /* UIControl+Rx.swift in Sources */, + 8FE0BD68EA39B931E49D9C038BE80B65 /* UIDatePicker+Rx.swift in Sources */, + 51C984425C777CF8B613C230DCE2DB65 /* UIGestureRecognizer+Rx.swift in Sources */, + 4EB4328C78B36211BF7D50529327FD7C /* UINavigationController+Rx.swift in Sources */, + DDEF2B45CC47E733C9FCCD38F0BF6857 /* UIPickerView+Rx.swift in Sources */, + 8B7686A732E13434E997809196B15955 /* UIRefreshControl+Rx.swift in Sources */, + 70A41125865DDF878FC4CBD646349805 /* UIScrollView+Rx.swift in Sources */, + EB276B66D2562F17B084C0D83B9D8F27 /* UISearchBar+Rx.swift in Sources */, + 0D7B6FF8C492D77C003609B68CFABA1E /* UISearchController+Rx.swift in Sources */, + 0B2165491D9E7087D8C78C7A8128A9F0 /* UISegmentedControl+Rx.swift in Sources */, + 2C64E385669A619F264F7556914DF205 /* UISlider+Rx.swift in Sources */, + 8AEF0775CDF920AC2DBE0C725B59EC96 /* UIStepper+Rx.swift in Sources */, + D05116642C20C568B926B4025B6EF995 /* UISwitch+Rx.swift in Sources */, + EE80E1376D7F9E22682AE05EE3054388 /* UITabBar+Rx.swift in Sources */, + 08155F3F6D55A38A07F00F85763290E7 /* UITabBarController+Rx.swift in Sources */, + 161856AC63FAA2C3D8164A7500E14CB8 /* UITableView+Rx.swift in Sources */, + 81A394201D240F032A6108ED479B427A /* UITextField+Rx.swift in Sources */, + 000702A76DD1A018D9B45DEB79FB505D /* UITextView+Rx.swift in Sources */, + 7F60B371FE78073E7DFDD621FFC482CE /* URLSession+Rx.swift in Sources */, + 8EA5CC7EF28B004A8A813925E4F17F93 /* WKWebView+Rx.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 066FF6E7D2AD331E0AE036243A462001 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = 439EBE25AEFBAA5BC20F9099F7C69F1E /* PBXContainerItemProxy */; + }; + 36DF872A6FDDE70718F7FAD72D0BC0C6 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxCocoa; + target = 7AD0C6DCDC9CEC8A3C7C10C7FEE07BE6 /* RxCocoa */; + targetProxy = AA2A58CC35F58189739CFCB9CB1744F0 /* PBXContainerItemProxy */; + }; + 3ECD2D538CECDA0F3E6C17C7A165C070 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = 6B8D90F2EB61286F0DD4C7DC35A28553 /* PBXContainerItemProxy */; + }; + 4DD515A7790615A3022120D28FD1F0D0 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Kingfisher; + target = E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */; + targetProxy = 0D0A4F250EC6A9EEBA45E42EB0C83196 /* PBXContainerItemProxy */; + }; + 6DEB3C1ABB560ABB8CAAD4B49165EDAD /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = "Pods-Nasa"; + target = F889E6876E3193B7BFC4912BB2571351 /* Pods-Nasa */; + targetProxy = D630FA3585DA150E5749E6BF0532AE8F /* PBXContainerItemProxy */; + }; + 6FF007392584F2444B28F075A57B324B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = D7A5EB60227DFFAE59DB6ADB5D194F24 /* PBXContainerItemProxy */; + }; + ACA1636861EA193B8331F57D55AE11ED /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = E030F31829B5758861A7572EBEB50676 /* PBXContainerItemProxy */; + }; + AFA24F454A287547C7E0D60144D4A0D0 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = B0F42041C2C6D6146329B048A5904ED6 /* PBXContainerItemProxy */; + }; + BF2EDCAB42AFE4FE61D849C7599D6400 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 5595B3D223167804FC98397C4536EB89 /* PBXContainerItemProxy */; + }; + C0921B6A0AF92D468064CB0E0E013426 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxRelay; + target = 4622BFEF3DC16E8BD15EEFC30D4D0084 /* RxRelay */; + targetProxy = 0CFE11329CD34D4A0D7050C813DB2BC0 /* PBXContainerItemProxy */; + }; + F04293B702898D187579F1B07E95E929 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = Kingfisher; + target = E8022D22FAA6690B5E1C379C1BCE1491 /* Kingfisher */; + targetProxy = 263B46AA724788B9C72FF8C7719DF893 /* PBXContainerItemProxy */; + }; + FAFDD3DF82FA08744030F2830C5E1F4F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = RxSwift; + target = EA9EA43B3B503823EE36C60D9C8A865F /* RxSwift */; + targetProxy = AEDA40EDA5F621AB289E21A5288DEEC5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 042F1E6ACBDBD1E8E5DEFC2B49ACE953 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 19633EC1F09BD3DF99FDB112C14031A0 /* RxRelay.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 0B15EFD7D111FC69E5226EB424213B89 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 168DC811C7106944BF69EDADA98FD6D0 /* Pods-NasaTests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-NasaTests/Pods-NasaTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-NasaTests/Pods-NasaTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 2206F23AE3A7B6E3FBC01DC3FDAA996D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 32630B4842C76B01267DF03C2B356519 /* Pods-NasaTests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-NasaTests/Pods-NasaTests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-NasaTests/Pods-NasaTests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3304867C422EACAD2AF96DDA0EEA8D39 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7A1C2B0C119BAFB3E2F50B4DC1622CB8 /* Pods-Nasa.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Nasa/Pods-Nasa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Nasa/Pods-Nasa.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 3530CA9B67AA015710D84AC01A3D0225 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = F5E1AF0DBAEBDBF51E2454A51D0E0912 /* Pods-Nasa-NasaUITests.release.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 50BC06EED7FAA83C3E819EA1F0996479 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = FD3DFA4324F53EFF292E97C31F7D3E78 /* Pods-Nasa-NasaUITests.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Nasa-NasaUITests/Pods-Nasa-NasaUITests.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 54E08EBFBE9AD5F4AC051C4B5F363420 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = B44BEF8F0C8D5BE9C952898810B8CB65 /* RxSwift.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 7D34C1F5EEAF808252A41D4904D30039 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7B38A37EDADBCE6A4E37BDA273C433F8 /* RxCocoa.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + 90D4D09BCB6A4660E43ACBE9ECB6FE9A /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_DEBUG=1", + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Debug; + }; + 9553C89E183877A5CB2F3C6801BEC129 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_PREPROCESSOR_DEFINITIONS = ( + "POD_CONFIGURATION_RELEASE=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRIP_INSTALLED_PRODUCT = NO; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + SWIFT_VERSION = 5.0; + SYMROOT = "${SRCROOT}/../build"; + }; + name = Release; + }; + 96859D0CBA06C4EA7691E92BBFBE3F95 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 32ED16D862E2C699D96329A575941E33 /* RxCocoa.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxCocoa/RxCocoa-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxCocoa/RxCocoa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxCocoa/RxCocoa.modulemap"; + PRODUCT_MODULE_NAME = RxCocoa; + PRODUCT_NAME = RxCocoa; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + 980A58862D8A5086E2825CF9017AC8DD /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = EBAFF86672E46BDCF016A36E670BA43A /* Kingfisher.debug.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kingfisher/Kingfisher-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; + PRODUCT_MODULE_NAME = Kingfisher; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + BFD9E4B58F44191AF73A3434AAF6831F /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 8A3A20480CFDF96D43D7E6857FBEA137 /* Kingfisher.release.xcconfig */; + buildSettings = { + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/Kingfisher/Kingfisher-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/Kingfisher/Kingfisher-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 12.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/Kingfisher/Kingfisher.modulemap"; + PRODUCT_MODULE_NAME = Kingfisher; + PRODUCT_NAME = Kingfisher; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; + D11067032B1DF2EF7CC718C07E1D6436 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 1AC15CC5C4A22DE8A1AD51D3064CF0C2 /* Pods-Nasa.debug.xcconfig */; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = NO; + CLANG_ENABLE_OBJC_WEAK = NO; + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + INFOPLIST_FILE = "Target Support Files/Pods-Nasa/Pods-Nasa-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 15.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MACH_O_TYPE = staticlib; + MODULEMAP_FILE = "Target Support Files/Pods-Nasa/Pods-Nasa.modulemap"; + OTHER_LDFLAGS = ""; + OTHER_LIBTOOLFLAGS = ""; + PODS_ROOT = "$(SRCROOT)"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.${PRODUCT_NAME:rfc1034identifier}"; + PRODUCT_NAME = "$(TARGET_NAME:c99extidentifier)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + D6B50D2637753F376F37B8176A6D3EE5 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = BE3CAC3B8C77ADA995F99AB865199E01 /* RxSwift.debug.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxSwift/RxSwift-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxSwift/RxSwift-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxSwift/RxSwift.modulemap"; + PRODUCT_MODULE_NAME = RxSwift; + PRODUCT_NAME = RxSwift; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Debug; + }; + F3DB583BBA9278858A0E15CD6F83C826 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 56EEDAC142A8697D3F3369C0CB954CE7 /* RxRelay.release.xcconfig */; + buildSettings = { + "CODE_SIGN_IDENTITY[sdk=appletvos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = ""; + "CODE_SIGN_IDENTITY[sdk=watchos*]" = ""; + CURRENT_PROJECT_VERSION = 1; + DEFINES_MODULE = YES; + DYLIB_COMPATIBILITY_VERSION = 1; + DYLIB_CURRENT_VERSION = 1; + DYLIB_INSTALL_NAME_BASE = "@rpath"; + GCC_PREFIX_HEADER = "Target Support Files/RxRelay/RxRelay-prefix.pch"; + INFOPLIST_FILE = "Target Support Files/RxRelay/RxRelay-Info.plist"; + INSTALL_PATH = "$(LOCAL_LIBRARY_DIR)/Frameworks"; + IPHONEOS_DEPLOYMENT_TARGET = 9.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + MODULEMAP_FILE = "Target Support Files/RxRelay/RxRelay.modulemap"; + PRODUCT_MODULE_NAME = RxRelay; + PRODUCT_NAME = RxRelay; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "$(inherited) "; + SWIFT_VERSION = 5.1; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + VERSIONING_SYSTEM = "apple-generic"; + VERSION_INFO_PREFIX = ""; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 1DCA7609A5ED259FE6835035578C6D52 /* Build configuration list for PBXNativeTarget "Pods-NasaTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0B15EFD7D111FC69E5226EB424213B89 /* Debug */, + 2206F23AE3A7B6E3FBC01DC3FDAA996D /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 25AE2A8304AA799A1A0A4FD6C1577310 /* Build configuration list for PBXNativeTarget "RxCocoa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7D34C1F5EEAF808252A41D4904D30039 /* Debug */, + 96859D0CBA06C4EA7691E92BBFBE3F95 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 3A14D11DE6D57CFFF29284B2A5A41C7D /* Build configuration list for PBXNativeTarget "Pods-Nasa-NasaUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 50BC06EED7FAA83C3E819EA1F0996479 /* Debug */, + 3530CA9B67AA015710D84AC01A3D0225 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 4821239608C13582E20E6DA73FD5F1F9 /* Build configuration list for PBXProject "Pods" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 90D4D09BCB6A4660E43ACBE9ECB6FE9A /* Debug */, + 9553C89E183877A5CB2F3C6801BEC129 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 69ACD8654734266A348C6FF68E734010 /* Build configuration list for PBXNativeTarget "Kingfisher" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 980A58862D8A5086E2825CF9017AC8DD /* Debug */, + BFD9E4B58F44191AF73A3434AAF6831F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 6A19B0B51830991FE5CDD4E8FD5C0CB4 /* Build configuration list for PBXNativeTarget "RxSwift" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D6B50D2637753F376F37B8176A6D3EE5 /* Debug */, + 54E08EBFBE9AD5F4AC051C4B5F363420 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A65D81D102BEC6604A21F09FF2C80B0C /* Build configuration list for PBXNativeTarget "RxRelay" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 042F1E6ACBDBD1E8E5DEFC2B49ACE953 /* Debug */, + F3DB583BBA9278858A0E15CD6F83C826 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E08BCE0FEFD2DE1C60BC6919223BC216 /* Build configuration list for PBXNativeTarget "Pods-Nasa" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + D11067032B1DF2EF7CC718C07E1D6436 /* Debug */, + 3304867C422EACAD2AF96DDA0EEA8D39 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = BFDFE7DC352907FC980B868725387E98 /* Project object */; +} diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Kingfisher.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Kingfisher.xcscheme new file mode 100644 index 0000000..0074170 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Kingfisher.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa-NasaUITests.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa-NasaUITests.xcscheme new file mode 100644 index 0000000..12af0c8 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa-NasaUITests.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa.xcscheme new file mode 100644 index 0000000..db52f99 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-Nasa.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-NasaTests.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-NasaTests.xcscheme new file mode 100644 index 0000000..2352810 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/Pods-NasaTests.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxCocoa.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxCocoa.xcscheme new file mode 100644 index 0000000..3b88af8 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxCocoa.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxRelay.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxRelay.xcscheme new file mode 100644 index 0000000..d69a445 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxRelay.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxSwift.xcscheme b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxSwift.xcscheme new file mode 100644 index 0000000..47e329b --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/RxSwift.xcscheme @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 0000000..9076428 --- /dev/null +++ b/Pods/Pods.xcodeproj/xcuserdata/Angie.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,60 @@ + + + + + SchemeUserState + + Kingfisher.xcscheme + + isShown + + orderHint + 0 + + Pods-Nasa-NasaUITests.xcscheme + + isShown + + orderHint + 2 + + Pods-Nasa.xcscheme + + isShown + + orderHint + 1 + + Pods-NasaTests.xcscheme + + isShown + + orderHint + 3 + + RxCocoa.xcscheme + + isShown + + orderHint + 4 + + RxRelay.xcscheme + + isShown + + orderHint + 5 + + RxSwift.xcscheme + + isShown + + orderHint + 6 + + + SuppressBuildableAutocreation + + + diff --git a/Pods/RxCocoa/LICENSE.md b/Pods/RxCocoa/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxCocoa/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/RxCocoa/Platform/DataStructures/Bag.swift b/Pods/RxCocoa/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift b/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift b/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/Pods/RxCocoa/Platform/DataStructures/Queue.swift b/Pods/RxCocoa/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/Pods/RxCocoa/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift b/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/Pods/RxCocoa/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/Pods/RxCocoa/Platform/Platform.Darwin.swift b/Pods/RxCocoa/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/Pods/RxCocoa/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxCocoa/Platform/Platform.Linux.swift b/Pods/RxCocoa/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/Pods/RxCocoa/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxCocoa/Platform/RecursiveLock.swift b/Pods/RxCocoa/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/Pods/RxCocoa/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/Pods/RxCocoa/README.md b/Pods/RxCocoa/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/Pods/RxCocoa/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.2.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.2.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift b/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift new file mode 100644 index 0000000..231c3fe --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/ControlTarget.swift @@ -0,0 +1,88 @@ +// +// ControlTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) || os(macOS) + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + typealias Control = UIKit.UIControl +#elseif os(macOS) + import Cocoa + + typealias Control = Cocoa.NSControl +#endif + +// This should be only used from `MainScheduler` +final class ControlTarget: RxTarget { + typealias Callback = (Control) -> Void + + let selector: Selector = #selector(ControlTarget.eventHandler(_:)) + + weak var control: Control? +#if os(iOS) || os(tvOS) + let controlEvents: UIControl.Event +#endif + var callback: Callback? + #if os(iOS) || os(tvOS) + init(control: Control, controlEvents: UIControl.Event, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.controlEvents = controlEvents + self.callback = callback + + super.init() + + control.addTarget(self, action: selector, for: controlEvents) + + let method = self.method(for: selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#elseif os(macOS) + init(control: Control, callback: @escaping Callback) { + MainScheduler.ensureRunningOnMainThread() + + self.control = control + self.callback = callback + + super.init() + + control.target = self + control.action = self.selector + + let method = self.method(for: self.selector) + if method == nil { + rxFatalError("Can't find method") + } + } +#endif + + @objc func eventHandler(_ sender: Control!) { + if let callback = self.callback, let control = self.control { + callback(control) + } + } + + override func dispose() { + super.dispose() +#if os(iOS) || os(tvOS) + self.control?.removeTarget(self, action: self.selector, for: self.controlEvents) +#elseif os(macOS) + self.control?.target = nil + self.control?.action = nil +#endif + self.callback = nil + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift b/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift new file mode 100644 index 0000000..4ef8de7 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/DelegateProxy.swift @@ -0,0 +1,293 @@ +// +// DelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import RxSwift + #if SWIFT_PACKAGE && !os(Linux) + import RxCocoaRuntime + #endif + + /// Base class for `DelegateProxyType` protocol. + /// + /// This implementation is not thread safe and can be used only from one thread (Main thread). + open class DelegateProxy: _RXDelegateProxy { + public typealias ParentObject = P + public typealias Delegate = D + + private var _sentMessageForSelector = [Selector: MessageDispatcher]() + private var _methodInvokedForSelector = [Selector: MessageDispatcher]() + + /// Parent object associated with delegate proxy. + private weak var _parentObject: ParentObject? + + private let _currentDelegateFor: (ParentObject) -> AnyObject? + private let _setCurrentDelegateTo: (AnyObject?, ParentObject) -> Void + + /// Initializes new instance. + /// + /// - parameter parentObject: Optional parent object that owns `DelegateProxy` as associated object. + public init(parentObject: ParentObject, delegateProxy: Proxy.Type) + where Proxy: DelegateProxy, Proxy.ParentObject == ParentObject, Proxy.Delegate == Delegate { + self._parentObject = parentObject + self._currentDelegateFor = delegateProxy._currentDelegate + self._setCurrentDelegateTo = delegateProxy._setCurrentDelegate + + MainScheduler.ensureRunningOnMainThread() + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + super.init() + } + + /** + Returns observable sequence of invocations of delegate methods. Elements are sent *before method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func sentMessage(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._sentMessageForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._sentMessageForSelector[selector] = subject + return subject.asObservable() + } + } + + /** + Returns observable sequence of invoked delegate methods. Elements are sent *after method is invoked*. + + Only methods that have `void` return value can be observed using this method because + those methods are used as a notification mechanism. It doesn't matter if they are optional + or not. Observing is performed by installing a hidden associated `PublishSubject` that is + used to dispatch messages to observers. + + Delegate methods that have non `void` return value can't be observed directly using this method + because: + * those methods are not intended to be used as a notification mechanism, but as a behavior customization mechanism + * there is no sensible automatic way to determine a default return value + + In case observing of delegate methods that have return type is required, it can be done by + manually installing a `PublishSubject` or `BehaviorSubject` and implementing delegate method. + + e.g. + + // delegate proxy part (RxScrollViewDelegateProxy) + + let internalSubject = PublishSubject + + public func requiredDelegateMethod(scrollView: UIScrollView, arg1: CGPoint) -> Bool { + internalSubject.on(.next(arg1)) + return self._forwardToDelegate?.requiredDelegateMethod?(scrollView, arg1: arg1) ?? defaultReturnValue + } + + .... + + // reactive property implementation in a real class (`UIScrollView`) + public var property: Observable { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + return proxy.internalSubject.asObservable() + } + + **In case calling this method prints "Delegate proxy is already implementing `\(selector)`, + a more performant way of registering might exist.", that means that manual observing method + is required analog to the example above because delegate method has already been implemented.** + + - parameter selector: Selector used to filter observed invocations of delegate methods. + - returns: Observable sequence of arguments passed to `selector` method. + */ + open func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + MainScheduler.ensureRunningOnMainThread() + + let subject = self._methodInvokedForSelector[selector] + + if let subject = subject { + return subject.asObservable() + } + else { + let subject = MessageDispatcher(selector: selector, delegateProxy: self) + self._methodInvokedForSelector[selector] = subject + return subject.asObservable() + } + } + + fileprivate func checkSelectorIsObservable(_ selector: Selector) { + MainScheduler.ensureRunningOnMainThread() + + if self.hasWiredImplementation(for: selector) { + print("⚠️ Delegate proxy is already implementing `\(selector)`, a more performant way of registering might exist.") + return + } + + if self.voidDelegateMethodsContain(selector) { + return + } + + // In case `_forwardToDelegate` is `nil`, it is assumed the check is being done prematurely. + if !(self._forwardToDelegate?.responds(to: selector) ?? true) { + print("⚠️ Using delegate proxy dynamic interception method but the target delegate object doesn't respond to the requested selector. " + + "In case pure Swift delegate proxy is being used please use manual observing method by using`PublishSubject`s. " + + " (selector: `\(selector)`, forwardToDelegate: `\(self._forwardToDelegate ?? self)`)") + } + } + + // proxy + + open override func _sentMessage(_ selector: Selector, withArguments arguments: [Any]) { + self._sentMessageForSelector[selector]?.on(.next(arguments)) + } + + open override func _methodInvoked(_ selector: Selector, withArguments arguments: [Any]) { + self._methodInvokedForSelector[selector]?.on(.next(arguments)) + } + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + open func forwardToDelegate() -> Delegate? { + return castOptionalOrFatalError(self._forwardToDelegate) + } + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + open func setForwardToDelegate(_ delegate: Delegate?, retainDelegate: Bool) { + #if DEBUG // 4.0 all configurations + MainScheduler.ensureRunningOnMainThread() + #endif + self._setForwardToDelegate(delegate, retainDelegate: retainDelegate) + + let sentSelectors: [Selector] = self._sentMessageForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let invokedSelectors: [Selector] = self._methodInvokedForSelector.values.filter { $0.hasObservers }.map { $0.selector } + let allUsedSelectors = sentSelectors + invokedSelectors + + for selector in Set(allUsedSelectors) { + self.checkSelectorIsObservable(selector) + } + + self.reset() + } + + private func hasObservers(selector: Selector) -> Bool { + return (self._sentMessageForSelector[selector]?.hasObservers ?? false) + || (self._methodInvokedForSelector[selector]?.hasObservers ?? false) + } + + override open func responds(to aSelector: Selector!) -> Bool { + return super.responds(to: aSelector) + || (self._forwardToDelegate?.responds(to: aSelector) ?? false) + || (self.voidDelegateMethodsContain(aSelector) && self.hasObservers(selector: aSelector)) + } + + fileprivate func reset() { + guard let parentObject = self._parentObject else { return } + + let maybeCurrentDelegate = self._currentDelegateFor(parentObject) + + if maybeCurrentDelegate === self { + self._setCurrentDelegateTo(nil, parentObject) + self._setCurrentDelegateTo(castOrFatalError(self), parentObject) + } + } + + deinit { + for v in self._sentMessageForSelector.values { + v.on(.completed) + } + for v in self._methodInvokedForSelector.values { + v.on(.completed) + } + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } + + + } + + private let mainScheduler = MainScheduler() + + private final class MessageDispatcher { + private let dispatcher: PublishSubject<[Any]> + private let result: Observable<[Any]> + + fileprivate let selector: Selector + + init(selector: Selector, delegateProxy _delegateProxy: DelegateProxy) { + weak var weakDelegateProxy = _delegateProxy + + let dispatcher = PublishSubject<[Any]>() + self.dispatcher = dispatcher + self.selector = selector + + self.result = dispatcher + .do(onSubscribed: { weakDelegateProxy?.checkSelectorIsObservable(selector); weakDelegateProxy?.reset() }, onDispose: { weakDelegateProxy?.reset() }) + .share() + .subscribe(on: mainScheduler) + } + + var on: (Event<[Any]>) -> Void { + return self.dispatcher.on + } + + var hasObservers: Bool { + return self.dispatcher.hasObservers + } + + func asObservable() -> Observable<[Any]> { + return self.result + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift b/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift new file mode 100644 index 0000000..42fa50d --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/DelegateProxyType.swift @@ -0,0 +1,435 @@ +// +// DelegateProxyType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + + import Foundation + import RxSwift + +/** +`DelegateProxyType` protocol enables using both normal delegates and Rx observable sequences with +views that can have only one delegate/datasource registered. + +`Proxies` store information about observers, subscriptions and delegates +for specific views. + +Type implementing `DelegateProxyType` should never be initialized directly. + +To fetch initialized instance of type implementing `DelegateProxyType`, `proxy` method +should be used. + +This is more or less how it works. + + + + +-------------------------------------------+ + | | + | UIView subclass (UIScrollView) | + | | + +-----------+-------------------------------+ + | + | Delegate + | + | + +-----------v-------------------------------+ + | | + | Delegate proxy : DelegateProxyType +-----+----> Observable + | , UIScrollViewDelegate | | + +-----------+-------------------------------+ +----> Observable + | | + | +----> Observable + | | + | forwards events | + | to custom delegate | + | v + +-----------v-------------------------------+ + | | + | Custom delegate (UIScrollViewDelegate) | + | | + +-------------------------------------------+ + + +Since RxCocoa needs to automagically create those Proxys and because views that have delegates can be hierarchical + + UITableView : UIScrollView : UIView + +.. and corresponding delegates are also hierarchical + + UITableViewDelegate : UIScrollViewDelegate : NSObject + +... this mechanism can be extended by using the following snippet in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + RxScrollViewDelegateProxy.register { RxTableViewDelegateProxy(parentObject: $0) } + +*/ +public protocol DelegateProxyType: AnyObject { + associatedtype ParentObject: AnyObject + associatedtype Delegate + + /// It is require that enumerate call `register` of the extended DelegateProxy subclasses here. + static func registerKnownImplementations() + + /// Unique identifier for delegate + static var identifier: UnsafeRawPointer { get } + + /// Returns designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter object: Object that has delegate property. + /// - returns: Value of delegate property. + static func currentDelegate(for object: ParentObject) -> Delegate? + + /// Sets designated delegate property for object. + /// + /// Objects can have multiple delegate properties. + /// + /// Each delegate property needs to have it's own type implementing `DelegateProxyType`. + /// + /// It's abstract method. + /// + /// - parameter toObject: Object that has delegate property. + /// - parameter delegate: Delegate value. + static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) + + /// Returns reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - returns: Value of reference if set or nil. + func forwardToDelegate() -> Delegate? + + /// Sets reference of normal delegate that receives all forwarded messages + /// through `self`. + /// + /// - parameter forwardToDelegate: Reference of delegate that receives all messages through `self`. + /// - parameter retainDelegate: Should `self` retain `forwardToDelegate`. + func setForwardToDelegate(_ forwardToDelegate: Delegate?, retainDelegate: Bool) +} + +// default implementations +extension DelegateProxyType { + /// Unique identifier for delegate + public static var identifier: UnsafeRawPointer { + let delegateIdentifier = ObjectIdentifier(Delegate.self) + let integerIdentifier = Int(bitPattern: delegateIdentifier) + return UnsafeRawPointer(bitPattern: integerIdentifier)! + } +} + +// workaround of Delegate: class +extension DelegateProxyType { + static func _currentDelegate(for object: ParentObject) -> AnyObject? { + currentDelegate(for: object).map { $0 as AnyObject } + } + + static func _setCurrentDelegate(_ delegate: AnyObject?, to object: ParentObject) { + setCurrentDelegate(castOptionalOrFatalError(delegate), to: object) + } + + func _forwardToDelegate() -> AnyObject? { + self.forwardToDelegate().map { $0 as AnyObject } + } + + func _setForwardToDelegate(_ forwardToDelegate: AnyObject?, retainDelegate: Bool) { + self.setForwardToDelegate(castOptionalOrFatalError(forwardToDelegate), retainDelegate: retainDelegate) + } +} + +extension DelegateProxyType { + + /// Store DelegateProxy subclass to factory. + /// When make 'Rx*DelegateProxy' subclass, call 'Rx*DelegateProxySubclass.register(for:_)' 1 time, or use it in DelegateProxyFactory + /// 'Rx*DelegateProxy' can have one subclass implementation per concrete ParentObject type. + /// Should call it from concrete DelegateProxy type, not generic. + public static func register(make: @escaping (Parent) -> Self) { + self.factory.extend(make: make) + } + + /// Creates new proxy for target object. + /// Should not call this function directory, use 'DelegateProxy.proxy(for:)' + public static func createProxy(for object: AnyObject) -> Self { + castOrFatalError(factory.createProxy(for: object)) + } + + /// Returns existing proxy for object or installs new instance of delegate proxy. + /// + /// - parameter object: Target object on which to install delegate proxy. + /// - returns: Installed instance of delegate proxy. + /// + /// + /// extension Reactive where Base: UISearchBar { + /// + /// public var delegate: DelegateProxy { + /// return RxSearchBarDelegateProxy.proxy(for: base) + /// } + /// + /// public var text: ControlProperty { + /// let source: Observable = self.delegate.observe(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) + /// ... + /// } + /// } + public static func proxy(for object: ParentObject) -> Self { + MainScheduler.ensureRunningOnMainThread() + + let maybeProxy = self.assignedProxy(for: object) + + let proxy: AnyObject + if let existingProxy = maybeProxy { + proxy = existingProxy + } + else { + proxy = castOrFatalError(self.createProxy(for: object)) + self.assignProxy(proxy, toObject: object) + assert(self.assignedProxy(for: object) === proxy) + } + let currentDelegate = self._currentDelegate(for: object) + let delegateProxy: Self = castOrFatalError(proxy) + + if currentDelegate !== delegateProxy { + delegateProxy._setForwardToDelegate(currentDelegate, retainDelegate: false) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + self._setCurrentDelegate(proxy, to: object) + assert(self._currentDelegate(for: object) === proxy) + assert(delegateProxy._forwardToDelegate() === currentDelegate) + } + + return delegateProxy + } + + /// Sets forward delegate for `DelegateProxyType` associated with a specific object and return disposable that can be used to unset the forward to delegate. + /// Using this method will also make sure that potential original object cached selectors are cleared and will report any accidental forward delegate mutations. + /// + /// - parameter forwardDelegate: Delegate object to set. + /// - parameter retainDelegate: Retain `forwardDelegate` while it's being set. + /// - parameter onProxyForObject: Object that has `delegate` property. + /// - returns: Disposable object that can be used to clear forward delegate. + public static func installForwardDelegate(_ forwardDelegate: Delegate, retainDelegate: Bool, onProxyForObject object: ParentObject) -> Disposable { + weak var weakForwardDelegate: AnyObject? = forwardDelegate as AnyObject + let proxy = self.proxy(for: object) + + assert(proxy._forwardToDelegate() === nil, "This is a feature to warn you that there is already a delegate (or data source) set somewhere previously. The action you are trying to perform will clear that delegate (data source) and that means that some of your features that depend on that delegate (data source) being set will likely stop working.\n" + + "If you are ok with this, try to set delegate (data source) to `nil` in front of this operation.\n" + + " This is the source object value: \(object)\n" + + " This is the original delegate (data source) value: \(proxy.forwardToDelegate()!)\n" + + "Hint: Maybe delegate was already set in xib or storyboard and now it's being overwritten in code.\n") + + proxy.setForwardToDelegate(forwardDelegate, retainDelegate: retainDelegate) + + return Disposables.create { + MainScheduler.ensureRunningOnMainThread() + + let delegate: AnyObject? = weakForwardDelegate + + assert(delegate == nil || proxy._forwardToDelegate() === delegate, "Delegate was changed from time it was first set. Current \(String(describing: proxy.forwardToDelegate())), and it should have been \(proxy)") + + proxy.setForwardToDelegate(nil, retainDelegate: retainDelegate) + } + } +} + + +// private extensions +extension DelegateProxyType { + private static var factory: DelegateProxyFactory { + DelegateProxyFactory.sharedFactory(for: self) + } + + private static func assignedProxy(for object: ParentObject) -> AnyObject? { + let maybeDelegate = objc_getAssociatedObject(object, self.identifier) + return castOptionalOrFatalError(maybeDelegate) + } + + private static func assignProxy(_ proxy: AnyObject, toObject object: ParentObject) { + objc_setAssociatedObject(object, self.identifier, proxy, .OBJC_ASSOCIATION_RETAIN) + } +} + +/// Describes an object that has a delegate. +public protocol HasDelegate: AnyObject { + /// Delegate type + associatedtype Delegate + + /// Delegate + var delegate: Delegate? { get set } +} + +extension DelegateProxyType where ParentObject: HasDelegate, Self.Delegate == ParentObject.Delegate { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.delegate + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +/// Describes an object that has a data source. +public protocol HasDataSource: AnyObject { + /// Data source type + associatedtype DataSource + + /// Data source + var dataSource: DataSource? { get set } +} + +extension DelegateProxyType where ParentObject: HasDataSource, Self.Delegate == ParentObject.DataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.dataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.dataSource = delegate + } +} + +/// Describes an object that has a prefetch data source. +@available(iOS 10.0, tvOS 10.0, *) +public protocol HasPrefetchDataSource: AnyObject { + /// Prefetch data source type + associatedtype PrefetchDataSource + + /// Prefetch data source + var prefetchDataSource: PrefetchDataSource? { get set } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension DelegateProxyType where ParentObject: HasPrefetchDataSource, Self.Delegate == ParentObject.PrefetchDataSource { + public static func currentDelegate(for object: ParentObject) -> Delegate? { + object.prefetchDataSource + } + + public static func setCurrentDelegate(_ delegate: Delegate?, to object: ParentObject) { + object.prefetchDataSource = delegate + } +} + + #if os(iOS) || os(tvOS) + import UIKit + + extension ObservableType { + func subscribeProxyDataSource(ofObject object: DelegateProxy.ParentObject, dataSource: DelegateProxy.Delegate, retainDataSource: Bool, binding: @escaping (DelegateProxy, Event) -> Void) + -> Disposable + where DelegateProxy.ParentObject: UIView + , DelegateProxy.Delegate: AnyObject { + let proxy = DelegateProxy.proxy(for: object) + let unregisterDelegate = DelegateProxy.installForwardDelegate(dataSource, retainDelegate: retainDataSource, onProxyForObject: object) + + // Do not perform layoutIfNeeded if the object is still not in the view heirarchy + if object.window != nil { + // this is needed to flush any delayed old state (https://github.com/RxSwiftCommunity/RxDataSources/pull/75) + object.layoutIfNeeded() + } + + let subscription = self.asObservable() + .observe(on:MainScheduler()) + .catch { error in + bindingError(error) + return Observable.empty() + } + // source can never end, otherwise it would release the subscriber, and deallocate the data source + .concat(Observable.never()) + .take(until: object.rx.deallocated) + .subscribe { [weak object] (event: Event) in + + if let object = object { + assert(proxy === DelegateProxy.currentDelegate(for: object), "Proxy changed from the time it was first set.\nOriginal: \(proxy)\nExisting: \(String(describing: DelegateProxy.currentDelegate(for: object)))") + } + + binding(proxy, event) + + switch event { + case .error(let error): + bindingError(error) + unregisterDelegate.dispose() + case .completed: + unregisterDelegate.dispose() + default: + break + } + } + + return Disposables.create { [weak object] in + subscription.dispose() + + if object?.window != nil { + object?.layoutIfNeeded() + } + + unregisterDelegate.dispose() + } + } + } + + #endif + + /** + + To add delegate proxy subclasses call `DelegateProxySubclass.register()` in `registerKnownImplementations` or in some other + part of your app that executes before using `rx.*` (e.g. appDidFinishLaunching). + + class RxScrollViewDelegateProxy: DelegateProxy { + public static func registerKnownImplementations() { + self.register { RxTableViewDelegateProxy(parentObject: $0) } + } + ... + + + */ + private class DelegateProxyFactory { + private static var _sharedFactories: [UnsafeRawPointer: DelegateProxyFactory] = [:] + + fileprivate static func sharedFactory(for proxyType: DelegateProxy.Type) -> DelegateProxyFactory { + MainScheduler.ensureRunningOnMainThread() + let identifier = DelegateProxy.identifier + if let factory = _sharedFactories[identifier] { + return factory + } + let factory = DelegateProxyFactory(for: proxyType) + _sharedFactories[identifier] = factory + DelegateProxy.registerKnownImplementations() + return factory + } + + private var _factories: [ObjectIdentifier: ((AnyObject) -> AnyObject)] + private var _delegateProxyType: Any.Type + private var _identifier: UnsafeRawPointer + + private init(for proxyType: DelegateProxy.Type) { + self._factories = [:] + self._delegateProxyType = proxyType + self._identifier = proxyType.identifier + } + + fileprivate func extend(make: @escaping (ParentObject) -> DelegateProxy) { + MainScheduler.ensureRunningOnMainThread() + precondition(self._identifier == DelegateProxy.identifier, "Delegate proxy has inconsistent identifier") + guard self._factories[ObjectIdentifier(ParentObject.self)] == nil else { + rxFatalError("The factory of \(ParentObject.self) is duplicated. DelegateProxy is not allowed of duplicated base object type.") + } + self._factories[ObjectIdentifier(ParentObject.self)] = { make(castOrFatalError($0)) } + } + + fileprivate func createProxy(for object: AnyObject) -> AnyObject { + MainScheduler.ensureRunningOnMainThread() + var maybeMirror: Mirror? = Mirror(reflecting: object) + while let mirror = maybeMirror { + if let factory = self._factories[ObjectIdentifier(mirror.subjectType)] { + return factory(object) + } + maybeMirror = mirror.superclassMirror + } + rxFatalError("DelegateProxy has no factory of \(object). Implement DelegateProxy subclass for \(object) first.") + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift b/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift new file mode 100644 index 0000000..82c2922 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/Infallible+Bind.swift @@ -0,0 +1,148 @@ +// +// Infallible+Bind.swift +// RxCocoa +// +// Created by Shai Mishali on 27/08/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension InfallibleType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter to: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter to: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter to: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter to: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter relay: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + return self.subscribe(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift b/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift new file mode 100644 index 0000000..edded6b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/Observable+Bind.swift @@ -0,0 +1,103 @@ +// +// Observable+Bind.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter to: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element { + self.subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer(s). + In this form, it's equivalent to the `subscribe` method, but it better conveys intent, and enables + writing more consistent binding code. + - parameter to: Observers to receives events. + - returns: Disposable object that can be used to unsubscribe the observers. + */ + public func bind(to observers: Observer...) -> Disposable where Observer.Element == Element? { + self.map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Subscribes to observable sequence using custom binder function. + + - parameter to: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> Result) -> Result { + binder(self) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func bind(to binder: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return binder(self)(curriedArgument) + } + + - parameter to: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func bind(to binder: (Self) -> (R1) -> R2, curriedArgument: R1) -> R2 { + binder(self)(curriedArgument) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind( + with object: Object, + onNext: @escaping (Object, Element) -> Void + ) -> Disposable { + self.subscribe(onNext: { [weak object] in + guard let object = object else { return } + onNext(object, $0) + }, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } + + /** + Subscribes an element handler to an observable sequence. + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func bind(onNext: @escaping (Element) -> Void) -> Disposable { + self.subscribe(onNext: onNext, + onError: { error in + rxFatalErrorInDebug("Binding error: \(error)") + }) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift b/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift new file mode 100644 index 0000000..4abf880 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/RxCocoaObjCRuntimeError+Extensions.swift @@ -0,0 +1,161 @@ +// +// RxCocoaObjCRuntimeError+Extensions.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/9/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + /// RxCocoa ObjC runtime interception mechanism. + public enum RxCocoaInterceptionMechanism { + /// Unknown message interception mechanism. + case unknown + /// Key value observing interception mechanism. + case kvo + } + + /// RxCocoa ObjC runtime modification errors. + public enum RxCocoaObjCRuntimeError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown(target: AnyObject) + + /** + If the object is reporting a different class then it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + The most common case when this would happen is when using a combination of KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why the other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point (possibly a bug in KVO) + + The reason why changing order of observing works is because any interception method on unregistration + should return object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that interception mechanism). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + case objectMessagesAlreadyBeingIntercepted(target: AnyObject, interceptionMechanism: RxCocoaInterceptionMechanism) + + /// Trying to observe messages for selector that isn't implemented. + case selectorNotImplemented(target: AnyObject) + + /// Core Foundation classes are usually toll free bridged. Those classes crash the program in case + /// `object_setClass` is performed on them. + /// + /// There is a possibility to just swizzle methods on original object, but since those won't be usual use + /// cases for this library, then an error will just be reported for now. + case cantInterceptCoreFoundationTollFreeBridgedObjects(target: AnyObject) + + /// Two libraries have simultaneously tried to modify ObjC runtime and that was detected. This can only + /// happen in scenarios where multiple interception libraries are used. + /// + /// To synchronize other libraries intercepting messages for an object, use `synchronized` on target object and + /// it's meta-class. + case threadingCollisionWithOtherInterceptionMechanism(target: AnyObject) + + /// For some reason saving original method implementation under RX namespace failed. + case savingOriginalForwardingMethodFailed(target: AnyObject) + + /// Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason. + case replacingMethodWithForwardingImplementation(target: AnyObject) + + /// Attempt to intercept one of the performance sensitive methods: + /// * class + /// * respondsToSelector: + /// * methodSignatureForSelector: + /// * forwardingTargetForSelector: + case observingPerformanceSensitiveMessages(target: AnyObject) + + /// Message implementation has unsupported return type (for example large struct). The reason why this is a error + /// is because in some cases intercepting sent messages requires replacing implementation with `_objc_msgForward_stret` + /// instead of `_objc_msgForward`. + /// + /// The unsupported cases should be fairly uncommon. + case observingMessagesWithUnsupportedReturnType(target: AnyObject) + } + + extension RxCocoaObjCRuntimeError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case let .unknown(target): + return "Unknown error occurred.\nTarget: `\(target)`" + case let .objectMessagesAlreadyBeingIntercepted(target, interceptionMechanism): + let interceptionMechanismDescription = interceptionMechanism == .kvo ? "KVO" : "other interception mechanism" + return "Collision between RxCocoa interception mechanism and \(interceptionMechanismDescription)." + + " To resolve this conflict please use this interception mechanism first.\nTarget: \(target)" + case let .selectorNotImplemented(target): + return "Trying to observe messages for selector that isn't implemented.\nTarget: \(target)" + case let .cantInterceptCoreFoundationTollFreeBridgedObjects(target): + return "Interception of messages sent to Core Foundation isn't supported.\nTarget: \(target)" + case let .threadingCollisionWithOtherInterceptionMechanism(target): + return "Detected a conflict while modifying ObjC runtime.\nTarget: \(target)" + case let .savingOriginalForwardingMethodFailed(target): + return "Saving original method implementation failed.\nTarget: \(target)" + case let .replacingMethodWithForwardingImplementation(target): + return "Intercepting a sent message by replacing a method implementation with `_objc_msgForward` failed for some reason.\nTarget: \(target)" + case let .observingPerformanceSensitiveMessages(target): + return "Attempt to intercept one of the performance sensitive methods. \nTarget: \(target)" + case let .observingMessagesWithUnsupportedReturnType(target): + return "Attempt to intercept a method with unsupported return type. \nTarget: \(target)" + } + } + } + + // MARK: Conversions `NSError` > `RxCocoaObjCRuntimeError` + + extension Error { + func rxCocoaErrorForTarget(_ target: AnyObject) -> RxCocoaObjCRuntimeError { + let error = self as NSError + + if error.domain == RXObjCRuntimeErrorDomain { + let errorCode = RXObjCRuntimeError(rawValue: error.code) ?? .unknown + + switch errorCode { + case .unknown: + return .unknown(target: target) + case .objectMessagesAlreadyBeingIntercepted: + let isKVO = (error.userInfo[RXObjCRuntimeErrorIsKVOKey] as? NSNumber)?.boolValue ?? false + return .objectMessagesAlreadyBeingIntercepted(target: target, interceptionMechanism: isKVO ? .kvo : .unknown) + case .selectorNotImplemented: + return .selectorNotImplemented(target: target) + case .cantInterceptCoreFoundationTollFreeBridgedObjects: + return .cantInterceptCoreFoundationTollFreeBridgedObjects(target: target) + case .threadingCollisionWithOtherInterceptionMechanism: + return .threadingCollisionWithOtherInterceptionMechanism(target: target) + case .savingOriginalForwardingMethodFailed: + return .savingOriginalForwardingMethodFailed(target: target) + case .replacingMethodWithForwardingImplementation: + return .replacingMethodWithForwardingImplementation(target: target) + case .observingPerformanceSensitiveMessages: + return .observingPerformanceSensitiveMessages(target: target) + case .observingMessagesWithUnsupportedReturnType: + return .observingMessagesWithUnsupportedReturnType(target: target) + @unknown default: + fatalError("Unhandled Objective C Runtime Error") + } + } + + return RxCocoaObjCRuntimeError.unknown(target: target) + } + } + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift b/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift new file mode 100644 index 0000000..5a2c464 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/RxTarget.swift @@ -0,0 +1,43 @@ +// +// RxTarget.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +import RxSwift + +class RxTarget : NSObject + , Disposable { + + private var retainSelf: RxTarget? + + override init() { + super.init() + self.retainSelf = self + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + } + + func dispose() { +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + self.retainSelf = nil + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift new file mode 100644 index 0000000..5c3cf3c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/SectionedViewDataSourceType.swift @@ -0,0 +1,20 @@ +// +// SectionedViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 1/10/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Data source with access to underlying sectioned model. +public protocol SectionedViewDataSourceType { + /// Returns model at index path. + /// + /// In case data source doesn't contain any sections when this method is being called, `RxCocoaError.ItemsNotYetBound(object: self)` is thrown. + + /// - parameter indexPath: Model index path + /// - returns: Model at index path. + func model(at indexPath: IndexPath) throws -> Any +} diff --git a/Pods/RxCocoa/RxCocoa/Common/TextInput.swift b/Pods/RxCocoa/RxCocoa/Common/TextInput.swift new file mode 100644 index 0000000..2268882 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Common/TextInput.swift @@ -0,0 +1,78 @@ +// +// TextInput.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +#if os(iOS) || os(tvOS) + import UIKit + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: UITextField { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + + extension Reactive where Base: UITextView { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: base, text: self.text) + } + } + +#endif + +#if os(macOS) + import Cocoa + + /// Represents text input with reactive extensions. + public struct TextInput { + /// Base text input to extend. + public let base: Base + + /// Reactive wrapper for `text` property. + public let text: ControlProperty + + /// Initializes new text input. + /// + /// - parameter base: Base object. + /// - parameter text: Textual control property. + public init(base: Base, text: ControlProperty) { + self.base = base + self.text = text + } + } + + extension Reactive where Base: NSTextField, Base: NSTextInputClient { + /// Reactive text input. + public var textInput: TextInput { + return TextInput(base: self.base, text: self.text) + } + } + +#endif + + diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift new file mode 100644 index 0000000..30026bf --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+CoreGraphics.swift @@ -0,0 +1,68 @@ +// +// KVORepresentable+CoreGraphics.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift +import CoreGraphics + +import Foundation + +#if arch(x86_64) || arch(arm64) + let CGRectType = "{CGRect={CGPoint=dd}{CGSize=dd}}" + let CGSizeType = "{CGSize=dd}" + let CGPointType = "{CGPoint=dd}" +#elseif arch(i386) || arch(arm) || os(watchOS) + let CGRectType = "{CGRect={CGPoint=ff}{CGSize=ff}}" + let CGSizeType = "{CGSize=ff}" + let CGPointType = "{CGPoint=ff}" +#endif + +extension CGRect : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGRectType) != 0 { + return nil + } + var typedValue = CGRect(x: 0, y: 0, width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGPoint : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGPointType) != 0 { + return nil + } + var typedValue = CGPoint(x: 0, y: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +extension CGSize : KVORepresentable { + public typealias KVOType = NSValue + + /// Constructs self from `NSValue`. + public init?(KVOValue: KVOType) { + if strcmp(KVOValue.objCType, CGSizeType) != 0 { + return nil + } + var typedValue = CGSize(width: 0, height: 0) + KVOValue.getValue(&typedValue) + self = typedValue + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift new file mode 100644 index 0000000..00d53dd --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable+Swift.swift @@ -0,0 +1,88 @@ +// +// KVORepresentable+Swift.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension Int : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int32Value) + } +} + +extension Int64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.int64Value) + } +} + +extension UInt : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uintValue) + } +} + +extension UInt32 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint32Value) + } +} + +extension UInt64 : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.uint64Value) + } +} + +extension Bool : KVORepresentable { + public typealias KVOType = NSNumber + + /// Constructs `Self` using KVO value. + public init?(KVOValue: KVOType) { + self.init(KVOValue.boolValue) + } +} + + +extension RawRepresentable where RawValue: KVORepresentable { + /// Constructs `Self` using optional KVO value. + init?(KVOValue: RawValue.KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + guard let rawValue = RawValue(KVOValue: KVOValue) else { + return nil + } + + self.init(rawValue: rawValue) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift new file mode 100644 index 0000000..be12b33 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/KVORepresentable.swift @@ -0,0 +1,28 @@ +// +// KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that is KVO representable (KVO mechanism can be used to observe it). +public protocol KVORepresentable { + /// Associated KVO type. + associatedtype KVOType + + /// Constructs `Self` using KVO value. + init?(KVOValue: KVOType) +} + +extension KVORepresentable { + /// Initializes `KVORepresentable` with optional value. + init?(KVOValue: KVOType?) { + guard let KVOValue = KVOValue else { + return nil + } + + self.init(KVOValue: KVOValue) + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift new file mode 100644 index 0000000..1be5a21 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+KVORepresentable.swift @@ -0,0 +1,60 @@ +// +// NSObject+Rx+KVORepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift + +/// Key value observing options +public struct KeyValueObservingOptions: OptionSet { + /// Raw value + public let rawValue: UInt + + public init(rawValue: UInt) { + self.rawValue = rawValue + } + + /// Whether a sequence element should be sent to the observer immediately, before the subscribe method even returns. + public static let initial = KeyValueObservingOptions(rawValue: 1 << 0) + /// Whether to send updated values. + public static let new = KeyValueObservingOptions(rawValue: 1 << 1) +} + +extension Reactive where Base: NSObject { + + /** + Specialization of generic `observe` method. + + This is a special overload because to observe values of some type (for example `Int`), first values of KVO type + need to be observed (`NSNumber`), and then converted to result type. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable { + return self.observe(Element.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING && !os(Linux) + // KVO + extension Reactive where Base: NSObject { + /** + Specialization of generic `observeWeakly` method. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return self.observeWeakly(Element.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift new file mode 100644 index 0000000..6e47cb2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx+RawRepresentable.swift @@ -0,0 +1,52 @@ +// +// NSObject+Rx+RawRepresentable.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import RxSwift + +import Foundation + +extension Reactive where Base: NSObject { + /** + Specialization of generic `observe` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observe` method. + */ + public func observe(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial], retainSelf: Bool = true) -> Observable where Element.RawValue: KVORepresentable { + return self.observe(Element.RawValue.KVOType.self, keyPath, options: options, retainSelf: retainSelf) + .map(Element.init) + } +} + +#if !DISABLE_SWIZZLING + + // observeWeakly + RawRepresentable + extension Reactive where Base: NSObject { + + /** + Specialization of generic `observeWeakly` method. + + This specialization first observes `KVORepresentable` value and then converts it to `RawRepresentable` value. + + It is useful for observing bridged ObjC enum values. + + For more information take a look at `observeWeakly` method. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable where Element.RawValue: KVORepresentable { + return self.observeWeakly(Element.RawValue.KVOType.self, keyPath, options: options) + .map(Element.init) + } + } +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift new file mode 100644 index 0000000..68affa7 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NSObject+Rx.swift @@ -0,0 +1,569 @@ +// +// NSObject+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if !os(Linux) + +import Foundation +import RxSwift +#if SWIFT_PACKAGE && !DISABLE_SWIZZLING && !os(Linux) + import RxCocoaRuntime +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +private var deallocatingSubjectTriggerContext: UInt8 = 0 +private var deallocatingSubjectContext: UInt8 = 0 +#endif +private var deallocatedSubjectTriggerContext: UInt8 = 0 +private var deallocatedSubjectContext: UInt8 = 0 + +#if !os(Linux) + +/** +KVO is a tricky mechanism. + +When observing child in a ownership hierarchy, usually retaining observing target is wanted behavior. +When observing parent in a ownership hierarchy, usually retaining target isn't wanter behavior. + +KVO with weak references is especially tricky. For it to work, some kind of swizzling is required. +That can be done by + * replacing object class dynamically (like KVO does) + * by swizzling `dealloc` method on all instances for a class. + * some third method ... + +Both approaches can fail in certain scenarios: + * problems arise when swizzlers return original object class (like KVO does when nobody is observing) + * Problems can arise because replacing dealloc method isn't atomic operation (get implementation, + set implementation). + +Second approach is chosen. It can fail in case there are multiple libraries dynamically trying +to replace dealloc method. In case that isn't the case, it should be ok. +*/ +extension Reactive where Base: NSObject { + + + /** + Observes values on `keyPath` starting from `self` with `options` and retains `self` if `retainSelf` is set. + + `observe` is just a simple and performant wrapper around KVO mechanism. + + * it can be used to observe paths starting from `self` or from ancestors in ownership graph (`retainSelf = false`) + * it can be used to observe paths starting from descendants in ownership graph (`retainSelf = true`) + * the paths have to consist only of `strong` properties, otherwise you are risking crashing the system by not unregistering KVO observer before dealloc. + + If support for weak properties is needed or observing arbitrary or unknown relationships in the + ownership tree, `observeWeakly` is the preferred option. + + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - parameter retainSelf: Retains self during observation if set `true`. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observe(_ type: Element.Type, + _ keyPath: String, + options: KeyValueObservingOptions = [.new, .initial], + retainSelf: Bool = true) -> Observable { + KVOObservable(object: self.base, keyPath: keyPath, options: options, retainTarget: retainSelf).asObservable() + } + + /** + Observes values at the provided key path using the provided options. + + - parameter keyPath: A key path between the object and one of its properties. + - parameter options: Key-value observation options, defaults to `.new` and `.initial`. + + - note: When the object is deallocated, a completion event is emitted. + + - returns: An observable emitting value changes at the provided key path. + */ + public func observe(_ keyPath: KeyPath, + options: NSKeyValueObservingOptions = [.new, .initial]) -> Observable { + Observable.create { [weak base] observer in + let observation = base?.observe(keyPath, options: options) { obj, _ in + observer.on(.next(obj[keyPath: keyPath])) + } + + return Disposables.create { observation?.invalidate() } + } + .take(until: base.rx.deallocated) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) +// KVO +extension Reactive where Base: NSObject { + /** + Observes values on `keyPath` starting from `self` with `options` and doesn't retain `self`. + + It can be used in all cases where `observe` can be used and additionally + + * because it won't retain observed target, it can be used to observe arbitrary object graph whose ownership relation is unknown + * it can be used to observe `weak` properties + + **Since it needs to intercept object deallocation process it needs to perform swizzling of `dealloc` method on observed object.** + + - parameter keyPath: Key path of property names to observe. + - parameter options: KVO mechanism notification options. + - returns: Observable sequence of objects on `keyPath`. + */ + public func observeWeakly(_ type: Element.Type, _ keyPath: String, options: KeyValueObservingOptions = [.new, .initial]) -> Observable { + return observeWeaklyKeyPathFor(self.base, keyPath: keyPath, options: options) + .map { n in + return n as? Element + } + } +} +#endif + +// Dealloc +extension Reactive where Base: AnyObject { + + /** + Observable sequence of object deallocated events. + + After object is deallocated one `()` element will be produced and sequence will immediately complete. + + - returns: Observable sequence of object deallocated events. + */ + public var deallocated: Observable { + return self.synchronized { + if let deallocObservable = objc_getAssociatedObject(self.base, &deallocatedSubjectContext) as? DeallocObservable { + return deallocObservable.subject + } + + let deallocObservable = DeallocObservable() + + objc_setAssociatedObject(self.base, &deallocatedSubjectContext, deallocObservable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return deallocObservable.subject + } + } + +#if !DISABLE_SWIZZLING && !os(Linux) + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced before message is invoked on target object. `methodInvoked` + exists in case observing of invoked messages is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func sentMessage(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocating.map { _ in [] } + } + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of message arguments that completes when object is deallocated. + + Each element is produced after message is invoked on target object. `sentMessage` + exists in case interception of sent messages before they were invoked is needed. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + In case some argument is `nil`, instance of `NSNull()` will be sent. + + - returns: Observable sequence of arguments passed to `selector` method. + */ + public func methodInvoked(_ selector: Selector) -> Observable<[Any]> { + return self.synchronized { + // in case of dealloc selector replay subject behavior needs to be used + if selector == deallocSelector { + return self.deallocated.map { _ in [] } + } + + + do { + let proxy: MessageSentProxy = try self.registerMessageInterceptor(selector) + return proxy.methodInvoked.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + /** + Observable sequence of object deallocating events. + + When `dealloc` message is sent to `self` one `()` element will be produced and after object is deallocated sequence + will immediately complete. + + In case an error occurs sequence will fail with `RxCocoaObjCRuntimeError`. + + - returns: Observable sequence of object deallocating events. + */ + public var deallocating: Observable<()> { + return self.synchronized { + do { + let proxy: DeallocatingProxy = try self.registerMessageInterceptor(deallocSelector) + return proxy.messageSent.asObservable() + } + catch let e { + return Observable.error(e) + } + } + } + + private func registerMessageInterceptor(_ selector: Selector) throws -> T { + let rxSelector = RX_selector(selector) + let selectorReference = RX_reference_from_selector(rxSelector) + + let subject: T + if let existingSubject = objc_getAssociatedObject(self.base, selectorReference) as? T { + subject = existingSubject + } + else { + subject = T() + objc_setAssociatedObject( + self.base, + selectorReference, + subject, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + + if subject.isActive { + return subject + } + + var error: NSError? + let targetImplementation = RX_ensure_observing(self.base, selector, &error) + if targetImplementation == nil { + throw error?.rxCocoaErrorForTarget(self.base) ?? RxCocoaError.unknown + } + + subject.targetImplementation = targetImplementation! + + return subject + } +#endif +} + +// MARK: Message interceptors + +#if !DISABLE_SWIZZLING && !os(Linux) + + private protocol MessageInterceptorSubject: AnyObject { + init() + + var isActive: Bool { + get + } + + var targetImplementation: IMP { get set } + } + + private final class DeallocatingProxy + : MessageInterceptorSubject + , RXDeallocatingObserver { + typealias Element = () + + let messageSent = ReplaySubject<()>.create(bufferSize: 1) + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func deallocating() { + self.messageSent.on(.next(())) + } + + deinit { + self.messageSent.on(.completed) + } + } + + private final class MessageSentProxy + : MessageInterceptorSubject + , RXMessageSentObserver { + typealias Element = [AnyObject] + + let messageSent = PublishSubject<[Any]>() + let methodInvoked = PublishSubject<[Any]>() + + @objc var targetImplementation: IMP = RX_default_target_implementation() + + var isActive: Bool { + return self.targetImplementation != RX_default_target_implementation() + } + + init() { + } + + @objc func messageSent(withArguments arguments: [Any]) { + self.messageSent.on(.next(arguments)) + } + + @objc func methodInvoked(withArguments arguments: [Any]) { + self.methodInvoked.on(.next(arguments)) + } + + deinit { + self.messageSent.on(.completed) + self.methodInvoked.on(.completed) + } + } + +#endif + + +private final class DeallocObservable { + let subject = ReplaySubject.create(bufferSize:1) + + init() { + } + + deinit { + self.subject.on(.next(())) + self.subject.on(.completed) + } +} + +// MARK: KVO + +#if !os(Linux) + +private protocol KVOObservableProtocol { + var target: AnyObject { get } + var keyPath: String { get } + var retainTarget: Bool { get } + var options: KeyValueObservingOptions { get } +} + +private final class KVOObserver + : _RXKVOObserver + , Disposable { + typealias Callback = (Any?) -> Void + + var retainSelf: KVOObserver? + + init(parent: KVOObservableProtocol, callback: @escaping Callback) { + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + + super.init(target: parent.target, retainTarget: parent.retainTarget, keyPath: parent.keyPath, options: parent.options.nsOptions, callback: callback) + self.retainSelf = self + } + + override func dispose() { + super.dispose() + self.retainSelf = nil + } + + deinit { + #if TRACE_RESOURCES + _ = Resources.decrementTotal() + #endif + } +} + +private final class KVOObservable + : ObservableType + , KVOObservableProtocol { + typealias Element = Element? + + unowned var target: AnyObject + var strongTarget: AnyObject? + + var keyPath: String + var options: KeyValueObservingOptions + var retainTarget: Bool + + init(object: AnyObject, keyPath: String, options: KeyValueObservingOptions, retainTarget: Bool) { + self.target = object + self.keyPath = keyPath + self.options = options + self.retainTarget = retainTarget + if retainTarget { + self.strongTarget = object + } + } + + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element? { + let observer = KVOObserver(parent: self) { value in + if value as? NSNull != nil { + observer.on(.next(nil)) + return + } + observer.on(.next(value as? Element)) + } + + return Disposables.create(with: observer.dispose) + } + +} + +private extension KeyValueObservingOptions { + var nsOptions: NSKeyValueObservingOptions { + var result: UInt = 0 + if self.contains(.new) { + result |= NSKeyValueObservingOptions.new.rawValue + } + if self.contains(.initial) { + result |= NSKeyValueObservingOptions.initial.rawValue + } + + return NSKeyValueObservingOptions(rawValue: result) + } +} + +#endif + +#if !DISABLE_SWIZZLING && !os(Linux) + + private func observeWeaklyKeyPathFor(_ target: NSObject, keyPath: String, options: KeyValueObservingOptions) -> Observable { + let components = keyPath.components(separatedBy: ".").filter { $0 != "self" } + + let observable = observeWeaklyKeyPathFor(target, keyPathSections: components, options: options) + .finishWithNilWhenDealloc(target) + + if !options.isDisjoint(with: .initial) { + return observable + } + else { + return observable + .skip(1) + } + } + + // This should work correctly + // Identifiers can't contain `,`, so the only place where `,` can appear + // is as a delimiter. + // This means there is `W` as element in an array of property attributes. + private func isWeakProperty(_ properyRuntimeInfo: String) -> Bool { + properyRuntimeInfo.range(of: ",W,") != nil + } + + private extension ObservableType where Element == AnyObject? { + func finishWithNilWhenDealloc(_ target: NSObject) + -> Observable { + let deallocating = target.rx.deallocating + + return deallocating + .map { _ in + return Observable.just(nil) + } + .startWith(self.asObservable()) + .switchLatest() + } + } + + private func observeWeaklyKeyPathFor( + _ target: NSObject, + keyPathSections: [String], + options: KeyValueObservingOptions + ) -> Observable { + + weak var weakTarget: AnyObject? = target + + let propertyName = keyPathSections[0] + let remainingPaths = Array(keyPathSections[1.. + + // KVO recursion for value changes + return propertyObservable + .flatMapLatest { (nextTarget: AnyObject?) -> Observable in + if nextTarget == nil { + return Observable.just(nil) + } + let nextObject = nextTarget! as? NSObject + + let strongTarget: AnyObject? = weakTarget + + if nextObject == nil { + return Observable.error(RxCocoaError.invalidObjectOnKeyPath(object: nextTarget!, sourceObject: strongTarget ?? NSNull(), propertyName: propertyName)) + } + + // if target is alive, then send change + // if it's deallocated, don't send anything + if strongTarget == nil { + return Observable.empty() + } + + let nextElementsObservable = keyPathSections.count == 1 + ? Observable.just(nextTarget) + : observeWeaklyKeyPathFor(nextObject!, keyPathSections: remainingPaths, options: options) + + if isWeak { + return nextElementsObservable + .finishWithNilWhenDealloc(nextObject!) + } + else { + return nextElementsObservable + } + } + } +#endif + +// MARK: Constants + +private let deallocSelector = NSSelectorFromString("dealloc") + +// MARK: AnyObject + Reactive + +extension Reactive where Base: AnyObject { + func synchronized( _ action: () -> T) -> T { + objc_sync_enter(self.base) + let result = action() + objc_sync_exit(self.base) + return result + } +} + +extension Reactive where Base: AnyObject { + /** + Helper to make sure that `Observable` returned from `createCachedObservable` is only created once. + This is important because there is only one `target` and `action` properties on `NSControl` or `UIBarButtonItem`. + */ + func lazyInstanceObservable(_ key: UnsafeRawPointer, createCachedObservable: () -> T) -> T { + if let value = objc_getAssociatedObject(self.base, key) { + return value as! T + } + + let observable = createCachedObservable() + + objc_setAssociatedObject(self.base, key, observable, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + + return observable + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift new file mode 100644 index 0000000..30ffa2b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/NotificationCenter+Rx.swift @@ -0,0 +1,31 @@ +// +// NotificationCenter+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +extension Reactive where Base: NotificationCenter { + /** + Transforms notifications posted to notification center to observable sequence of notifications. + + - parameter name: Optional name used to filter notifications. + - parameter object: Optional object used to filter notifications. + - returns: Observable sequence of posted notifications. + */ + public func notification(_ name: Notification.Name?, object: AnyObject? = nil) -> Observable { + return Observable.create { [weak object] observer in + let nsObserver = self.base.addObserver(forName: name, object: object, queue: nil) { notification in + observer.on(.next(notification)) + } + + return Disposables.create { + self.base.removeObserver(nsObserver) + } + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift b/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift new file mode 100644 index 0000000..93e65cc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift @@ -0,0 +1,240 @@ +// +// URLSession+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation +import RxSwift + +#if canImport(FoundationNetworking) +import FoundationNetworking +#endif + +/// RxCocoa URL errors. +public enum RxCocoaURLError + : Swift.Error { + /// Unknown error occurred. + case unknown + /// Response is not NSHTTPURLResponse + case nonHTTPResponse(response: URLResponse) + /// Response is not successful. (not in `200 ..< 300` range) + case httpRequestFailed(response: HTTPURLResponse, data: Data?) + /// Deserialization error. + case deserializationError(error: Swift.Error) +} + +extension RxCocoaURLError + : CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error has occurred." + case let .nonHTTPResponse(response): + return "Response is not NSHTTPURLResponse `\(response)`." + case let .httpRequestFailed(response, _): + return "HTTP request failed with `\(response.statusCode)`." + case let .deserializationError(error): + return "Error during deserialization of the response: \(error)" + } + } +} + +private func escapeTerminalString(_ value: String) -> String { + return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil) +} + +private func convertURLRequestToCurlCommand(_ request: URLRequest) -> String { + let method = request.httpMethod ?? "GET" + var returnValue = "curl -X \(method) " + + if let httpBody = request.httpBody { + let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8) + if let body = maybeBody { + returnValue += "-d \"\(escapeTerminalString(body))\" " + } + } + + for (key, value) in request.allHTTPHeaderFields ?? [:] { + let escapedKey = escapeTerminalString(key as String) + let escapedValue = escapeTerminalString(value as String) + returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" " + } + + let URLString = request.url?.absoluteString ?? "" + + returnValue += "\n\"\(escapeTerminalString(URLString))\"" + + returnValue += " -i -v" + + return returnValue +} + +private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String { + let ms = Int(interval * 1000) + + if let response = response as? HTTPURLResponse { + if 200 ..< 300 ~= response.statusCode { + return "Success (\(ms)ms): Status \(response.statusCode)" + } + else { + return "Failure (\(ms)ms): Status \(response.statusCode)" + } + } + + if let error = error { + if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled { + return "Canceled (\(ms)ms)" + } + return "Failure (\(ms)ms): NSError > \(error)" + } + + return "" +} + +extension Reactive where Base: URLSession { + /** + Observable sequence of responses for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + - parameter request: URL request. + - returns: Observable sequence of URL responses. + */ + public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> { + return Observable.create { observer in + + // smart compiler should be able to optimize this out + let d: Date? + + if URLSession.rx.shouldLogRequest(request) { + d = Date() + } + else { + d = nil + } + + let task = self.base.dataTask(with: request) { data, response, error in + + if URLSession.rx.shouldLogRequest(request) { + let interval = Date().timeIntervalSince(d ?? Date()) + print(convertURLRequestToCurlCommand(request)) + #if os(Linux) + print(convertResponseToString(response, error.flatMap { $0 as NSError }, interval)) + #else + print(convertResponseToString(response, error.map { $0 as NSError }, interval)) + #endif + } + + guard let response = response, let data = data else { + observer.on(.error(error ?? RxCocoaURLError.unknown)) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response))) + return + } + + observer.on(.next((httpResponse, data))) + observer.on(.completed) + } + + task.resume() + + return Disposables.create(with: task.cancel) + } + } + + /** + Observable sequence of response data for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + - parameter request: URL request. + - returns: Observable sequence of response data. + */ + public func data(request: URLRequest) -> Observable { + return self.response(request: request).map { pair -> Data in + if 200 ..< 300 ~= pair.0.statusCode { + return pair.1 + } + else { + throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1) + } + } + } + + /** + Observable sequence of response JSON for URL request. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter request: URL request. + - returns: Observable sequence of response JSON. + */ + public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable { + return self.data(request: request).map { data -> Any in + do { + return try JSONSerialization.jsonObject(with: data, options: options) + } catch let error { + throw RxCocoaURLError.deserializationError(error: error) + } + } + } + + /** + Observable sequence of response JSON for GET request with `URL`. + + Performing of request starts after observer is subscribed and not after invoking this method. + + **URL requests will be performed per subscribed observer.** + + Any error during fetching of the response will cause observed sequence to terminate with error. + + If response is not HTTP response with status code in the range of `200 ..< 300`, sequence + will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`. + + If there is an error during JSON deserialization observable sequence will fail with that error. + + - parameter url: URL of `NSURLRequest` request. + - returns: Observable sequence of response JSON. + */ + public func json(url: Foundation.URL) -> Observable { + self.json(request: URLRequest(url: url)) + } +} + +extension Reactive where Base == URLSession { + /// Log URL requests to standard output in curl format. + public static var shouldLogRequest: (URLRequest) -> Bool = { _ in + #if DEBUG + return true + #else + return false + #endif + } +} diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RX.m b/Pods/RxCocoa/RxCocoa/Runtime/_RX.m new file mode 100644 index 0000000..cffbfbc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RX.m @@ -0,0 +1,10 @@ +// +// _RX.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RX.h" + diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m new file mode 100644 index 0000000..36338a5 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXDelegateProxy.m @@ -0,0 +1,147 @@ +// +// _RXDelegateProxy.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXDelegateProxy.h" +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +@interface _RXDelegateProxy () { + id __weak __forwardToDelegate; +} + +@property (nonatomic, strong) id strongForwardDelegate; + +@end + +static NSMutableDictionary *voidSelectorsPerClass = nil; + +@implementation _RXDelegateProxy + ++(NSSet*)collectVoidSelectorsForProtocol:(Protocol *)protocol { + NSMutableSet *selectors = [NSMutableSet set]; + + unsigned int protocolMethodCount = 0; + struct objc_method_description *pMethods = protocol_copyMethodDescriptionList(protocol, NO, YES, &protocolMethodCount); + + for (unsigned int i = 0; i < protocolMethodCount; ++i) { + struct objc_method_description method = pMethods[i]; + if (RX_is_method_with_description_void(method)) { + [selectors addObject:SEL_VALUE(method.name)]; + } + } + + free(pMethods); + + unsigned int numberOfBaseProtocols = 0; + Protocol * __unsafe_unretained * pSubprotocols = protocol_copyProtocolList(protocol, &numberOfBaseProtocols); + + for (unsigned int i = 0; i < numberOfBaseProtocols; ++i) { + [selectors unionSet:[self collectVoidSelectorsForProtocol:pSubprotocols[i]]]; + } + + free(pSubprotocols); + + return selectors; +} + ++(void)initialize { + @synchronized (_RXDelegateProxy.class) { + if (voidSelectorsPerClass == nil) { + voidSelectorsPerClass = [[NSMutableDictionary alloc] init]; + } + + NSMutableSet *voidSelectors = [NSMutableSet set]; + +#define CLASS_HIERARCHY_MAX_DEPTH 100 + + NSInteger classHierarchyDepth = 0; + Class targetClass = NULL; + + for (classHierarchyDepth = 0, targetClass = self; + classHierarchyDepth < CLASS_HIERARCHY_MAX_DEPTH && targetClass != nil; + ++classHierarchyDepth, targetClass = class_getSuperclass(targetClass) + ) { + unsigned int count; + Protocol *__unsafe_unretained *pProtocols = class_copyProtocolList(targetClass, &count); + + for (unsigned int i = 0; i < count; i++) { + NSSet *selectorsForProtocol = [self collectVoidSelectorsForProtocol:pProtocols[i]]; + [voidSelectors unionSet:selectorsForProtocol]; + } + + free(pProtocols); + } + + if (classHierarchyDepth == CLASS_HIERARCHY_MAX_DEPTH) { + NSLog(@"Detected weird class hierarchy with depth over %d. Starting with this class -> %@", CLASS_HIERARCHY_MAX_DEPTH, self); +#if DEBUG + abort(); +#endif + } + + voidSelectorsPerClass[CLASS_VALUE(self)] = voidSelectors; + } +} + +-(id)_forwardToDelegate { + return __forwardToDelegate; +} + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate { + __forwardToDelegate = forwardToDelegate; + if (retainDelegate) { + self.strongForwardDelegate = forwardToDelegate; + } + else { + self.strongForwardDelegate = nil; + } +} + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector { + return [super respondsToSelector:selector]; +} + +-(BOOL)voidDelegateMethodsContain:(SEL)selector { + @synchronized(_RXDelegateProxy.class) { + NSSet *voidSelectors = voidSelectorsPerClass[CLASS_VALUE(self.class)]; + NSAssert(voidSelectors != nil, @"Set of allowed methods not initialized"); + return [voidSelectors containsObject:SEL_VALUE(selector)]; + } +} + +-(void)forwardInvocation:(NSInvocation *)anInvocation { + BOOL isVoid = RX_is_method_signature_void(anInvocation.methodSignature); + NSArray *arguments = nil; + if (isVoid) { + arguments = RX_extract_arguments(anInvocation); + [self _sentMessage:anInvocation.selector withArguments:arguments]; + } + + if (self._forwardToDelegate && [self._forwardToDelegate respondsToSelector:anInvocation.selector]) { + [anInvocation invokeWithTarget:self._forwardToDelegate]; + } + + if (isVoid) { + [self _methodInvoked:anInvocation.selector withArguments:arguments]; + } +} + +// abstract method +-(void)_sentMessage:(SEL)selector withArguments:(NSArray *)arguments { + +} + +// abstract method +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray *)arguments { + +} + +-(void)dealloc { +} + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m new file mode 100644 index 0000000..fc8fb75 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXKVOObserver.m @@ -0,0 +1,54 @@ +// +// _RXKVOObserver.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import "include/_RXKVOObserver.h" + +@interface _RXKVOObserver () + +@property (nonatomic, unsafe_unretained) id target; +@property (nonatomic, strong ) id retainedTarget; +@property (nonatomic, copy ) NSString *keyPath; +@property (nonatomic, copy ) void (^callback)(id); + +@end + +@implementation _RXKVOObserver + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback { + self = [super init]; + if (!self) return nil; + + self.target = target; + if (retainTarget) { + self.retainedTarget = target; + } + self.keyPath = keyPath; + self.callback = callback; + + [self.target addObserver:self forKeyPath:self.keyPath options:options context:nil]; + + return self; +} + +-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context { + @synchronized(self) { + self.callback(change[NSKeyValueChangeNewKey]); + } +} + +-(void)dispose { + [self.target removeObserver:self forKeyPath:self.keyPath context:nil]; + self.target = nil; + self.retainedTarget = nil; +} + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m b/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m new file mode 100644 index 0000000..2e685aa --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/_RXObjCRuntime.m @@ -0,0 +1,1062 @@ +// +// _RXObjCRuntime.m +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import +#import + +#import "include/_RX.h" +#import "include/_RXObjCRuntime.h" + +// self + cmd +#define HIDDEN_ARGUMENT_COUNT 2 + +#if !DISABLE_SWIZZLING + +#define NSErrorParam NSError *__autoreleasing __nullable * __nullable + +@class RXObjCRuntime; + +BOOL RXAbortOnThreadingHazard = NO; + +typedef NSInvocation *NSInvocationRef; +typedef NSMethodSignature *NSMethodSignatureRef; +typedef unsigned char rx_uchar; +typedef unsigned short rx_ushort; +typedef unsigned int rx_uint; +typedef unsigned long rx_ulong; +typedef id (^rx_block)(id); +typedef BOOL (^RXInterceptWithOptimizedObserver)(RXObjCRuntime * __nonnull self, Class __nonnull class, SEL __nonnull selector, NSErrorParam error); + +static CFTypeID defaultTypeID; +static SEL deallocSelector; + +static int RxSwizzlingTargetClassKey = 0; + +#if TRACE_RESOURCES +_Atomic static int32_t numberOInterceptedMethods = 0; +_Atomic static int32_t numberOfForwardedMethods = 0; +#endif + +#define THREADING_HAZARD(class) \ + NSLog(@"There was a problem swizzling on `%@`.\nYou have probably two libraries performing swizzling in runtime.\nWe didn't want to crash your program, but this is not good ...\nYou an solve this problem by either not using swizzling in this library, removing one of those other libraries, or making sure that swizzling parts are synchronized (only perform them on main thread).\nAnd yes, this message will self destruct when you clear the console, and since it's non deterministic, the problem could still exist and it will be hard for you to reproduce it.", NSStringFromClass(class)); ABORT_IN_DEBUG if (RXAbortOnThreadingHazard) { abort(); } + +#define ALWAYS(condition, message) if (!(condition)) { [NSException raise:@"RX Invalid Operator" format:@"%@", message]; } +#define ALWAYS_WITH_INFO(condition, message) NSAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) +#define C_ALWAYS(condition, message) NSCAssert((condition), @"%@ [%@] > %@", NSStringFromClass(class), NSStringFromSelector(selector), (message)) + +#define RX_PREFIX @"_RX_namespace_" + +#define RX_ARG_id(value) ((value) ?: [NSNull null]) +#define RX_ARG_char(value) [NSNumber numberWithChar:value] +#define RX_ARG_short(value) [NSNumber numberWithShort:value] +#define RX_ARG_int(value) [NSNumber numberWithInt:value] +#define RX_ARG_long(value) [NSNumber numberWithLong:value] +#define RX_ARG_BOOL(value) [NSNumber numberWithBool:value] +#define RX_ARG_SEL(value) [NSNumber valueWithPointer:value] +#define RX_ARG_rx_uchar(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ushort(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_uint(value) [NSNumber numberWithUnsignedInt:value] +#define RX_ARG_rx_ulong(value) [NSNumber numberWithUnsignedLong:value] +#define RX_ARG_rx_block(value) ((id)(value) ?: [NSNull null]) +#define RX_ARG_float(value) [NSNumber numberWithFloat:value] +#define RX_ARG_double(value) [NSNumber numberWithDouble:value] + +typedef struct supported_type { + const char *encoding; +} supported_type_t; + +static supported_type_t supported_types[] = { + { .encoding = @encode(void)}, + { .encoding = @encode(id)}, + { .encoding = @encode(Class)}, + { .encoding = @encode(void (^)(void))}, + { .encoding = @encode(char)}, + { .encoding = @encode(short)}, + { .encoding = @encode(int)}, + { .encoding = @encode(long)}, + { .encoding = @encode(long long)}, + { .encoding = @encode(unsigned char)}, + { .encoding = @encode(unsigned short)}, + { .encoding = @encode(unsigned int)}, + { .encoding = @encode(unsigned long)}, + { .encoding = @encode(unsigned long long)}, + { .encoding = @encode(float)}, + { .encoding = @encode(double)}, + { .encoding = @encode(BOOL)}, + { .encoding = @encode(const char*)}, +}; + +NSString * __nonnull const RXObjCRuntimeErrorDomain = @"RXObjCRuntimeErrorDomain"; +NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey = @"RXObjCRuntimeErrorIsKVOKey"; + +BOOL RX_return_type_is_supported(const char *type) { + if (type == nil) { + return NO; + } + + for (int i = 0; i < sizeof(supported_types) / sizeof(supported_type_t); ++i) { + if (supported_types[i].encoding[0] != type[0]) { + continue; + } + if (strcmp(supported_types[i].encoding, type) == 0) { + return YES; + } + } + + return NO; +} + +static BOOL RX_method_has_supported_return_type(Method method) { + const char *rawEncoding = method_getTypeEncoding(method); + ALWAYS(rawEncoding != nil, @"Example encoding method is nil."); + + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:rawEncoding]; + ALWAYS(methodSignature != nil, @"Method signature method is nil."); + + return RX_return_type_is_supported(methodSignature.methodReturnType); +} + +SEL __nonnull RX_selector(SEL __nonnull selector) { + NSString *selectorString = NSStringFromSelector(selector); + return NSSelectorFromString([RX_PREFIX stringByAppendingString:selectorString]); +} + +#endif + +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature) { + const char *methodReturnType = methodSignature.methodReturnType; + return strcmp(methodReturnType, @encode(void)) == 0; +} + +BOOL RX_is_method_with_description_void(struct objc_method_description method) { + return strncmp(method.types, @encode(void), 1) == 0; +} + +id __nonnull RX_extract_argument_at_index(NSInvocation * __nonnull invocation, NSUInteger index) { + const char *argumentType = [invocation.methodSignature getArgumentTypeAtIndex:index]; + +#define RETURN_VALUE(type) \ + else if (strcmp(argumentType, @encode(type)) == 0) {\ + type val = 0; \ + [invocation getArgument:&val atIndex:index]; \ + return @(val); \ + } + + // Skip const type qualifier. + if (argumentType[0] == 'r') { + argumentType++; + } + + if (strcmp(argumentType, @encode(id)) == 0 + || strcmp(argumentType, @encode(Class)) == 0 + || strcmp(argumentType, @encode(void (^)(void))) == 0 + ) { + __unsafe_unretained id argument = nil; + [invocation getArgument:&argument atIndex:index]; + return argument; + } + RETURN_VALUE(char) + RETURN_VALUE(short) + RETURN_VALUE(int) + RETURN_VALUE(long) + RETURN_VALUE(long long) + RETURN_VALUE(unsigned char) + RETURN_VALUE(unsigned short) + RETURN_VALUE(unsigned int) + RETURN_VALUE(unsigned long) + RETURN_VALUE(unsigned long long) + RETURN_VALUE(float) + RETURN_VALUE(double) + RETURN_VALUE(BOOL) + RETURN_VALUE(const char *) + else { + NSUInteger size = 0; + NSGetSizeAndAlignment(argumentType, &size, NULL); + NSCParameterAssert(size > 0); + uint8_t data[size]; + [invocation getArgument:&data atIndex:index]; + + return [NSValue valueWithBytes:&data objCType:argumentType]; + } +} + +NSArray *RX_extract_arguments(NSInvocation *invocation) { + NSUInteger numberOfArguments = invocation.methodSignature.numberOfArguments; + NSUInteger numberOfVisibleArguments = numberOfArguments - HIDDEN_ARGUMENT_COUNT; + + NSCParameterAssert(numberOfVisibleArguments >= 0); + + NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:numberOfVisibleArguments]; + + for (NSUInteger index = HIDDEN_ARGUMENT_COUNT; index < numberOfArguments; ++index) { + [arguments addObject:RX_extract_argument_at_index(invocation, index) ?: [NSNull null]]; + } + + return arguments; +} + +IMP __nonnull RX_default_target_implementation(void) { + return _objc_msgForward; +} + +#if !DISABLE_SWIZZLING + +void * __nonnull RX_reference_from_selector(SEL __nonnull selector) { + return selector; +} + +static BOOL RX_forward_invocation(id __nonnull __unsafe_unretained self, NSInvocation *invocation) { + SEL originalSelector = RX_selector(invocation.selector); + + id messageSentObserver = objc_getAssociatedObject(self, originalSelector); + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver messageSentWithArguments:arguments]; + } + + if ([self respondsToSelector:originalSelector]) { + invocation.selector = originalSelector; + [invocation invokeWithTarget:self]; + + if (messageSentObserver != nil) { + NSArray *arguments = RX_extract_arguments(invocation); + [messageSentObserver methodInvokedWithArguments:arguments]; + } + + return YES; + } + + return NO; +} + +static BOOL RX_responds_to_selector(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return NO; } + + Method m = class_getInstanceMethod(class, selector); + return m != nil; + +} + +static NSMethodSignatureRef RX_method_signature(id __nonnull __unsafe_unretained self, SEL selector) { + Class class = object_getClass(self); + if (class == nil) { return nil; } + + Method method = class_getInstanceMethod(class, selector); + if (method == nil) { return nil; } + + const char *encoding = method_getTypeEncoding(method); + if (encoding == nil) { return nil; } + + return [NSMethodSignature signatureWithObjCTypes:encoding]; +} + +static NSString * __nonnull RX_method_encoding(Method __nonnull method) { + const char *typeEncoding = method_getTypeEncoding(method); + ALWAYS(typeEncoding != nil, @"Method encoding is nil."); + + NSString *encoding = [NSString stringWithCString:typeEncoding encoding:NSASCIIStringEncoding]; + ALWAYS(encoding != nil, @"Can't convert encoding to NSString."); + return encoding; +} + +@interface RXObjCRuntime: NSObject + +@property (nonatomic, assign) pthread_mutex_t lock; + +@property (nonatomic, strong) NSMutableSet *classesThatSupportObservingByForwarding; +@property (nonatomic, strong) NSMutableDictionary *> *forwardedSelectorsByClass; + +@property (nonatomic, strong) NSMutableDictionary *dynamicSubclassByRealClass; +@property (nonatomic, strong) NSMutableDictionary*> *interceptorIMPbySelectorsByClass; + ++(RXObjCRuntime*)instance; + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action; +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error; +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error; + + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector; + +@end + +/** + All API methods perform work on locked instance of `RXObjCRuntime`. In that way it's easy to prove + that every action is properly locked. + */ +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSErrorParam error) { + __block IMP targetImplementation = nil; + // Target is the second object that needs to be synchronized to TRY to make sure other swizzling framework + // won't do something in parallel. + // Even though this is too fine grained locking and more coarse grained locks should exist, this is just in case + // someone calls this method directly without any external lock. + @synchronized(target) { + // The only other resource that all other swizzling libraries have in common without introducing external + // dependencies is class object. + // + // It is polite to try to synchronize it in hope other unknown entities will also attempt to do so. + // It's like trying to figure out how to communicate with aliens without actually communicating, + // save for the fact that aliens are people, programmers, authors of swizzling libraries. + @synchronized([target class]) { + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + targetImplementation = [self ensurePrepared:target + forObserving:selector + error:error]; + }]; + } + } + + return targetImplementation; +} + +// bodies + +#define FORWARD_BODY(invocation) if (RX_forward_invocation(self, NAME_CAT(_, 0, invocation))) { return; } + +#define RESPONDS_TO_SELECTOR_BODY(selector) if (RX_responds_to_selector(self, NAME_CAT(_, 0, selector))) return YES; + +#define CLASS_BODY(...) return actAsClass; + +#define METHOD_SIGNATURE_FOR_SELECTOR_BODY(selector) \ + NSMethodSignatureRef methodSignature = RX_method_signature(self, NAME_CAT(_, 0, selector)); \ + if (methodSignature != nil) { \ + return methodSignature; \ + } + +#define DEALLOCATING_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer deallocating]; \ + } + +#define OBSERVE_BODY(...) \ + id observer = objc_getAssociatedObject(self, rxSelector); \ + \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer messageSentWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define OBSERVE_INVOKED_BODY(...) \ + if (observer != nil && observer.targetImplementation == thisIMP) { \ + [observer methodInvokedWithArguments:@[COMMA_DELIMITED_ARGUMENTS(__VA_ARGS__)]]; \ + } \ + + +#define BUILD_ARG_WRAPPER(type) RX_ARG_ ## type //RX_ARG_ ## type + +#define CAT(_1, _2, head, tail) RX_CAT2(head, tail) +#define SEPARATE_BY_COMMA(_1, _2, head, tail) head, tail +#define SEPARATE_BY_SPACE(_1, _2, head, tail) head tail +#define SEPARATE_BY_UNDERSCORE(head, tail) RX_CAT2(RX_CAT2(head, _), tail) + +#define UNDERSCORE_TYPE_CAT(_1, index, type) RX_CAT2(_, type) // generates -> _type +#define NAME_CAT(_1, index, type) SEPARATE_BY_UNDERSCORE(type, index) // generates -> type_0 +#define TYPE_AND_NAME_CAT(_1, index, type) type SEPARATE_BY_UNDERSCORE(type, index) // generates -> type type_0 +#define NOT_NULL_ARGUMENT_CAT(_1, index, type) BUILD_ARG_WRAPPER(type)(NAME_CAT(_1, index, type)) // generates -> ((id)(type_0) ?: [NSNull null]) +#define EXAMPLE_PARAMETER(_1, index, type) RX_CAT2(_, type):(type)SEPARATE_BY_UNDERSCORE(type, index) // generates -> _type:(type)type_0 +#define SELECTOR_PART(_1, index, type) RX_CAT2(_, type:) // generates -> _type: + +#define COMMA_DELIMITED_ARGUMENTS(...) RX_FOREACH(_, SEPARATE_BY_COMMA, NOT_NULL_ARGUMENT_CAT, ## __VA_ARGS__) +#define ARGUMENTS(...) RX_FOREACH_COMMA(_, NAME_CAT, ## __VA_ARGS__) +#define DECLARE_ARGUMENTS(...) RX_FOREACH_COMMA(_, TYPE_AND_NAME_CAT, ## __VA_ARGS__) + +// optimized observe methods + +#define GENERATE_SELECTOR_IDENTIFIER(...) RX_CAT2(exampleSelector, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_METHOD_IDENTIFIER(...) RX_CAT2(swizzle, RX_FOREACH(_, CAT, UNDERSCORE_TYPE_CAT, ## __VA_ARGS__)) + +#define GENERATE_OBSERVE_METHOD_DECLARATION(...) \ + -(BOOL)GENERATE_METHOD_IDENTIFIER(__VA_ARGS__):(Class __nonnull)class \ + selector:(SEL)selector \ + error:(NSErrorParam)error { \ + + +#define BUILD_EXAMPLE_METHOD(return_value, ...) \ + +(return_value)RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, EXAMPLE_PARAMETER, ## __VA_ARGS__)) {} + +#define BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ...) \ + RX_CAT2(RX_CAT2(example_, return_value), RX_FOREACH(_, SEPARATE_BY_SPACE, SELECTOR_PART, ## __VA_ARGS__)) + +#define SWIZZLE_OBSERVE_METHOD_DEFINITIONS(return_value, ...) \ + BUILD_EXAMPLE_METHOD(return_value, ## __VA_ARGS__) \ + SWIZZLE_METHOD(return_value, GENERATE_OBSERVE_METHOD_DECLARATION(return_value, ## __VA_ARGS__), OBSERVE_BODY, OBSERVE_INVOKED_BODY, ## __VA_ARGS__) \ + +#define SWIZZLE_OBSERVE_METHOD_BODY(return_value, ...) \ + __unused SEL GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__) = @selector(BUILD_EXAMPLE_METHOD_SELECTOR(return_value, ## __VA_ARGS__)); \ + [self registerOptimizedObserver:^BOOL(RXObjCRuntime * __nonnull self, Class __nonnull class, \ + SEL __nonnull selector, NSErrorParam error) { \ + return [self GENERATE_METHOD_IDENTIFIER(return_value, ## __VA_ARGS__):class selector:selector error:error]; \ + } encodedAs:GENERATE_SELECTOR_IDENTIFIER(return_value, ## __VA_ARGS__)]; \ + +// infrastructure method + +#define NO_BODY(...) + +#define SWIZZLE_INFRASTRUCTURE_METHOD(return_value, method_name, parameters, method_selector, body, ...) \ + SWIZZLE_METHOD(return_value, -(BOOL)method_name:(Class __nonnull)class parameters error:(NSErrorParam)error \ + { \ + SEL selector = method_selector; , body, NO_BODY, __VA_ARGS__) \ + + +// common base + +#define SWIZZLE_METHOD(return_value, method_prototype, body, invoked_body, ...) \ +method_prototype \ + __unused SEL rxSelector = RX_selector(selector); \ + IMP (^newImplementationGenerator)(void) = ^() { \ + __block IMP thisIMP = nil; \ + id newImplementation = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__)) { \ + body(__VA_ARGS__) \ + \ + struct objc_super superInfo = { \ + .receiver = self, \ + .super_class = class_getSuperclass(class) \ + }; \ + \ + return_value (*msgSend)(struct objc_super *, SEL DECLARE_ARGUMENTS(__VA_ARGS__)) \ + = (__typeof__(msgSend))objc_msgSendSuper; \ + @try { \ + return msgSend(&superInfo, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(newImplementation); \ + return thisIMP; \ + }; \ + \ + IMP (^replacementImplementationGenerator)(IMP) = ^(IMP originalImplementation) { \ + __block return_value (*originalImplementationTyped)(__unsafe_unretained id, SEL DECLARE_ARGUMENTS(__VA_ARGS__) ) \ + = (__typeof__(originalImplementationTyped))(originalImplementation); \ + \ + __block IMP thisIMP = nil; \ + id implementationReplacement = ^return_value(__unsafe_unretained id self DECLARE_ARGUMENTS(__VA_ARGS__) ) { \ + body(__VA_ARGS__) \ + @try { \ + return originalImplementationTyped(self, selector ARGUMENTS(__VA_ARGS__)); \ + } \ + @finally { invoked_body(__VA_ARGS__) } \ + }; \ + \ + thisIMP = imp_implementationWithBlock(implementationReplacement); \ + return thisIMP; \ + }; \ + \ + return [self ensureSwizzledSelector:selector \ + ofClass:class \ + newImplementationGenerator:newImplementationGenerator \ + replacementImplementationGenerator:replacementImplementationGenerator \ + error:error]; \ + } \ + + +@interface RXObjCRuntime (InfrastructureMethods) +@end + +// MARK: Infrastructure Methods + +@implementation RXObjCRuntime (InfrastructureMethods) + +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleForwardInvocation, + , + @selector(forwardInvocation:), + FORWARD_BODY, + NSInvocationRef +) +SWIZZLE_INFRASTRUCTURE_METHOD( + BOOL, + swizzleRespondsToSelector, + , + @selector(respondsToSelector:), + RESPONDS_TO_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + Class __nonnull, + swizzleClass, + toActAs:(Class)actAsClass, + @selector(class), + CLASS_BODY +) +SWIZZLE_INFRASTRUCTURE_METHOD( + NSMethodSignatureRef, + swizzleMethodSignatureForSelector, + , + @selector(methodSignatureForSelector:), + METHOD_SIGNATURE_FOR_SELECTOR_BODY, + SEL +) +SWIZZLE_INFRASTRUCTURE_METHOD( + void, + swizzleDeallocating, + , + deallocSelector, + DEALLOCATING_BODY +) + +@end + +// MARK: Optimized intercepting methods for specific combination of parameter types + +@interface RXObjCRuntime (swizzle) + +@end + +@implementation RXObjCRuntime(swizzle) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, SEL) + +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, id) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, char) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, short) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, int) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, long) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uchar) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ushort) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_uint) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_ulong) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, rx_block) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, float) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, double) +SWIZZLE_OBSERVE_METHOD_DEFINITIONS(void, id, SEL) + ++(void)load { + SWIZZLE_OBSERVE_METHOD_BODY(void) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, SEL) + + SWIZZLE_OBSERVE_METHOD_BODY(void, id, id) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, char) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, short) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, int) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, long) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uchar) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ushort) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_uint) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_ulong) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, rx_block) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, float) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, double) + SWIZZLE_OBSERVE_METHOD_BODY(void, id, SEL) +} + +@end + +// MARK: RXObjCRuntime + +@implementation RXObjCRuntime + +static RXObjCRuntime *_instance = nil; +static NSMutableDictionary *optimizedObserversByMethodEncoding = nil; + ++(RXObjCRuntime*)instance { + return _instance; +} + ++(void)initialize { + _instance = [[RXObjCRuntime alloc] init]; + defaultTypeID = CFGetTypeID((CFTypeRef)RXObjCRuntime.class); // just need a reference of some object not from CF + deallocSelector = NSSelectorFromString(@"dealloc"); + NSAssert(_instance != nil, @"Failed to initialize swizzling"); +} + +-(instancetype)init { + self = [super init]; + if (!self) return nil; + + self.classesThatSupportObservingByForwarding = [NSMutableSet set]; + self.forwardedSelectorsByClass = [NSMutableDictionary dictionary]; + + self.dynamicSubclassByRealClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass = [NSMutableDictionary dictionary]; + + pthread_mutexattr_t lock_attr; + pthread_mutexattr_init(&lock_attr); + pthread_mutexattr_settype(&lock_attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(&_lock, &lock_attr); + pthread_mutexattr_destroy(&lock_attr); + + return self; +} + +-(void)performLocked:(void (^)(RXObjCRuntime* __nonnull))action { + pthread_mutex_lock(&_lock); + action(self); + pthread_mutex_unlock(&_lock); +} + ++(void)registerOptimizedObserver:(RXInterceptWithOptimizedObserver)registration encodedAs:(SEL)selector { + Method exampleEncodingMethod = class_getClassMethod(self, selector); + ALWAYS(exampleEncodingMethod != nil, @"Example encoding method is nil."); + + NSString *methodEncoding = RX_method_encoding(exampleEncodingMethod); + + if (optimizedObserversByMethodEncoding == nil) { + optimizedObserversByMethodEncoding = [NSMutableDictionary dictionary]; + } + + DLOG(@"Added optimized method: %@ (%@)", methodEncoding, NSStringFromSelector(selector)); + ALWAYS(optimizedObserversByMethodEncoding[methodEncoding] == nil, @"Optimized observer already registered") + optimizedObserversByMethodEncoding[methodEncoding] = registration; +} + +/** + This is the main entry point for observing messages sent to arbitrary objects. + */ +-(IMP __nullable)ensurePrepared:(id __nonnull)target forObserving:(SEL __nonnull)selector error:(NSErrorParam)error { + Method instanceMethod = class_getInstanceMethod([target class], selector); + if (instanceMethod == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], nil); + } + + if (selector == @selector(class) + || selector == @selector(forwardingTargetForSelector:) + || selector == @selector(methodSignatureForSelector:) + || selector == @selector(respondsToSelector:)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingPerformanceSensitiveMessages + userInfo:nil], nil); + } + + // For `dealloc` message, original implementation will be swizzled. + // This is a special case because observing `dealloc` message is performed when `observeWeakly` is used. + // + // Some toll free bridged classes don't handle `object_setClass` well and cause crashes. + // + // To make `deallocating` as robust as possible, original implementation will be replaced. + if (selector == deallocSelector) { + Class __nonnull deallocSwizzingTarget = [target class]; + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (![self swizzleDeallocating:deallocSwizzingTarget error:error]) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:deallocSwizzingTarget]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + else { + Class __nullable swizzlingImplementorClass = [self prepareTargetClassForObserving:target error:error]; + if (swizzlingImplementorClass == nil) { + return nil; + } + + NSString *methodEncoding = RX_method_encoding(instanceMethod); + RXInterceptWithOptimizedObserver optimizedIntercept = optimizedObserversByMethodEncoding[methodEncoding]; + + if (!RX_method_has_supported_return_type(instanceMethod)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType + userInfo:nil], nil); + } + + // optimized interception method + if (optimizedIntercept != nil) { + IMP interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + + if (!optimizedIntercept(self, swizzlingImplementorClass, selector, error)) { + return nil; + } + + interceptorIMPForSelector = [self interceptorImplementationForSelector:selector forClass:swizzlingImplementorClass]; + if (interceptorIMPForSelector != nil) { + return interceptorIMPForSelector; + } + } + // default fallback to observing by forwarding messages + else { + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + + if (![self observeByForwardingMessages:swizzlingImplementorClass + selector:selector + target:target + error:error]) { + return nil; + } + + if ([self forwardingSelector:selector forClass:swizzlingImplementorClass]) { + return RX_default_target_implementation(); + } + } + } + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorUnknown + userInfo:nil], nil); +} + +-(Class __nullable)prepareTargetClassForObserving:(id __nonnull)target error:(NSErrorParam)error { + Class swizzlingClass = objc_getAssociatedObject(target, &RxSwizzlingTargetClassKey); + if (swizzlingClass != nil) { + return swizzlingClass; + } + + Class __nonnull wannaBeClass = [target class]; + /** + Core Foundation classes are usually toll free bridged. Those classes crash the program in case + `object_setClass` is performed on them. + + There is a possibility to just swizzle methods on original object, but since those won't be usual use + cases for this library, then an error will just be reported for now. + */ + BOOL isThisTollFreeFoundationClass = CFGetTypeID((CFTypeRef)target) != defaultTypeID; + + if (isThisTollFreeFoundationClass) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects + userInfo:nil], nil); + } + + /** + If the object is reporting a different class then what it's real class, that means that there is probably + already some interception mechanism in place or something weird is happening. + + Most common case when this would happen is when using KVO (`observe`) and `sentMessage`. + + This error is easily resolved by just using `sentMessage` observing before `observe`. + + The reason why other way around could create issues is because KVO will unregister it's interceptor + class and restore original class. Unfortunately that will happen no matter was there another interceptor + subclass registered in hierarchy or not. + + Failure scenario: + * KVO sets class to be `__KVO__OriginalClass` (subclass of `OriginalClass`) + * `sentMessage` sets object class to be `_RX_namespace___KVO__OriginalClass` (subclass of `__KVO__OriginalClass`) + * then unobserving with KVO will restore class to be `OriginalClass` -> failure point + + The reason why changing order of observing works is because any interception method should return + object's original real class (if that doesn't happen then it's really easy to argue that's a bug + in that other library). + + This library won't remove registered interceptor even if there aren't any observers left because + it's highly unlikely it would have any benefit in real world use cases, and it's even more + dangerous. + */ + if ([target class] != object_getClass(target)) { + BOOL isKVO = [target respondsToSelector:NSSelectorFromString(@"_isKVOA")]; + + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted + userInfo:@{ + RXObjCRuntimeErrorIsKVOKey : @(isKVO) + }], nil); + } + + Class __nullable dynamicFakeSubclass = [self ensureHasDynamicFakeSubclass:wannaBeClass error:error]; + + if (dynamicFakeSubclass == nil) { + return nil; + } + + Class previousClass = object_setClass(target, dynamicFakeSubclass); + if (previousClass != wannaBeClass) { + THREADING_HAZARD(wannaBeClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism + userInfo:nil], nil); + } + + objc_setAssociatedObject(target, &RxSwizzlingTargetClassKey, dynamicFakeSubclass, OBJC_ASSOCIATION_RETAIN_NONATOMIC); + return dynamicFakeSubclass; +} + + +-(BOOL)forwardingSelector:(SEL)selector forClass:(Class __nonnull)class { + return [self.forwardedSelectorsByClass[CLASS_VALUE(class)] containsObject:SEL_VALUE(selector)]; +} + +-(void)registerForwardedSelector:(SEL)selector forClass:(Class __nonnull)class { + NSValue *classValue = CLASS_VALUE(class); + + NSMutableSet *forwardedSelectors = self.forwardedSelectorsByClass[classValue]; + + if (forwardedSelectors == nil) { + forwardedSelectors = [NSMutableSet set]; + self.forwardedSelectorsByClass[classValue] = forwardedSelectors; + } + + [forwardedSelectors addObject:SEL_VALUE(selector)]; +} + +-(BOOL)observeByForwardingMessages:(Class __nonnull)swizzlingImplementorClass + selector:(SEL)selector + target:(id __nonnull)target + error:(NSErrorParam)error { + if (![self ensureForwardingMethodsAreSwizzled:swizzlingImplementorClass error:error]) { + return NO; + } + + ALWAYS(![self forwardingSelector:selector forClass:swizzlingImplementorClass], @"Already observing selector for class"); + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOfForwardedMethods, 1); +#endif + SEL rxSelector = RX_selector(selector); + + Method instanceMethod = class_getInstanceMethod(swizzlingImplementorClass, selector); + ALWAYS(instanceMethod != nil, @"Instance method is nil"); + + const char* methodEncoding = method_getTypeEncoding(instanceMethod); + ALWAYS(methodEncoding != nil, @"Method encoding is nil."); + NSMethodSignature *methodSignature = [NSMethodSignature signatureWithObjCTypes:methodEncoding]; + ALWAYS(methodSignature != nil, @"Method signature is invalid."); + + IMP implementation = method_getImplementation(instanceMethod); + + if (implementation == nil) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSelectorNotImplemented + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, rxSelector, implementation, methodEncoding)) { + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed + userInfo:nil], NO); + } + + if (!class_addMethod(swizzlingImplementorClass, selector, _objc_msgForward, methodEncoding)) { + if (implementation != method_setImplementation(instanceMethod, _objc_msgForward)) { + THREADING_HAZARD(swizzlingImplementorClass); + RX_THROW_ERROR([NSError errorWithDomain:RXObjCRuntimeErrorDomain + code:RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation + userInfo:nil], NO); + } + } + + DLOG(@"Rx uses forwarding to observe `%@` for `%@`.", NSStringFromSelector(selector), swizzlingImplementorClass); + [self registerForwardedSelector:selector forClass:swizzlingImplementorClass]; + + return YES; +} + +/** + If object don't have some weird behavior, claims it's the same class that runtime shows, + then dynamic subclass is created (only this instance will have performance hit). + + In case something weird is detected, then original base class is being swizzled and all instances + will have somewhat reduced performance. + + This is especially handy optimization for weak KVO. Nobody will swizzle for example `NSString`, + but to know when instance of a `NSString` was deallocated, performance hit will be only felt on a + single instance of `NSString`, not all instances of `NSString`s. + */ +-(Class __nullable)ensureHasDynamicFakeSubclass:(Class __nonnull)class error:(NSErrorParam)error { + Class dynamicFakeSubclass = self.dynamicSubclassByRealClass[CLASS_VALUE(class)]; + if (dynamicFakeSubclass != nil) { + return dynamicFakeSubclass; + } + + NSString *dynamicFakeSubclassName = [RX_PREFIX stringByAppendingString:NSStringFromClass(class)]; + const char *dynamicFakeSubclassNameRaw = dynamicFakeSubclassName.UTF8String; + dynamicFakeSubclass = objc_allocateClassPair(class, dynamicFakeSubclassNameRaw, 0); + ALWAYS(dynamicFakeSubclass != nil, @"Class not generated"); + + if (![self swizzleClass:dynamicFakeSubclass toActAs:class error:error]) { + return nil; + } + + objc_registerClassPair(dynamicFakeSubclass); + + [self.dynamicSubclassByRealClass setObject:dynamicFakeSubclass forKey:CLASS_VALUE(class)]; + ALWAYS(self.dynamicSubclassByRealClass[CLASS_VALUE(class)] != nil, @"Class not registered"); + + return dynamicFakeSubclass; +} + +-(BOOL)ensureForwardingMethodsAreSwizzled:(Class __nonnull)class error:(NSErrorParam)error { + NSValue *classValue = CLASS_VALUE(class); + if ([self.classesThatSupportObservingByForwarding containsObject:classValue]) { + return YES; + } + + if (![self swizzleForwardInvocation:class error:error]) { return NO; } + if (![self swizzleMethodSignatureForSelector:class error:error]) { return NO; } + if (![self swizzleRespondsToSelector:class error:error]) { return NO; } + + [self.classesThatSupportObservingByForwarding addObject:classValue]; + + return YES; +} + +-(void)registerInterceptedSelector:(SEL)selector implementation:(IMP)implementation forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorsForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + if (swizzledIMPBySelectorsForClass == nil) { + swizzledIMPBySelectorsForClass = [NSMutableDictionary dictionary]; + self.interceptorIMPbySelectorsByClass[classValue] = swizzledIMPBySelectorsForClass; + } + + swizzledIMPBySelectorsForClass[selectorValue] = IMP_VALUE(implementation); + + ALWAYS([self interceptorImplementationForSelector:selector forClass:class] != nil, @"Class should have been swizzled"); +} + +-(IMP)interceptorImplementationForSelector:(SEL)selector forClass:(Class)class { + NSValue * __nonnull classValue = CLASS_VALUE(class); + NSValue * __nonnull selectorValue = SEL_VALUE(selector); + + NSMutableDictionary *swizzledIMPBySelectorForClass = self.interceptorIMPbySelectorsByClass[classValue]; + + NSValue *impValue = swizzledIMPBySelectorForClass[selectorValue]; + return impValue.pointerValue; +} + +-(BOOL)ensureSwizzledSelector:(SEL __nonnull)selector + ofClass:(Class __nonnull)class + newImplementationGenerator:(IMP(^)(void))newImplementationGenerator +replacementImplementationGenerator:(IMP (^)(IMP originalImplementation))replacementImplementationGenerator + error:(NSErrorParam)error { + if ([self interceptorImplementationForSelector:selector forClass:class] != nil) { + DLOG(@"Trying to register same intercept at least once, this sounds like a possible bug"); + return YES; + } + +#if TRACE_RESOURCES + atomic_fetch_add(&numberOInterceptedMethods, 1); +#endif + + DLOG(@"Rx is swizzling `%@` for `%@`", NSStringFromSelector(selector), class); + + Method existingMethod = class_getInstanceMethod(class, selector); + ALWAYS(existingMethod != nil, @"Method doesn't exist"); + + const char *encoding = method_getTypeEncoding(existingMethod); + ALWAYS(encoding != nil, @"Encoding is nil"); + + IMP newImplementation = newImplementationGenerator(); + + if (class_addMethod(class, selector, newImplementation, encoding)) { + // new method added, job done + [self registerInterceptedSelector:selector implementation:newImplementation forClass:class]; + + return YES; + } + + imp_removeBlock(newImplementation); + + // if add fails, that means that method already exists on targetClass + Method existingMethodOnTargetClass = existingMethod; + + IMP originalImplementation = method_getImplementation(existingMethodOnTargetClass); + ALWAYS(originalImplementation != nil, @"Method must exist."); + IMP implementationReplacementIMP = replacementImplementationGenerator(originalImplementation); + ALWAYS(implementationReplacementIMP != nil, @"Method must exist."); + IMP originalImplementationAfterChange = method_setImplementation(existingMethodOnTargetClass, implementationReplacementIMP); + ALWAYS(originalImplementation != nil, @"Method must exist."); + + // If method replacing failed, who knows what happened, better not trying again, otherwise program can get + // corrupted. + [self registerInterceptedSelector:selector implementation:implementationReplacementIMP forClass:class]; + + // ¯\_(ツ)_/¯ + if (originalImplementationAfterChange != originalImplementation) { + THREADING_HAZARD(class); + return NO; + } + + return YES; +} + +@end + +#if TRACE_RESOURCES + +NSInteger RX_number_of_dynamic_subclasses(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.dynamicSubclassByRealClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarding_enabled_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.classesThatSupportObservingByForwarding.count; + }]; + + return count; +} + +NSInteger RX_number_of_intercepting_classes(void) { + __block NSInteger count = 0; + [[RXObjCRuntime instance] performLocked:^(RXObjCRuntime * __nonnull self) { + count = self.interceptorIMPbySelectorsByClass.count; + }]; + + return count; +} + +NSInteger RX_number_of_forwarded_methods(void) { + return numberOfForwardedMethods; +} + +NSInteger RX_number_of_swizzled_methods(void) { + return numberOInterceptedMethods; +} + +#endif + +#endif diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h b/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h new file mode 100644 index 0000000..8cf762e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/RxCocoaRuntime.h @@ -0,0 +1,19 @@ +// +// RxCocoaRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import "_RX.h" +#import "_RXDelegateProxy.h" +#import "_RXKVOObserver.h" +#import "_RXObjCRuntime.h" + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h new file mode 100644 index 0000000..b868ac9 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RX.h @@ -0,0 +1,93 @@ +// +// _RX.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +#if TRACE_RESOURCES >= 2 +# define DLOG(...) NSLog(__VA_ARGS__) +#else +# define DLOG(...) +#endif + +#if DEBUG +# define ABORT_IN_DEBUG abort(); +#else +# define ABORT_IN_DEBUG +#endif + + +#define SEL_VALUE(x) [NSValue valueWithPointer:(x)] +#define CLASS_VALUE(x) [NSValue valueWithNonretainedObject:(x)] +#define IMP_VALUE(x) [NSValue valueWithPointer:(x)] + +/** + Checks that the local `error` instance exists before assigning it's value by reference. + This macro exists to work around static analysis warnings — `NSError` is always assumed to be `nullable`, even though we explicitly define the method parameter as `nonnull`. See http://www.openradar.me/21766176 for more details. + */ +#define RX_THROW_ERROR(errorValue, returnValue) if (error != nil) { *error = (errorValue); } return (returnValue); + +#define RX_CAT2(_1, _2) _RX_CAT2(_1, _2) +#define _RX_CAT2(_1, _2) _1 ## _2 + +#define RX_ELEMENT_AT(n, ...) RX_CAT2(_RX_ELEMENT_AT_, n)(__VA_ARGS__) +#define _RX_ELEMENT_AT_0(x, ...) x +#define _RX_ELEMENT_AT_1(_0, x, ...) x +#define _RX_ELEMENT_AT_2(_0, _1, x, ...) x +#define _RX_ELEMENT_AT_3(_0, _1, _2, x, ...) x +#define _RX_ELEMENT_AT_4(_0, _1, _2, _3, x, ...) x +#define _RX_ELEMENT_AT_5(_0, _1, _2, _3, _4, x, ...) x +#define _RX_ELEMENT_AT_6(_0, _1, _2, _3, _4, _5, x, ...) x + +#define RX_COUNT(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 6, 5, 4, 3, 2, 1, 0) +#define RX_EMPTY(...) RX_ELEMENT_AT(6, ## __VA_ARGS__, 0, 0, 0, 0, 0, 0, 1) + +/** + #define SUM(context, index, head, tail) head + tail + #define MAP(context, index, element) (context)[index] * (element) + + RX_FOR(numbers, SUM, MAP, b0, b1, b2); + + (numbers)[0] * (b0) + (numbers)[1] * (b1) + (numbers[2]) * (b2) + */ + +#define RX_FOREACH(context, concat, map, ...) RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_CONCAT, _RX_FOREACH_MAP, context, concat, map, __VA_ARGS__) +#define _RX_FOREACH_CONCAT(index, head, tail, context, concat, map, ...) concat(context, index, head, tail) +#define _RX_FOREACH_MAP(index, context, concat, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +/** + #define MAP(context, index, item) (context)[index] * (item) + + RX_FOR_COMMA(numbers, MAP, b0, b1); + + ,(numbers)[0] * b0, (numbers)[1] * b1 + */ +#define RX_FOREACH_COMMA(context, map, ...) RX_CAT2(_RX_FOREACH_COMMA_EMPTY_, RX_EMPTY(__VA_ARGS__))(context, map, ## __VA_ARGS__) +#define _RX_FOREACH_COMMA_EMPTY_1(context, map, ...) +#define _RX_FOREACH_COMMA_EMPTY_0(context, map, ...) , RX_FOR_MAX(RX_COUNT(__VA_ARGS__), _RX_FOREACH_COMMA_CONCAT, _RX_FOREACH_COMMA_MAP, context, map, __VA_ARGS__) +#define _RX_FOREACH_COMMA_CONCAT(index, head, tail, context, map, ...) head, tail +#define _RX_FOREACH_COMMA_MAP(index, context, map, ...) map(context, index, RX_ELEMENT_AT(index, __VA_ARGS__)) + +// rx for + +#define RX_FOR_MAX(max, concat, map, ...) RX_CAT2(RX_FOR_, max)(concat, map, ## __VA_ARGS__) + +#define RX_FOR_0(concat, map, ...) +#define RX_FOR_1(concat, map, ...) map(0, __VA_ARGS__) +#define RX_FOR_2(concat, map, ...) concat(1, RX_FOR_1(concat, map, ## __VA_ARGS__), map(1, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_3(concat, map, ...) concat(2, RX_FOR_2(concat, map, ## __VA_ARGS__), map(2, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_4(concat, map, ...) concat(3, RX_FOR_3(concat, map, ## __VA_ARGS__), map(3, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_5(concat, map, ...) concat(4, RX_FOR_4(concat, map, ## __VA_ARGS__), map(4, __VA_ARGS__), __VA_ARGS__) +#define RX_FOR_6(concat, map, ...) concat(5, RX_FOR_5(concat, map, ## __VA_ARGS__), map(5, __VA_ARGS__), __VA_ARGS__) + diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h new file mode 100644 index 0000000..e1cc207 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXDelegateProxy.h @@ -0,0 +1,27 @@ +// +// _RXDelegateProxy.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface _RXDelegateProxy : NSObject + +@property (nonatomic, weak, readonly) id _forwardToDelegate; + +-(void)_setForwardToDelegate:(id __nullable)forwardToDelegate retainDelegate:(BOOL)retainDelegate NS_SWIFT_NAME(_setForwardToDelegate(_:retainDelegate:)) ; + +-(BOOL)hasWiredImplementationForSelector:(SEL)selector; +-(BOOL)voidDelegateMethodsContain:(SEL)selector; + +-(void)_sentMessage:(SEL)selector withArguments:(NSArray*)arguments; +-(void)_methodInvoked:(SEL)selector withArguments:(NSArray*)arguments; + +@end + +NS_ASSUME_NONNULL_END diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h new file mode 100644 index 0000000..adcfd0a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXKVOObserver.h @@ -0,0 +1,28 @@ +// +// _RXKVOObserver.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +// Exists because if written in Swift, reading unowned is disabled during dealloc process +@interface _RXKVOObserver : NSObject + +-(instancetype)initWithTarget:(id)target + retainTarget:(BOOL)retainTarget + keyPath:(NSString*)keyPath + options:(NSKeyValueObservingOptions)options + callback:(void (^)(id))callback; + +-(void)dispose; + +@end diff --git a/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h new file mode 100644 index 0000000..bc6a76a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Runtime/include/_RXObjCRuntime.h @@ -0,0 +1,102 @@ +// +// _RXObjCRuntime.h +// RxCocoa +// +// Created by Krunoslav Zaher on 7/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import + +#if !DISABLE_SWIZZLING + +/** + ################################################################################ + This file is part of RX private API + ################################################################################ + */ + +/** + This flag controls `RELEASE` configuration behavior in case race was detecting while modifying + ObjC runtime. + + In case this value is set to `YES`, after runtime race is detected, `abort()` will be called. + Otherwise, only error will be reported using normal error reporting mechanism. + + In `DEBUG` mode `abort` will be always called in case race is detected. + + Races can't happen in case this is the only library modifying ObjC runtime, but in case there are multiple libraries + changing ObjC runtime, race conditions can occur because there is no way to synchronize multiple libraries unaware of + each other. + + To help remedy this situation this library will use `synchronized` on target object and it's meta-class, but + there aren't any guarantees of how other libraries will behave. + + Default value is `NO`. + + */ +extern BOOL RXAbortOnThreadingHazard; + +/// Error domain for RXObjCRuntime. +extern NSString * __nonnull const RXObjCRuntimeErrorDomain; + +/// `userInfo` key with additional information is interceptor probably KVO. +extern NSString * __nonnull const RXObjCRuntimeErrorIsKVOKey; + +typedef NS_ENUM(NSInteger, RXObjCRuntimeError) { + RXObjCRuntimeErrorUnknown = 1, + RXObjCRuntimeErrorObjectMessagesAlreadyBeingIntercepted = 2, + RXObjCRuntimeErrorSelectorNotImplemented = 3, + RXObjCRuntimeErrorCantInterceptCoreFoundationTollFreeBridgedObjects = 4, + RXObjCRuntimeErrorThreadingCollisionWithOtherInterceptionMechanism = 5, + RXObjCRuntimeErrorSavingOriginalForwardingMethodFailed = 6, + RXObjCRuntimeErrorReplacingMethodWithForwardingImplementation = 7, + RXObjCRuntimeErrorObservingPerformanceSensitiveMessages = 8, + RXObjCRuntimeErrorObservingMessagesWithUnsupportedReturnType = 9, +}; + +/// Transforms normal selector into a selector with RX prefix. +SEL _Nonnull RX_selector(SEL _Nonnull selector); + +/// Transforms selector into a unique pointer (because of Swift conversion rules) +void * __nonnull RX_reference_from_selector(SEL __nonnull selector); + +/// Protocol that interception observers must implement. +@protocol RXMessageSentObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)messageSentWithArguments:(NSArray* __nonnull)arguments; +-(void)methodInvokedWithArguments:(NSArray* __nonnull)arguments; + +@end + +/// Protocol that deallocating observer must implement. +@protocol RXDeallocatingObserver + +/// In case the same selector is being intercepted for a pair of base/sub classes, +/// this property will differentiate between interceptors that need to fire. +@property (nonatomic, assign, readonly) IMP __nonnull targetImplementation; + +-(void)deallocating; + +@end + +/// Ensures interceptor is installed on target object. +IMP __nullable RX_ensure_observing(id __nonnull target, SEL __nonnull selector, NSError *__autoreleasing __nullable * __nullable error); + +#endif + +/// Extracts arguments for `invocation`. +NSArray * __nonnull RX_extract_arguments(NSInvocation * __nonnull invocation); + +/// Returns `YES` in case method has `void` return type. +BOOL RX_is_method_with_description_void(struct objc_method_description method); + +/// Returns `YES` in case methodSignature has `void` return type. +BOOL RX_is_method_signature_void(NSMethodSignature * __nonnull methodSignature); + +/// Default value for `RXInterceptionObserver.targetImplementation`. +IMP __nonnull RX_default_target_implementation(void); diff --git a/Pods/RxCocoa/RxCocoa/RxCocoa.h b/Pods/RxCocoa/RxCocoa/RxCocoa.h new file mode 100644 index 0000000..0bca1bc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/RxCocoa.h @@ -0,0 +1,19 @@ +// +// RxCocoa.h +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#import +#import +#import +#import +#import + +//! Project version number for RxCocoa. +FOUNDATION_EXPORT double RxCocoaVersionNumber; + +//! Project version string for RxCocoa. +FOUNDATION_EXPORT const unsigned char RxCocoaVersionString[]; diff --git a/Pods/RxCocoa/RxCocoa/RxCocoa.swift b/Pods/RxCocoa/RxCocoa/RxCocoa.swift new file mode 100644 index 0000000..5e569fc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/RxCocoa.swift @@ -0,0 +1,155 @@ +// +// RxCocoa.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +// Importing RxCocoa also imports RxRelay +@_exported import RxRelay + +import RxSwift +#if os(iOS) + import UIKit +#endif + +/// RxCocoa errors. +public enum RxCocoaError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error has occurred. + case unknown + /// Invalid operation was attempted. + case invalidOperation(object: Any) + /// Items are not yet bound to user interface but have been requested. + case itemsNotYetBound(object: Any) + /// Invalid KVO Path. + case invalidPropertyName(object: Any, propertyName: String) + /// Invalid object on key path. + case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String) + /// Error during swizzling. + case errorDuringSwizzling + /// Casting error. + case castingError(object: Any, targetType: Any.Type) +} + + +// MARK: Debug descriptions + +extension RxCocoaError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case let .invalidOperation(object): + return "Invalid operation was attempted on `\(object)`." + case let .itemsNotYetBound(object): + return "Data source is set, but items are not yet bound to user interface for `\(object)`." + case let .invalidPropertyName(object, propertyName): + return "Object `\(object)` doesn't have a property named `\(propertyName)`." + case let .invalidObjectOnKeyPath(object, sourceObject, propertyName): + return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`." + case .errorDuringSwizzling: + return "Error during swizzling." + case let .castingError(object, targetType): + return "Error casting `\(object)` to `\(targetType)`" + } + } +} + + + +// MARK: Error binding policies + +func bindingError(_ error: Swift.Error) { + let error = "Binding error: \(error)" +#if DEBUG + rxFatalError(error) +#else + print(error) +#endif +} + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError(message, file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +// MARK: casts or fatal error + +// workaround for Swift compiler bug, cheers compiler team :) +func castOptionalOrFatalError(_ value: Any?) -> T? { + if value == nil { + return nil + } + let v: T = castOrFatalError(value) + return v +} + +func castOrThrow(_ resultType: T.Type, _ object: Any) throws -> T { + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOptionalOrThrow(_ resultType: T.Type, _ object: AnyObject) throws -> T? { + if NSNull().isEqual(object) { + return nil + } + + guard let returnValue = object as? T else { + throw RxCocoaError.castingError(object: object, targetType: resultType) + } + + return returnValue +} + +func castOrFatalError(_ value: AnyObject!, message: String) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError(message) + } + + return result +} + +func castOrFatalError(_ value: Any!) -> T { + let maybeResult: T? = value as? T + guard let result = maybeResult else { + rxFatalError("Failure converting from \(String(describing: value)) to \(T.self)") + } + + return result +} + +// MARK: Error messages + +let dataSourceNotSet = "DataSource not set" +let delegateNotSet = "Delegate not set" + +// MARK: Shared with RxSwift + +func rxFatalError(_ lastMessage: String) -> Never { + // The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours. + fatalError(lastMessage) +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift b/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift new file mode 100644 index 0000000..bea1d83 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/ControlEvent.swift @@ -0,0 +1,68 @@ +// +// ControlEvent.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// A protocol that extends `ControlEvent`. +public protocol ControlEventType : ObservableType { + + /// - returns: `ControlEvent` interface + func asControlEvent() -> ControlEvent +} + +/** + A trait for `Observable`/`ObservableType` that represents an event on a UI element. + + Properties: + + - it doesn’t send any initial value on subscription, + - it `Complete`s the sequence when the control deallocates, + - it never errors out + - it delivers events on `MainScheduler.instance`. + + **The implementation of `ControlEvent` will ensure that sequence of events is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is the implementor’s responsibility to make sure that all other properties enumerated above are satisfied.** + + **If they aren’t, using this trait will communicate wrong properties, and could potentially break someone’s code.** + + **If the `events` observable sequence passed into the initializer doesn’t satisfy all enumerated + properties, don’t use this trait.** +*/ +public struct ControlEvent : ControlEventType { + public typealias Element = PropertyType + + let events: Observable + + /// Initializes control event with a observable sequence that represents events. + /// + /// - parameter events: Observable sequence that represents events. + /// - returns: Control event created with a observable sequence of events. + public init(events: Ev) where Ev.Element == Element { + self.events = events.subscribe(on: ConcurrentMainScheduler.instance) + } + + /// Subscribes an observer to control events. + /// + /// - parameter observer: Observer to subscribe to events. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control events. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.events.subscribe(observer) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.events + } + + /// - returns: `ControlEvent` interface. + public func asControlEvent() -> ControlEvent { + self + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift b/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift new file mode 100644 index 0000000..3068afb --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/ControlProperty.swift @@ -0,0 +1,118 @@ +// +// ControlProperty.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// Protocol that enables extension of `ControlProperty`. +public protocol ControlPropertyType : ObservableType, ObserverType { + + /// - returns: `ControlProperty` interface + func asControlProperty() -> ControlProperty +} + +/** + Trait for `Observable`/`ObservableType` that represents property of UI element. + + Sequence of values only represents initial control value and user initiated value changes. + Programmatic value changes won't be reported. + + It's properties are: + + - `shareReplay(1)` behavior + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - it will `Complete` sequence on control being deallocated + - it never errors out + - it delivers events on `MainScheduler.instance` + + **The implementation of `ControlProperty` will ensure that sequence of values is being subscribed on main scheduler + (`subscribe(on: ConcurrentMainScheduler.instance)` behavior).** + + **It is implementor's responsibility to make sure that that all other properties enumerated above are satisfied.** + + **If they aren't, then using this trait communicates wrong properties and could potentially break someone's code.** + + **In case `values` observable sequence that is being passed into initializer doesn't satisfy all enumerated + properties, please don't use this trait.** +*/ +public struct ControlProperty : ControlPropertyType { + public typealias Element = PropertyType + + let values: Observable + let valueSink: AnyObserver + + /// Initializes control property with a observable sequence that represents property values and observer that enables + /// binding values to property. + /// + /// - parameter values: Observable sequence that represents property values. + /// - parameter valueSink: Observer that enables binding values to control property. + /// - returns: Control property created with a observable sequence of values and an observer that enables binding values + /// to property. + public init(values: Values, valueSink: Sink) where Element == Values.Element, Element == Sink.Element { + self.values = values.subscribe(on: ConcurrentMainScheduler.instance) + self.valueSink = valueSink.asObserver() + } + + /// Subscribes an observer to control property values. + /// + /// - parameter observer: Observer to subscribe to property values. + /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.values.subscribe(observer) + } + + /// `ControlEvent` of user initiated value changes. Every time user updates control value change event + /// will be emitted from `changed` event. + /// + /// Programmatic changes to control value won't be reported. + /// + /// It contains all control property values except for first one. + /// + /// The name only implies that sequence element will be generated once user changes a value and not that + /// adjacent sequence values need to be different (e.g. because of interaction between programmatic and user updates, + /// or for any other reason). + public var changed: ControlEvent { + ControlEvent(events: self.values.skip(1)) + } + + /// - returns: `Observable` interface. + public func asObservable() -> Observable { + self.values + } + + /// - returns: `ControlProperty` interface. + public func asControlProperty() -> ControlProperty { + self + } + + /// Binds event to user interface. + /// + /// - In case next element is received, it is being set to control value. + /// - In case error is received, DEBUG buids raise fatal error, RELEASE builds log event to standard output. + /// - In case sequence completes, nothing happens. + public func on(_ event: Event) { + switch event { + case .error(let error): + bindingError(error) + case .next: + self.valueSink.on(event) + case .completed: + self.valueSink.on(event) + } + } +} + +extension ControlPropertyType where Element == String? { + /// Transforms control property of type `String?` into control property of type `String`. + public var orEmpty: ControlProperty { + let original: ControlProperty = self.asControlProperty() + + let values: Observable = original.values.map { $0 ?? "" } + let valueSink: AnyObserver = original.valueSink.mapObserver { $0 } + return ControlProperty(values: values, valueSink: valueSink) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift new file mode 100644 index 0000000..76d960f --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/BehaviorRelay+Driver.swift @@ -0,0 +1,21 @@ +// +// BehaviorRelay+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension BehaviorRelay { + /// Converts `BehaviorRelay` to `Driver`. + /// + /// - returns: Observable sequence. + public func asDriver() -> Driver { + let source = self.asObservable() + .observe(on:DriverSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift new file mode 100644 index 0000000..b59c753 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlEvent+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlEvent+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Driver` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift new file mode 100644 index 0000000..7904529 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ControlProperty+Driver.swift @@ -0,0 +1,24 @@ +// +// ControlProperty+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlProperty { + /// Converts `ControlProperty` to `Driver` trait. + /// + /// `ControlProperty` already can't fail, so no special case needs to be handled. + public func asDriver() -> Driver { + return self.asDriver { _ -> Driver in + #if DEBUG + rxFatalError("Somehow driver received error from a source that shouldn't fail.") + #else + return Driver.empty() + #endif + } + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift new file mode 100644 index 0000000..da9659c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver+Subscription.swift @@ -0,0 +1,203 @@ +// +// Driver+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +private let errorMessage = "`drive*` family of methods can be only called from `MainThread`.\n" + +"This is required to ensure that the last replayed `Driver` element is delivered on `MainThread`.\n" + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to observer. + This method can be only called from `MainThread`. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter observers: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func drive(_ observers: Observer...) -> Disposable where Observer.Element == Element? { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { e in + observers.forEach { $0.on(e) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: BehaviorRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + This method can be only called from `MainThread`. + + - parameter relays: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func drive(_ relays: ReplayRelay...) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.drive(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes to observable sequence using custom binder function. + This method can be only called from `MainThread`. + + - parameter with: Function used to bind elements from `self`. + - returns: Object representing subscription. + */ + public func drive(_ transformation: (Observable) -> Result) -> Result { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return transformation(self.asObservable()) + } + + /** + Subscribes to observable sequence using custom binder function and final parameter passed to binder function + after `self` is passed. + + public func drive(with: Self -> R1 -> R2, curriedArgument: R1) -> R2 { + return with(self)(curriedArgument) + } + + This method can be only called from `MainThread`. + + - parameter with: Function used to bind elements from `self`. + - parameter curriedArgument: Final argument passed to `binder` to finish binding process. + - returns: Object representing subscription. + */ + public func drive(_ with: (Observable) -> (R1) -> R2, curriedArgument: R1) -> R2 { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return with(self.asObservable())(curriedArgument) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Driver` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(with: object, onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + This method can be only called from `MainThread`. + + Error callback is not exposed because `Driver` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + MainScheduler.ensureRunningOnMainThread(errorMessage: errorMessage) + return self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Driver` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `drive(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func drive() -> Disposable { + drive(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} + + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift new file mode 100644 index 0000000..5de8b3a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/Driver.swift @@ -0,0 +1,53 @@ +// +// Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(replay: 1, scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - it's stateful, upon subscription (calling subscribe) last element is immediately replayed if it was produced + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models event bus is required, please check `Signal`. + + `Driver` can be considered a builder pattern for observable sequences that drive the application. + + If observable sequence has produced at least one element, after new subscription is made last produced element will be + immediately replayed on the same thread on which the subscription was made. + + When using `drive*`, `subscribe*` and `bind*` family of methods, they should always be called from main thread. + + If `drive*`, `subscribe*` and `bind*` are called from background thread, it is possible that initial replay + will happen on background thread, and subsequent events will arrive on main thread. + + To find out more about traits and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Driver = SharedSequence + +public struct DriverSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + public static func share(_ source: Observable) -> Observable { + source.share(replay: 1, scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + /// Adds `asDriver` to `SharingSequence` with `DriverSharingStrategy`. + public func asDriver() -> Driver { + self.asSharedSequence() + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift b/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift new file mode 100644 index 0000000..bcac66b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Driver/ObservableConvertibleType+Driver.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Driver.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driver trait. + */ + public func asDriver(onErrorJustReturn: Element) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorDriveWith: Driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorDriveWith: Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return Driver(source) + } + + /** + Converts observable sequence to `Driver` trait. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driver trait. + */ + public func asDriver(onErrorRecover: @escaping (_ error: Swift.Error) -> Driver) -> Driver { + let source = self + .asObservable() + .observe(on:DriverSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Driver(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift new file mode 100644 index 0000000..20ddf86 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/ObservableConvertibleType+SharedSequence.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorJustReturn: Element) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catchAndReturn(onErrorJustReturn) + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorDriveWith: SharedSequence that provides elements of the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorDriveWith: SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { _ in + onErrorDriveWith.asObservable() + } + return SharedSequence(source) + } + + /** + Converts anything convertible to `Observable` to `SharedSequence` unit. + + - parameter onErrorRecover: Calculates driver that continues to drive the sequence in case of error. + - returns: Driving observable sequence. + */ + public func asSharedSequence(sharingStrategy: S.Type = S.self, onErrorRecover: @escaping (_ error: Swift.Error) -> SharedSequence) -> SharedSequence { + let source = self + .asObservable() + .observe(on:S.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift new file mode 100644 index 0000000..5111e06 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SchedulerType+SharedSequence.swift @@ -0,0 +1,62 @@ +// +// SchedulerType+SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +public enum SharingScheduler { + /// Default scheduler used in SharedSequence based traits. + public private(set) static var make: () -> SchedulerType = { MainScheduler() } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(scheduler: SchedulerType, action: () throws -> Void) rethrows { + return try mock(makeScheduler: { scheduler }, action: action) + } + + /** + This method can be used in unit tests to ensure that built in shared sequences are using mock schedulers instead + of main schedulers. + + **This shouldn't be used in normal release builds.** + */ + static public func mock(makeScheduler: @escaping () -> SchedulerType, action: () throws -> Void) rethrows { + let originalMake = make + make = makeScheduler + defer { + make = originalMake + } + + try action() + + // If you remove this line , compiler buggy optimizations will change behavior of this code + _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(makeScheduler) + // Scary, I know + } +} + +#if os(Linux) + import Glibc +#else + import Foundation +#endif + +func _forceCompilerToStopDoingInsaneOptimizationsThatBreakCode(_ scheduler: () -> SchedulerType) { + let a: Int32 = 1 +#if os(Linux) + let b = 314 + Int32(Glibc.random() & 1) +#else + let b = 314 + Int32(arc4random() & 1) +#endif + if a == b { + print(scheduler()) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift new file mode 100644 index 0000000..4cc967c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators+arity.swift @@ -0,0 +1,656 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// SharedSequence+Operators+arity.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 10/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + + + +// 2 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 3 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 4 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 5 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 6 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 7 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + + +// 8 + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.zip( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable(), + resultSelector: resultSelector + ) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of element tuples whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> SharedSequence where SharingStrategy == O1.SharingStrategy, + SharingStrategy == O2.SharingStrategy, + SharingStrategy == O3.SharingStrategy, + SharingStrategy == O4.SharingStrategy, + SharingStrategy == O5.SharingStrategy, + SharingStrategy == O6.SharingStrategy, + SharingStrategy == O7.SharingStrategy, + SharingStrategy == O8.SharingStrategy { + let source = Observable.combineLatest( + source1.asSharedSequence().asObservable(), source2.asSharedSequence().asObservable(), source3.asSharedSequence().asObservable(), source4.asSharedSequence().asObservable(), source5.asSharedSequence().asObservable(), source6.asSharedSequence().asObservable(), source7.asSharedSequence().asObservable(), source8.asSharedSequence().asObservable() + ) + + return SharedSequence(source) + } +} + + diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift new file mode 100644 index 0000000..45383ef --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence+Operators.swift @@ -0,0 +1,585 @@ +// +// SharedSequence+Operators.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +// MARK: map +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into a new form. + + - parameter selector: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + */ + public func map(_ selector: @escaping (Element) -> Result) -> SharedSequence { + let source = self + .asObservable() + .map(selector) + return SharedSequence(source) + } +} + +// MARK: compactMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter transform: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ selector: @escaping (Element) -> Result?) -> SharedSequence { + let source = self + .asObservable() + .compactMap(selector) + return SharedSequence(source) + } +} + +// MARK: filter +extension SharedSequenceConvertibleType { + /** + Filters the elements of an observable sequence based on a predicate. + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) -> Bool) -> SharedSequence { + let source = self + .asObservable() + .filter(predicate) + return SharedSequence(source) + } +} + +// MARK: switchLatest +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> SharedSequence { + let source: Observable = self + .asObservable() + .map { $0.asSharedSequence() } + .switchLatest() + return SharedSequence(source) + } +} + +// MARK: flatMapLatest +extension SharedSequenceConvertibleType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapLatest(selector) + return SharedSequence(source) + } +} + +// MARK: flatMapFirst +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) -> SharedSequence) + -> SharedSequence { + let source: Observable = self + .asObservable() + .flatMapFirst(selector) + return SharedSequence(source) + } +} + +// MARK: do +extension SharedSequenceConvertibleType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) -> Void)? = nil, afterNext: ((Element) -> Void)? = nil, onCompleted: (() -> Void)? = nil, afterCompleted: (() -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> SharedSequence { + let source = self.asObservable() + .do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + + return SharedSequence(source) + } +} + +// MARK: debug +extension SharedSequenceConvertibleType { + + /** + Prints received events for all observers on standard output. + + - parameter identifier: Identifier that is printed together with event description to standard output. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) -> SharedSequence { + let source = self.asObservable() + .debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function) + return SharedSequence(source) + } +} + +// MARK: distinctUntilChanged +extension SharedSequenceConvertibleType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + + return SharedSequence(source) + } +} + +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> Key) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged({ $0 }, comparer: comparer) + return SharedSequence(source) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) -> K, comparer: @escaping (K, K) -> Bool) -> SharedSequence { + let source = self.asObservable() + .distinctUntilChanged(keySelector, comparer: comparer) + return SharedSequence(source) + } +} + + +// MARK: flatMap +extension SharedSequenceConvertibleType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) -> SharedSequence) -> SharedSequence { + let source = self.asObservable() + .flatMap(selector) + + return SharedSequence(source) + } +} + +// MARK: merge +extension SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [SharedSequence]) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: SharedSequence...) -> SharedSequence { + let source = Observable.merge(sources.map { $0.asObservable() }) + return SharedSequence(source) + } + +} + +// MARK: merge +extension SharedSequenceConvertibleType where Element: SharedSequenceConvertibleType { + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge() + return SharedSequence(source) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> SharedSequence { + let source = self.asObservable() + .map { $0.asSharedSequence() } + .merge(maxConcurrent: maxConcurrent) + return SharedSequence(source) + } +} + +// MARK: throttle +extension SharedSequenceConvertibleType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true) + -> SharedSequence { + let source = self.asObservable() + .throttle(dueTime, latest: latest, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - parameter dueTime: Throttling duration for each element. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .debounce(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} + +// MARK: scan +extension SharedSequenceConvertibleType { + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) -> A) + -> SharedSequence { + let source = self.asObservable() + .scan(seed, accumulator: accumulator) + return SharedSequence(source) + } +} + +// MARK: concat + +extension SharedSequence { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> SharedSequence + where Sequence.Element == SharedSequence { + let source = Observable.concat(sequence.lazy.map { $0.asObservable() }) + return SharedSequence(source) + } + + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.concat(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: zip + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence all of the observable sequences have produced an element at a corresponding index. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.zip(collection.map { $0.asSharedSequence().asObservable() }) + return SharedSequence(source) + } +} + +// MARK: combineLatest + +extension SharedSequence { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Element]) throws -> Result) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }, resultSelector: resultSelector) + return SharedSequence(source) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> SharedSequence + where Collection.Element == SharedSequence { + let source = Observable.combineLatest(collection.map { $0.asObservable() }) + return SharedSequence(source) + } +} + +// MARK: - withUnretained +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the seqeunce will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the seqeunce will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> SharedSequence { + withUnretained(obj) { ($0, $1) } + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == DriverSharingStrategy { + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj, resultSelector: resultSelector)) + } + + @available(*, message: "withUnretained has been deprecated for Driver. Consider using `drive(with:onNext:onCompleted:onDisposed:)`, instead", unavailable) + public func withUnretained(_ obj: Object) -> SharedSequence { + SharedSequence(self.asObservable().withUnretained(obj) { ($0, $1) }) + } +} + +// MARK: withLatestFrom +extension SharedSequenceConvertibleType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO, resultSelector: @escaping (Element, SecondO.Element) -> ResultType) -> SharedSequence where SecondO.SharingStrategy == SharingStrategy { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence(), resultSelector: resultSelector) + + return SharedSequence(source) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: SecondO) -> SharedSequence { + let source = self.asObservable() + .withLatestFrom(second.asSharedSequence()) + + return SharedSequence(source) + } +} + +// MARK: skip +extension SharedSequenceConvertibleType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> SharedSequence { + let source = self.asObservable() + .skip(count) + return SharedSequence(source) + } +} + +// MARK: startWith +extension SharedSequenceConvertibleType { + + /** + Prepends a value to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter element: Element to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ element: Element) + -> SharedSequence { + let source = self.asObservable() + .startWith(element) + + return SharedSequence(source) + } +} + +// MARK: delay +extension SharedSequenceConvertibleType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval) + -> SharedSequence { + let source = self.asObservable() + .delay(dueTime, scheduler: SharingStrategy.scheduler) + + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift new file mode 100644 index 0000000..4db2ee4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift @@ -0,0 +1,226 @@ +// +// SharedSequence.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 8/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence that shares computation resources with following properties: + + - it never fails + - it delivers events on `SharingStrategy.scheduler` + - sharing strategy is customizable using `SharingStrategy.share` behavior + + `SharedSequence` can be considered a builder pattern for observable sequences that share computation resources. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. +*/ +public struct SharedSequence : SharedSequenceConvertibleType, ObservableConvertibleType { + let source: Observable + + init(_ source: Observable) { + self.source = SharingStrategy.share(source) + } + + init(raw: Observable) { + self.source = raw + } + + #if EXPANDABLE_SHARED_SEQUENCE + /** + This method is extension hook in case this unit needs to extended from outside the library. + + By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to them to ensure shared sequence + properties are preserved after extension. + */ + public static func createUnsafe(source: Source) -> SharedSequence { + SharedSequence(raw: source.asObservable()) + } + #endif + + /** + - returns: Built observable sequence. + */ + public func asObservable() -> Observable { + self.source + } + + /** + - returns: `self` + */ + public func asSharedSequence() -> SharedSequence { + self + } +} + +/** + Different `SharedSequence` sharing strategies must conform to this protocol. + */ +public protocol SharingStrategyProtocol { + /** + Scheduled on which all sequence events will be delivered. + */ + static var scheduler: SchedulerType { get } + + /** + Computation resources sharing strategy for multiple sequence observers. + + E.g. One can choose `share(replay:scope:)` + as sequence event sharing strategies, but also do something more exotic, like + implementing promises or lazy loading chains. + */ + static func share(_ source: Observable) -> Observable +} + +/** +A type that can be converted to `SharedSequence`. +*/ +public protocol SharedSequenceConvertibleType : ObservableConvertibleType { + associatedtype SharingStrategy: SharingStrategyProtocol + + /** + Converts self to `SharedSequence`. + */ + func asSharedSequence() -> SharedSequence +} + +extension SharedSequenceConvertibleType { + public func asObservable() -> Observable { + self.asSharedSequence().asObservable() + } +} + + +extension SharedSequence { + + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - returns: An observable sequence with no elements. + */ + public static func empty() -> SharedSequence { + SharedSequence(raw: Observable.empty().subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> SharedSequence { + SharedSequence(raw: Observable.never()) + } + + /** + Returns an observable sequence that contains a single element. + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> SharedSequence { + SharedSequence(raw: Observable.just(element).subscribe(on: SharingStrategy.scheduler)) + } + + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () -> SharedSequence) + -> SharedSequence { + SharedSequence(Observable.deferred { observableFactory().asObservable() }) + } + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ...) -> SharedSequence { + let source = Observable.from(elements, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence { + + /** + This method converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element]) -> SharedSequence { + let source = Observable.from(array, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence) -> SharedSequence where Sequence.Element == Element { + let source = Observable.from(sequence, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } + + /** + This method converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> SharedSequence { + let source = Observable.from(optional: optional, scheduler: SharingStrategy.scheduler) + return SharedSequence(raw: source) + } +} + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.interval(period, scheduler: SharingStrategy.scheduler)) + } +} + +// MARK: timer + +extension SharedSequence where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) + -> SharedSequence { + SharedSequence(Observable.timer(dueTime, period: period, scheduler: SharingStrategy.scheduler)) + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift new file mode 100644 index 0000000..bec4723 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/ControlEvent+Signal.swift @@ -0,0 +1,25 @@ +// +// ControlEvent+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 11/1/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ControlEvent { + /// Converts `ControlEvent` to `Signal` trait. + /// + /// `ControlEvent` already can't fail, so no special case needs to be handled. + public func asSignal() -> Signal { + return self.asSignal { _ -> Signal in + #if DEBUG + rxFatalError("Somehow signal received error from a source that shouldn't fail.") + #else + return Signal.empty() + #endif + } + } +} + diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift new file mode 100644 index 0000000..b962d4e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/ObservableConvertibleType+Signal.swift @@ -0,0 +1,57 @@ +// +// ObservableConvertibleType+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableConvertibleType { + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorJustReturn: Element to return in case of error and after that complete the sequence. + - returns: Signal trait. + */ + public func asSignal(onErrorJustReturn: Element) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catchAndReturn(onErrorJustReturn) + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorSignalWith: Signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorSignalWith: Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { _ in + onErrorSignalWith.asObservable() + } + return Signal(source) + } + + /** + Converts observable sequence to `Signal` trait. + + - parameter onErrorRecover: Calculates signal that continues to emit the sequence in case of error. + - returns: Signal trait. + */ + public func asSignal(onErrorRecover: @escaping (_ error: Swift.Error) -> Signal) -> Signal { + let source = self + .asObservable() + .observe(on: SignalSharingStrategy.scheduler) + .catch { error in + onErrorRecover(error).asObservable() + } + return Signal(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift new file mode 100644 index 0000000..79b975d --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/PublishRelay+Signal.swift @@ -0,0 +1,21 @@ +// +// PublishRelay+Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension PublishRelay { + /// Converts `PublishRelay` to `Signal`. + /// + /// - returns: Observable sequence. + public func asSignal() -> Signal { + let source = self.asObservable() + .observe(on:SignalSharingStrategy.scheduler) + return SharedSequence(source) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift new file mode 100644 index 0000000..ce3f94b --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal+Subscription.swift @@ -0,0 +1,178 @@ +// +// Signal+Subscription.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import RxSwift +import RxRelay + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter to: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element { + return self.asSharedSequence() + .asObservable() + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to observer. + + In this form it's equivalent to `subscribe` method, but it communicates intent better. + + - parameter to: Observers that receives events. + - returns: Disposable object that can be used to unsubscribe the observer from the subject. + */ + public func emit(to observers: Observer...) -> Disposable where Observer.Element == Element? { + return self.asSharedSequence() + .asObservable() + .map { $0 as Element? } + .subscribe { event in + observers.forEach { $0.on(event) } + } + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter to: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `BehaviorRelay`. + - parameter to: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: BehaviorRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter to: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `PublishRelay`. + + - parameter to: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: PublishRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter to: Target relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Creates new subscription and sends elements to `ReplayRelay`. + + - parameter to: Target relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer from the relay. + */ + public func emit(to relays: ReplayRelay...) -> Disposable { + return self.emit(onNext: { e in + relays.forEach { $0.accept(e) } + }) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + Error callback is not exposed because `Signal` can't error out. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe( + with: object, + onNext: onNext, + onCompleted: onCompleted, + onDisposed: onDisposed + ) + } + + /** + Subscribes an element handler, a completion handler and disposed handler to an observable sequence. + + Error callback is not exposed because `Signal` can't error out. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription) + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit( + onNext: ((Element) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + self.asObservable().subscribe(onNext: onNext, onCompleted: onCompleted, onDisposed: onDisposed) + } + + /** + Subscribes to this `Signal` with a no-op. + This method can be only called from `MainThread`. + + - note: This is an alias of `emit(onNext: nil, onCompleted: nil, onDisposed: nil)` used to fix an ambiguity bug in Swift: https://bugs.swift.org/browse/SR-13657 + + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func emit() -> Disposable { + emit(onNext: nil, onCompleted: nil, onDisposed: nil) + } +} diff --git a/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift new file mode 100644 index 0000000..e066b7e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/Traits/Signal/Signal.swift @@ -0,0 +1,45 @@ +// +// Signal.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 9/26/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/** + Trait that represents observable sequence with following properties: + + - it never fails + - it delivers events on `MainScheduler.instance` + - `share(scope: .whileConnected)` sharing strategy + + Additional explanation: + - all observers share sequence computation resources + - there is no replaying of sequence elements on new observer subscription + - computation of elements is reference counted with respect to the number of observers + - if there are no subscribers, it will release sequence computation resources + + In case trait that models state propagation is required, please check `Driver`. + + `Signal` can be considered a builder pattern for observable sequences that model imperative events part of the application. + + To find out more about units and how to use them, please visit `Documentation/Traits.md`. + */ +public typealias Signal = SharedSequence + +public struct SignalSharingStrategy: SharingStrategyProtocol { + public static var scheduler: SchedulerType { SharingScheduler.make() } + + public static func share(_ source: Observable) -> Observable { + source.share(scope: .whileConnected) + } +} + +extension SharedSequenceConvertibleType where SharingStrategy == SignalSharingStrategy { + /// Adds `asPublisher` to `SharingSequence` with `PublishSharingStrategy`. + public func asSignal() -> Signal { + self.asSharedSequence() + } +} diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..1acc998 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxCollectionViewReactiveArrayDataSource.swift @@ -0,0 +1,108 @@ +// +// RxCollectionViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxCollectionViewReactiveArrayDataSource + : NSObject + , UICollectionViewDataSource { + + @objc(numberOfSectionsInCollectionView:) + func numberOfSections(in: UICollectionView) -> Int { + 1 + } + + func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + _collectionView(collectionView, numberOfItemsInSection: section) + } + + fileprivate func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod() + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + _collectionView(collectionView, cellForItemAt: indexPath) + } +} + +class RxCollectionViewReactiveArrayDataSourceSequenceWrapper + : RxCollectionViewReactiveArrayDataSource + , RxCollectionViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) { + Binder(self) { collectionViewDataSource, sectionModels in + let sections = Array(sectionModels) + collectionViewDataSource.collectionView(collectionView, observedElements: sections) + }.on(observedEvent) + } +} + + +// Please take a look at `DelegateProxyType.swift` +class RxCollectionViewReactiveArrayDataSource + : _RxCollectionViewReactiveArrayDataSource + , SectionedViewDataSourceType { + + typealias CellFactory = (UICollectionView, Int, Element) -> UICollectionViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + var cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + // data source + + override func _collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + cellFactory(collectionView, indexPath.item, itemModels![indexPath.item]) + } + + // reactive + + func collectionView(_ collectionView: UICollectionView, observedElements: [Element]) { + self.itemModels = observedElements + + collectionView.reloadData() + + // workaround for http://stackoverflow.com/questions/39867325/ios-10-bug-uicollectionview-received-layout-attributes-for-a-cell-with-an-index + collectionView.collectionViewLayout.invalidateLayout() + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift new file mode 100644 index 0000000..53b8475 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxPickerViewAdapter.swift @@ -0,0 +1,92 @@ +// +// RxPickerViewAdapter.swift +// RxCocoa +// +// Created by Sergey Shulga on 12/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +class RxPickerViewArrayDataSource: NSObject, UIPickerViewDataSource, SectionedViewDataSourceType { + fileprivate var items: [T] = [] + + func model(at indexPath: IndexPath) throws -> Any { + guard items.indices ~= indexPath.row else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return items[indexPath.row] + } + + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 1 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + items.count + } +} + +class RxPickerViewSequenceDataSource + : RxPickerViewArrayDataSource + , RxPickerViewDataSourceType { + typealias Element = Sequence + + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) { + Binder(self) { dataSource, items in + dataSource.items = items + pickerView.reloadAllComponents() + } + .on(observedEvent.map(Array.init)) + } +} + +final class RxStringPickerViewAdapter + : RxPickerViewSequenceDataSource + , UIPickerViewDelegate { + + typealias TitleForRow = (Int, Sequence.Element) -> String? + private let titleForRow: TitleForRow + + init(titleForRow: @escaping TitleForRow) { + self.titleForRow = titleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { + titleForRow(row, items[row]) + } +} + +final class RxAttributedStringPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias AttributedTitleForRow = (Int, Sequence.Element) -> NSAttributedString? + private let attributedTitleForRow: AttributedTitleForRow + + init(attributedTitleForRow: @escaping AttributedTitleForRow) { + self.attributedTitleForRow = attributedTitleForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { + attributedTitleForRow(row, items[row]) + } +} + +final class RxPickerViewAdapter: RxPickerViewSequenceDataSource, UIPickerViewDelegate { + typealias ViewForRow = (Int, Sequence.Element, UIView?) -> UIView + private let viewForRow: ViewForRow + + init(viewForRow: @escaping ViewForRow) { + self.viewForRow = viewForRow + super.init() + } + + func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView { + viewForRow(row, items[row], view) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift new file mode 100644 index 0000000..6d612f3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/DataSources/RxTableViewReactiveArrayDataSource.swift @@ -0,0 +1,101 @@ +// +// RxTableViewReactiveArrayDataSource.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// objc monkey business +class _RxTableViewReactiveArrayDataSource + : NSObject + , UITableViewDataSource { + + func numberOfSections(in tableView: UITableView) -> Int { + 1 + } + + func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + _tableView(tableView, numberOfRowsInSection: section) + } + + fileprivate func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod() + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + _tableView(tableView, cellForRowAt: indexPath) + } +} + + +class RxTableViewReactiveArrayDataSourceSequenceWrapper + : RxTableViewReactiveArrayDataSource + , RxTableViewDataSourceType { + typealias Element = Sequence + + override init(cellFactory: @escaping CellFactory) { + super.init(cellFactory: cellFactory) + } + + func tableView(_ tableView: UITableView, observedEvent: Event) { + Binder(self) { tableViewDataSource, sectionModels in + let sections = Array(sectionModels) + tableViewDataSource.tableView(tableView, observedElements: sections) + }.on(observedEvent) + } +} + +// Please take a look at `DelegateProxyType.swift` +class RxTableViewReactiveArrayDataSource + : _RxTableViewReactiveArrayDataSource + , SectionedViewDataSourceType { + typealias CellFactory = (UITableView, Int, Element) -> UITableViewCell + + var itemModels: [Element]? + + func modelAtIndex(_ index: Int) -> Element? { + itemModels?[index] + } + + func model(at indexPath: IndexPath) throws -> Any { + precondition(indexPath.section == 0) + guard let item = itemModels?[indexPath.item] else { + throw RxCocoaError.itemsNotYetBound(object: self) + } + return item + } + + let cellFactory: CellFactory + + init(cellFactory: @escaping CellFactory) { + self.cellFactory = cellFactory + } + + override func _tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + itemModels?.count ?? 0 + } + + override func _tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + cellFactory(tableView, indexPath.item, itemModels![indexPath.row]) + } + + // reactive + + func tableView(_ tableView: UITableView, observedElements: [Element]) { + self.itemModels = observedElements + + tableView.reloadData() + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift b/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift new file mode 100644 index 0000000..aadf749 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Events/ItemEvents.swift @@ -0,0 +1,15 @@ +// +// ItemEvents.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) +import UIKit + +public typealias ItemMovedEvent = (sourceIndex: IndexPath, destinationIndex: IndexPath) +public typealias WillDisplayCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +public typealias DidEndDisplayingCellEvent = (cell: UITableViewCell, indexPath: IndexPath) +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift new file mode 100644 index 0000000..ba30547 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/NSTextStorage+Rx.swift @@ -0,0 +1,35 @@ +// +// NSTextStorage+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: NSTextStorage { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxTextStorageDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didProcessEditingRangeChangeInLength: Observable<(editedMask: NSTextStorage.EditActions, editedRange: NSRange, delta: Int)> { + return delegate + .methodInvoked(#selector(NSTextStorageDelegate.textStorage(_:didProcessEditing:range:changeInLength:))) + .map { a in + let editedMask = NSTextStorage.EditActions(rawValue: try castOrThrow(UInt.self, a[1]) ) + let editedRange = try castOrThrow(NSValue.self, a[2]).rangeValue + let delta = try castOrThrow(Int.self, a[3]) + + return (editedMask, editedRange, delta) + } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift new file mode 100644 index 0000000..b098a9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxCollectionViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxCollectionViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UICollectionView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxCollectionViewDataSourceType /*: UICollectionViewDataSource*/ { + + /// Type of elements that can be bound to collection view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter collectionView: Bound collection view. + /// - parameter observedEvent: Event + func collectionView(_ collectionView: UICollectionView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift new file mode 100644 index 0000000..1f390bf --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxPickerViewDataSourceType.swift @@ -0,0 +1,26 @@ +// +// RxPickerViewDataSourceType.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +/// Marks data source as `UIPickerView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxPickerViewDataSourceType { + /// Type of elements that can be bound to picker view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter pickerView: Bound picker view. + /// - parameter observedEvent: Event + func pickerView(_ pickerView: UIPickerView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift new file mode 100644 index 0000000..d59af9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Protocols/RxTableViewDataSourceType.swift @@ -0,0 +1,27 @@ +// +// RxTableViewDataSourceType.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/26/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// Marks data source as `UITableView` reactive data source enabling it to be used with one of the `bindTo` methods. +public protocol RxTableViewDataSourceType /*: UITableViewDataSource*/ { + + /// Type of elements that can be bound to table view. + associatedtype Element + + /// New observable sequence event observed. + /// + /// - parameter tableView: Bound table view. + /// - parameter observedEvent: Event + func tableView(_ tableView: UITableView, observedEvent: Event) +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..efb7554 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,92 @@ +// +// RxCollectionViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UICollectionView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UICollectionViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let collectionViewPrefetchDataSourceNotSet = CollectionViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class CollectionViewPrefetchDataSourceNotSet + : NSObject + , UICollectionViewDataSourcePrefetching { + + func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxCollectionViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType + , UICollectionViewDataSourcePrefetching { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourcePrefetchingProxy(collectionView: $0) } + } + + private var _prefetchItemsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch items callbacks. + internal var prefetchItemsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchItemsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchItemsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UICollectionViewDataSourcePrefetching? = collectionViewPrefetchDataSourceNotSet + + // MARK: delegate + + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, prefetchItemsAt indexPaths: [IndexPath]) { + if let subject = _prefetchItemsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? collectionViewPrefetchDataSourceNotSet).collectionView(collectionView, prefetchItemsAt: indexPaths) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? collectionViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchItemsPublishSubject { + subject.on(.completed) + } + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift new file mode 100644 index 0000000..793e544 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift @@ -0,0 +1,76 @@ +// +// RxCollectionViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UICollectionView: HasDataSource { + public typealias DataSource = UICollectionViewDataSource +} + +private let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() + +private final class CollectionViewDataSourceNotSet + : NSObject + , UICollectionViewDataSource { + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + 0 + } + + // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } + +} + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDataSourceProxy + : DelegateProxy + , DelegateProxyType + , UICollectionViewDataSource { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: ParentObject) { + self.collectionView = collectionView + super.init(parentObject: collectionView, delegateProxy: RxCollectionViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxCollectionViewDataSourceProxy(collectionView: $0) } + } + + private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet + + // MARK: delegate + + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) + } + + /// Required delegate method implementation. + public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAt: indexPath) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UICollectionViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? collectionViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift new file mode 100644 index 0000000..dd8f4b4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDelegateProxy.swift @@ -0,0 +1,32 @@ +// +// RxCollectionViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxCollectionViewDelegateProxy + : RxScrollViewDelegateProxy + , UICollectionViewDelegate + , UICollectionViewDelegateFlowLayout { + + /// Typed parent object. + public weak private(set) var collectionView: UICollectionView? + + /// Initializes `RxCollectionViewDelegateProxy` + /// + /// - parameter collectionView: Parent object for delegate proxy. + public init(collectionView: UICollectionView) { + self.collectionView = collectionView + super.init(scrollView: collectionView) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift new file mode 100644 index 0000000..372bf79 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxNavigationControllerDelegateProxy.swift @@ -0,0 +1,38 @@ +// +// RxNavigationControllerDelegateProxy.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import UIKit + import RxSwift + + extension UINavigationController: HasDelegate { + public typealias Delegate = UINavigationControllerDelegate + } + + /// For more information take a look at `DelegateProxyType`. + open class RxNavigationControllerDelegateProxy + : DelegateProxy + , DelegateProxyType + , UINavigationControllerDelegate { + + /// Typed parent object. + public weak private(set) var navigationController: UINavigationController? + + /// - parameter navigationController: Parent object for delegate proxy. + public init(navigationController: ParentObject) { + self.navigationController = navigationController + super.init(parentObject: navigationController, delegateProxy: RxNavigationControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxNavigationControllerDelegateProxy(navigationController: $0) } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift new file mode 100644 index 0000000..f9c65d1 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDataSourceProxy.swift @@ -0,0 +1,71 @@ +// +// RxPickerViewDataSourceProxy.swift +// RxCocoa +// +// Created by Sergey Shulga on 05/07/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension UIPickerView: HasDataSource { + public typealias DataSource = UIPickerViewDataSource +} + +private let pickerViewDataSourceNotSet = PickerViewDataSourceNotSet() + +final private class PickerViewDataSourceNotSet: NSObject, UIPickerViewDataSource { + func numberOfComponents(in pickerView: UIPickerView) -> Int { + 0 + } + + func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + 0 + } +} + +/// For more information take a look at `DelegateProxyType`. +public class RxPickerViewDataSourceProxy + : DelegateProxy + , DelegateProxyType + , UIPickerViewDataSource { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxPickerViewDataSourceProxy(pickerView: $0) } + } + + private weak var _requiredMethodsDataSource: UIPickerViewDataSource? = pickerViewDataSourceNotSet + + // MARK: UIPickerViewDataSource + + /// Required delegate method implementation. + public func numberOfComponents(in pickerView: UIPickerView) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).numberOfComponents(in: pickerView) + } + + /// Required delegate method implementation. + public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { + (_requiredMethodsDataSource ?? pickerViewDataSourceNotSet).pickerView(pickerView, numberOfRowsInComponent: component) + } + + /// For more information take a look at `DelegateProxyType`. + public override func setForwardToDelegate(_ forwardToDelegate: UIPickerViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? pickerViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift new file mode 100644 index 0000000..922126f --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxPickerViewDelegateProxy.swift @@ -0,0 +1,37 @@ +// +// RxPickerViewDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension UIPickerView: HasDelegate { + public typealias Delegate = UIPickerViewDelegate + } + + open class RxPickerViewDelegateProxy + : DelegateProxy + , DelegateProxyType + , UIPickerViewDelegate { + + /// Typed parent object. + public weak private(set) var pickerView: UIPickerView? + + /// - parameter pickerView: Parent object for delegate proxy. + public init(pickerView: ParentObject) { + self.pickerView = pickerView + super.init(parentObject: pickerView, delegateProxy: RxPickerViewDelegateProxy.self) + } + + // Register known implementationss + public static func registerKnownImplementations() { + self.register { RxPickerViewDelegateProxy(pickerView: $0) } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift new file mode 100644 index 0000000..59608d3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxScrollViewDelegateProxy.swift @@ -0,0 +1,92 @@ +// +// RxScrollViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension UIScrollView: HasDelegate { + public typealias Delegate = UIScrollViewDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxScrollViewDelegateProxy + : DelegateProxy + , DelegateProxyType + , UIScrollViewDelegate { + + /// Typed parent object. + public weak private(set) var scrollView: UIScrollView? + + /// - parameter scrollView: Parent object for delegate proxy. + public init(scrollView: ParentObject) { + self.scrollView = scrollView + super.init(parentObject: scrollView, delegateProxy: RxScrollViewDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxScrollViewDelegateProxy(scrollView: $0) } + self.register { RxTableViewDelegateProxy(tableView: $0) } + self.register { RxCollectionViewDelegateProxy(collectionView: $0) } + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + private var _contentOffsetBehaviorSubject: BehaviorSubject? + private var _contentOffsetPublishSubject: PublishSubject<()>? + + /// Optimized version used for observing content offset changes. + internal var contentOffsetBehaviorSubject: BehaviorSubject { + if let subject = _contentOffsetBehaviorSubject { + return subject + } + + let subject = BehaviorSubject(value: self.scrollView?.contentOffset ?? CGPoint.zero) + _contentOffsetBehaviorSubject = subject + + return subject + } + + /// Optimized version used for observing content offset changes. + internal var contentOffsetPublishSubject: PublishSubject<()> { + if let subject = _contentOffsetPublishSubject { + return subject + } + + let subject = PublishSubject<()>() + _contentOffsetPublishSubject = subject + + return subject + } + + // MARK: delegate methods + + /// For more information take a look at `DelegateProxyType`. + public func scrollViewDidScroll(_ scrollView: UIScrollView) { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.next(scrollView.contentOffset)) + } + if let subject = _contentOffsetPublishSubject { + subject.on(.next(())) + } + self._forwardToDelegate?.scrollViewDidScroll?(scrollView) + } + + deinit { + if let subject = _contentOffsetBehaviorSubject { + subject.on(.completed) + } + + if let subject = _contentOffsetPublishSubject { + subject.on(.completed) + } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift new file mode 100644 index 0000000..532ab68 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchBarDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// RxSearchBarDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 7/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UISearchBar: HasDelegate { + public typealias Delegate = UISearchBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchBarDelegateProxy + : DelegateProxy + , DelegateProxyType + , UISearchBarDelegate { + + /// Typed parent object. + public weak private(set) var searchBar: UISearchBar? + + /// - parameter searchBar: Parent object for delegate proxy. + public init(searchBar: ParentObject) { + self.searchBar = searchBar + super.init(parentObject: searchBar, delegateProxy: RxSearchBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchBarDelegateProxy(searchBar: $0) } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift new file mode 100644 index 0000000..04e0de0 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxSearchControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// RxSearchControllerDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension UISearchController: HasDelegate { + public typealias Delegate = UISearchControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxSearchControllerDelegateProxy + : DelegateProxy + , DelegateProxyType + , UISearchControllerDelegate { + + /// Typed parent object. + public weak private(set) var searchController: UISearchController? + + /// - parameter searchController: Parent object for delegate proxy. + public init(searchController: UISearchController) { + self.searchController = searchController + super.init(parentObject: searchController, delegateProxy: RxSearchControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxSearchControllerDelegateProxy(searchController: $0) } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift new file mode 100644 index 0000000..585894c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarControllerDelegateProxy.swift @@ -0,0 +1,39 @@ +// +// RxTabBarControllerDelegateProxy.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBarController: HasDelegate { + public typealias Delegate = UITabBarControllerDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarControllerDelegateProxy + : DelegateProxy + , DelegateProxyType + , UITabBarControllerDelegate { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBarController? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarControllerDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarControllerDelegateProxy(tabBar: $0) } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift new file mode 100644 index 0000000..6205730 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTabBarDelegateProxy.swift @@ -0,0 +1,49 @@ +// +// RxTabBarDelegateProxy.swift +// RxCocoa +// +// Created by Jesse Farless on 5/14/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITabBar: HasDelegate { + public typealias Delegate = UITabBarDelegate +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTabBarDelegateProxy + : DelegateProxy + , DelegateProxyType + , UITabBarDelegate { + + /// Typed parent object. + public weak private(set) var tabBar: UITabBar? + + /// - parameter tabBar: Parent object for delegate proxy. + public init(tabBar: ParentObject) { + self.tabBar = tabBar + super.init(parentObject: tabBar, delegateProxy: RxTabBarDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTabBarDelegateProxy(tabBar: $0) } + } + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> UITabBarDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: UITabBarDelegate?, to object: ParentObject) { + object.delegate = delegate + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift new file mode 100644 index 0000000..4345312 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourcePrefetchingProxy.swift @@ -0,0 +1,93 @@ +// +// RxTableViewDataSourcePrefetchingProxy.swift +// RxCocoa +// +// Created by Rowan Livingstone on 2/15/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +@available(iOS 10.0, tvOS 10.0, *) +extension UITableView: HasPrefetchDataSource { + public typealias PrefetchDataSource = UITableViewDataSourcePrefetching +} + +@available(iOS 10.0, tvOS 10.0, *) +private let tableViewPrefetchDataSourceNotSet = TableViewPrefetchDataSourceNotSet() + +@available(iOS 10.0, tvOS 10.0, *) +private final class TableViewPrefetchDataSourceNotSet + : NSObject + , UITableViewDataSourcePrefetching { + + func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {} + +} + +@available(iOS 10.0, tvOS 10.0, *) +open class RxTableViewDataSourcePrefetchingProxy + : DelegateProxy + , DelegateProxyType + , UITableViewDataSourcePrefetching { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: ParentObject) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourcePrefetchingProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourcePrefetchingProxy(tableView: $0) } + } + + private var _prefetchRowsPublishSubject: PublishSubject<[IndexPath]>? + + /// Optimized version used for observing prefetch rows callbacks. + internal var prefetchRowsPublishSubject: PublishSubject<[IndexPath]> { + if let subject = _prefetchRowsPublishSubject { + return subject + } + + let subject = PublishSubject<[IndexPath]>() + _prefetchRowsPublishSubject = subject + + return subject + } + + private weak var _requiredMethodsPrefetchDataSource: UITableViewDataSourcePrefetching? = tableViewPrefetchDataSourceNotSet + + // MARK: delegate + + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) { + if let subject = _prefetchRowsPublishSubject { + subject.on(.next(indexPaths)) + } + + (_requiredMethodsPrefetchDataSource ?? tableViewPrefetchDataSourceNotSet).tableView(tableView, prefetchRowsAt: indexPaths) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSourcePrefetching?, retainDelegate: Bool) { + _requiredMethodsPrefetchDataSource = forwardToDelegate ?? tableViewPrefetchDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + + deinit { + if let subject = _prefetchRowsPublishSubject { + subject.on(.completed) + } + } + +} + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift new file mode 100644 index 0000000..42d9386 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDataSourceProxy.swift @@ -0,0 +1,75 @@ +// +// RxTableViewDataSourceProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension UITableView: HasDataSource { + public typealias DataSource = UITableViewDataSource +} + +private let tableViewDataSourceNotSet = TableViewDataSourceNotSet() + +private final class TableViewDataSourceNotSet + : NSObject + , UITableViewDataSource { + + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + 0 + } + + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + rxAbstractMethod(message: dataSourceNotSet) + } +} + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDataSourceProxy + : DelegateProxy + , DelegateProxyType + , UITableViewDataSource { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(parentObject: tableView, delegateProxy: RxTableViewDataSourceProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTableViewDataSourceProxy(tableView: $0) } + } + + private weak var _requiredMethodsDataSource: UITableViewDataSource? = tableViewDataSourceNotSet + + // MARK: delegate + + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, numberOfRowsInSection: section) + } + + /// Required delegate method implementation. + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + (_requiredMethodsDataSource ?? tableViewDataSourceNotSet).tableView(tableView, cellForRowAt: indexPath) + } + + /// For more information take a look at `DelegateProxyType`. + open override func setForwardToDelegate(_ forwardToDelegate: UITableViewDataSource?, retainDelegate: Bool) { + _requiredMethodsDataSource = forwardToDelegate ?? tableViewDataSourceNotSet + super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift new file mode 100644 index 0000000..86a8758 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTableViewDelegateProxy.swift @@ -0,0 +1,30 @@ +// +// RxTableViewDelegateProxy.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 6/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTableViewDelegateProxy + : RxScrollViewDelegateProxy + , UITableViewDelegate { + + /// Typed parent object. + public weak private(set) var tableView: UITableView? + + /// - parameter tableView: Parent object for delegate proxy. + public init(tableView: UITableView) { + self.tableView = tableView + super.init(scrollView: tableView) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift new file mode 100644 index 0000000..12669f9 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextStorageDelegateProxy.swift @@ -0,0 +1,37 @@ +// +// RxTextStorageDelegateProxy.swift +// RxCocoa +// +// Created by Segii Shulga on 12/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension NSTextStorage: HasDelegate { + public typealias Delegate = NSTextStorageDelegate + } + + open class RxTextStorageDelegateProxy + : DelegateProxy + , DelegateProxyType + , NSTextStorageDelegate { + + /// Typed parent object. + public weak private(set) var textStorage: NSTextStorage? + + /// - parameter textStorage: Parent object for delegate proxy. + public init(textStorage: NSTextStorage) { + self.textStorage = textStorage + super.init(parentObject: textStorage, delegateProxy: RxTextStorageDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxTextStorageDelegateProxy(textStorage: $0) } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift new file mode 100644 index 0000000..c8a1dfd --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxTextViewDelegateProxy.swift @@ -0,0 +1,43 @@ +// +// RxTextViewDelegateProxy.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy + : RxScrollViewDelegateProxy + , UITextViewDelegate { + + /// Typed parent object. + public weak private(set) var textView: UITextView? + + /// - parameter textview: Parent object for delegate proxy. + public init(textView: UITextView) { + self.textView = textView + super.init(scrollView: textView) + } + + // MARK: delegate methods + + /// For more information take a look at `DelegateProxyType`. + @objc open func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { + /** + We've had some issues with observing text changes. This is here just in case we need the same hack in future and that + we wouldn't need to change the public interface. + */ + let forwardToDelegate = self.forwardToDelegate() as? UITextViewDelegate + return forwardToDelegate?.textView?(textView, + shouldChangeTextIn: range, + replacementText: text) ?? true + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift new file mode 100644 index 0000000..c758c02 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxWKNavigationDelegateProxy.swift @@ -0,0 +1,43 @@ +// +// RxWKNavigationDelegateProxy.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +open class RxWKNavigationDelegateProxy + : DelegateProxy + , DelegateProxyType +, WKNavigationDelegate { + + /// Typed parent object. + public weak private(set) var webView: WKWebView? + + /// - parameter webView: Parent object for delegate proxy. + public init(webView: ParentObject) { + self.webView = webView + super.init(parentObject: webView, delegateProxy: RxWKNavigationDelegateProxy.self) + } + + // Register known implementations + public static func registerKnownImplementations() { + self.register { RxWKNavigationDelegateProxy(webView: $0) } + } + + public static func currentDelegate(for object: WKWebView) -> WKNavigationDelegate? { + object.navigationDelegate + } + + public static func setCurrentDelegate(_ delegate: WKNavigationDelegate?, to object: WKWebView) { + object.navigationDelegate = delegate + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift new file mode 100644 index 0000000..ca2d4f1 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIActivityIndicatorView+Rx.swift @@ -0,0 +1,27 @@ +// +// UIActivityIndicatorView+Rx.swift +// RxCocoa +// +// Created by Ivan Persidskiy on 02/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIActivityIndicatorView { + /// Bindable sink for `startAnimating()`, `stopAnimating()` methods. + public var isAnimating: Binder { + Binder(self.base) { activityIndicator, active in + if active { + activityIndicator.startAnimating() + } else { + activityIndicator.stopAnimating() + } + } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift new file mode 100644 index 0000000..d776105 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIApplication+Rx.swift @@ -0,0 +1,106 @@ +// +// UIApplication+Rx.swift +// RxCocoa +// +// Created by Mads Bøgeskov on 18/01/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIApplication { + /// Bindable sink for `isNetworkActivityIndicatorVisible`. + public var isNetworkActivityIndicatorVisible: Binder { + return Binder(self.base) { application, active in + application.isNetworkActivityIndicatorVisible = active + } + } + + /// Reactive wrapper for `UIApplication.didEnterBackgroundNotification` + public static var didEnterBackground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didEnterBackgroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willEnterForegroundNotification` + public static var willEnterForeground: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didFinishLaunchingNotification` + public static var didFinishLaunching: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didFinishLaunchingNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didBecomeActiveNotification` + public static var didBecomeActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didBecomeActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willResignActiveNotification` + public static var willResignActive: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willResignActiveNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.didReceiveMemoryWarningNotification` + public static var didReceiveMemoryWarning: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.didReceiveMemoryWarningNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.willTerminateNotification` + public static var willTerminate: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.willTerminateNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.significantTimeChangeNotification` + public static var significantTimeChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.significantTimeChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.backgroundRefreshStatusDidChangeNotification` + public static var backgroundRefreshStatusDidChange: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.backgroundRefreshStatusDidChangeNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataWillBecomeUnavailableNotification` + public static var protectedDataWillBecomeUnavailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataWillBecomeUnavailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.protectedDataDidBecomeAvailableNotification` + public static var protectedDataDidBecomeAvailable: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.protectedDataDidBecomeAvailableNotification).map { _ in } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `UIApplication.userDidTakeScreenshotNotification` + public static var userDidTakeScreenshot: ControlEvent { + let source = NotificationCenter.default.rx.notification(UIApplication.userDidTakeScreenshotNotification).map { _ in } + + return ControlEvent(events: source) + } +} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift new file mode 100644 index 0000000..0bcaa99 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIBarButtonItem+Rx.swift @@ -0,0 +1,72 @@ +// +// UIBarButtonItem+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +private var rx_tap_key: UInt8 = 0 + +extension Reactive where Base: UIBarButtonItem { + /// Reactive wrapper for target action pattern on `self`. + public var tap: ControlEvent<()> { + let source = lazyInstanceObservable(&rx_tap_key) { () -> Observable<()> in + Observable.create { [weak control = self.base] observer in + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + let target = BarButtonItemTarget(barButtonItem: control) { + observer.on(.next(())) + } + return target + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } +} + + +@objc +final class BarButtonItemTarget: RxTarget { + typealias Callback = () -> Void + + weak var barButtonItem: UIBarButtonItem? + var callback: Callback! + + init(barButtonItem: UIBarButtonItem, callback: @escaping () -> Void) { + self.barButtonItem = barButtonItem + self.callback = callback + super.init() + barButtonItem.target = self + barButtonItem.action = #selector(BarButtonItemTarget.action(_:)) + } + + override func dispose() { + super.dispose() +#if DEBUG + MainScheduler.ensureRunningOnMainThread() +#endif + + barButtonItem?.target = nil + barButtonItem?.action = nil + + callback = nil + } + + @objc func action(_ sender: AnyObject) { + callback() + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift new file mode 100644 index 0000000..4d0f4c3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIButton+Rx.swift @@ -0,0 +1,82 @@ +// +// UIButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `TouchUpInside` control event. + public var tap: ControlEvent { + controlEvent(.touchUpInside) + } +} + +#endif + +#if os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + + /// Reactive wrapper for `PrimaryActionTriggered` control event. + public var primaryAction: ControlEvent { + controlEvent(.primaryActionTriggered) + } + +} + +#endif + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIButton { + /// Reactive wrapper for `setTitle(_:for:)` + public func title(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, title in + button.setTitle(title, for: controlState) + } + } + + /// Reactive wrapper for `setImage(_:for:)` + public func image(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setImage(image, for: controlState) + } + } + + /// Reactive wrapper for `setBackgroundImage(_:for:)` + public func backgroundImage(for controlState: UIControl.State = []) -> Binder { + Binder(self.base) { button, image in + button.setBackgroundImage(image, for: controlState) + } + } + +} +#endif + +#if os(iOS) || os(tvOS) + import RxSwift + import UIKit + + extension Reactive where Base: UIButton { + /// Reactive wrapper for `setAttributedTitle(_:controlState:)` + public func attributedTitle(for controlState: UIControl.State = []) -> Binder { + return Binder(self.base) { button, attributedTitle -> Void in + button.setAttributedTitle(attributedTitle, for: controlState) + } + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift new file mode 100644 index 0000000..7f3de00 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UICollectionView+Rx.swift @@ -0,0 +1,380 @@ +// +// UICollectionView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UICollectionView { + + /** + Binds sequences of elements to collection view items. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items) { (collectionView, row, element) in + let indexPath = IndexPath(row: row, section: 0) + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ \(row)" + return cell + } + .disposed(by: disposeBag) + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UICollectionView, Int, Sequence.Element) -> UICollectionViewCell) + -> Disposable where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + + } + + /** + Binds sequences of elements to collection view items. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of collection view cell. + - returns: Disposable object that can be used to unbind. + + Example + + let items = Observable.just([ + 1, + 2, + 3 + ]) + + items + .bind(to: collectionView.rx.items(cellIdentifier: "Cell", cellType: NumberCell.self)) { (row, element, cell) in + cell.value?.text = "\(element) @ \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxCollectionViewReactiveArrayDataSourceSequenceWrapper { cv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = cv.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to collection view items using a custom reactive data used to perform the transformation. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + + Example + + let dataSource = RxCollectionViewSectionedReloadDataSource>() + + let items = Observable.just([ + SectionModel(model: "First section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Second section", items: [ + 1.0, + 2.0, + 3.0 + ]), + SectionModel(model: "Third section", items: [ + 1.0, + 2.0, + 3.0 + ]) + ]) + + dataSource.configureCell = { (dataSource, cv, indexPath, element) in + let cell = cv.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! NumberCell + cell.value?.text = "\(element) @ row \(indexPath.row)" + return cell + } + + items + .bind(to: collectionView.rx.items(dataSource: dataSource)) + .disposed(by: disposeBag) + */ + public func items< + DataSource: RxCollectionViewDataSourceType & UICollectionViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable where DataSource.Element == Source.Element + { + return { source in + // This is called for sideeffects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UICollectionView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource, retainDataSource: true) { [weak collectionView = self.base] (_: RxCollectionViewDataSourceProxy, event) -> Void in + guard let collectionView = collectionView else { + return + } + dataSource.collectionView(collectionView, observedEvent: event) + } + } + } +} + +extension Reactive where Base: UICollectionView { + public typealias DisplayCollectionViewCellEvent = (cell: UICollectionViewCell, at: IndexPath) + public typealias DisplayCollectionViewSupplementaryViewEvent = (supplementaryView: UICollectionReusableView, elementKind: String, at: IndexPath) + + /// Reactive wrapper for `dataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var dataSource: DelegateProxy { + RxCollectionViewDataSourceProxy.proxy(for: base) + } + + /// Installs data source as forwarding delegate on `rx.dataSource`. + /// Data source won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter dataSource: Data source object. + /// - returns: Disposable object that can be used to unbind the data source. + public func setDataSource(_ dataSource: UICollectionViewDataSource) + -> Disposable { + RxCollectionViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + public var itemSelected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didSelectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didDeselectItemAtIndexPath:)`. + public var itemDeselected: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didDeselectItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didHighlightItemAt:)`. + public var itemHighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didHighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didUnhighlightItemAt:)`. + public var itemUnhighlighted: ControlEvent { + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUnhighlightItemAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:willDisplay:forItemAt:`. + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplay:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:willDisplaySupplementaryView:forElementKind:at:)`. + public var willDisplaySupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:willDisplaySupplementaryView:forElementKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView:didEndDisplaying:forItemAt:`. + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplaying:forItemAt:))) + .map { a in + return (try castOrThrow(UICollectionViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:)`. + public var didEndDisplayingSupplementaryView: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didEndDisplayingSupplementaryView:forElementOfKind:at:))) + .map { a in + return (try castOrThrow(UICollectionReusableView.self, a[1]), + try castOrThrow(String.self, a[2]), + try castOrThrow(IndexPath.self, a[3])) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelSelected(MyModel.self) + /// .map { ... + /// ``` + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemSelected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `collectionView(_:didSelectItemAtIndexPath:)`. + /// + /// It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + /// or any other data source conforming to `SectionedViewDataSourceType` protocol. + /// + /// ``` + /// collectionView.rx.modelDeselected(MyModel.self) + /// .map { ... + /// ``` + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = itemDeselected.flatMap { [weak view = self.base as UICollectionView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /// Synchronous helper method for retrieving a model at indexPath through a reactive data source + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemsWith*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return try castOrThrow(T.self, element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UICollectionViewDataSourcePrefetching) + -> Disposable { + return RxCollectionViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:prefetchItemsAt:)`. + public var prefetchItems: ControlEvent<[IndexPath]> { + let source = RxCollectionViewDataSourcePrefetchingProxy.proxy(for: base).prefetchItemsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `collectionView(_:cancelPrefetchingForItemsAt:)`. + public var cancelPrefetchingForItems: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UICollectionViewDataSourcePrefetching.collectionView(_:cancelPrefetchingForItemsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + +extension Reactive where Base: UICollectionView { + + /// Reactive wrapper for `delegate` message `collectionView(_:didUpdateFocusInContext:withAnimationCoordinator:)`. + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UICollectionViewDelegate.collectionView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UICollectionViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UICollectionViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } +} +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift new file mode 100644 index 0000000..6698cf2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift @@ -0,0 +1,86 @@ +// +// UIControl+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIControl { + /// Reactive wrapper for target action pattern. + /// + /// - parameter controlEvents: Filter for observed event types. + public func controlEvent(_ controlEvents: UIControl.Event) -> ControlEvent<()> { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { _ in + observer.on(.next(())) + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter controlEvents: Events that trigger value update sequence elements. + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + editingEvents: UIControl.Event, + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + let source: Observable = Observable.create { [weak weakControl = base] observer in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(getter(control))) + + let controlTarget = ControlTarget(control: control, controlEvents: editingEvents) { _ in + if let control = weakControl { + observer.on(.next(getter(control))) + } + } + + return Disposables.create(with: controlTarget.dispose) + } + .take(until: deallocated) + + let bindingObserver = Binder(base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// This is a separate method to better communicate to public consumers that + /// an `editingEvent` needs to fire for control property to be updated. + internal func controlPropertyWithDefaultEvents( + editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged], + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + return controlProperty( + editingEvents: editingEvents, + getter: getter, + setter: setter + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift new file mode 100644 index 0000000..e10c1ec --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIDatePicker+Rx.swift @@ -0,0 +1,43 @@ +// +// UIDatePicker+Rx.swift +// RxCocoa +// +// Created by Daniel Tartaglia on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UIDatePicker { + /// Reactive wrapper for `date` property. + public var date: ControlProperty { + value + } + + /// Reactive wrapper for `date` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.date + }, setter: { datePicker, value in + datePicker.date = value + } + ) + } + + /// Reactive wrapper for `countDownDuration` property. + public var countDownDuration: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { datePicker in + datePicker.countDownDuration + }, setter: { datePicker, value in + datePicker.countDownDuration = value + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift new file mode 100644 index 0000000..5512900 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIGestureRecognizer+Rx.swift @@ -0,0 +1,75 @@ +// +// UIGestureRecognizer+Rx.swift +// RxCocoa +// +// Created by Carlos García on 10/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +// This should be only used from `MainScheduler` +final class GestureTarget: RxTarget { + typealias Callback = (Recognizer) -> Void + + let selector = #selector(ControlTarget.eventHandler(_:)) + + weak var gestureRecognizer: Recognizer? + var callback: Callback? + + init(_ gestureRecognizer: Recognizer, callback: @escaping Callback) { + self.gestureRecognizer = gestureRecognizer + self.callback = callback + + super.init() + + gestureRecognizer.addTarget(self, action: selector) + + let method = self.method(for: selector) + if method == nil { + fatalError("Can't find method") + } + } + + @objc func eventHandler(_ sender: UIGestureRecognizer) { + if let callback = self.callback, let gestureRecognizer = self.gestureRecognizer { + callback(gestureRecognizer) + } + } + + override func dispose() { + super.dispose() + + self.gestureRecognizer?.removeTarget(self, action: self.selector) + self.callback = nil + } +} + +extension Reactive where Base: UIGestureRecognizer { + + /// Reactive wrapper for gesture recognizer events. + public var event: ControlEvent { + let source: Observable = Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = GestureTarget(control) { control in + observer.on(.next(control)) + } + + return observer + }.take(until: deallocated) + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift new file mode 100644 index 0000000..94796b6 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UINavigationController+Rx.swift @@ -0,0 +1,49 @@ +// +// UINavigationController+Rx.swift +// RxCocoa +// +// Created by Diogo on 13/04/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UINavigationController { + public typealias ShowEvent = (viewController: UIViewController, animated: Bool) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxNavigationControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for delegate method `navigationController(:willShow:animated:)`. + public var willShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:willShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `navigationController(:didShow:animated:)`. + public var didShow: ControlEvent { + let source: Observable = delegate + .methodInvoked(#selector(UINavigationControllerDelegate.navigationController(_:didShow:animated:))) + .map { arg in + let viewController = try castOrThrow(UIViewController.self, arg[1]) + let animated = try castOrThrow(Bool.self, arg[2]) + return (viewController, animated) + } + return ControlEvent(events: source) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift new file mode 100644 index 0000000..317dc13 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIPickerView+Rx.swift @@ -0,0 +1,224 @@ +// +// UIPickerView+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 5/12/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIPickerView { + + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxPickerViewDelegateProxy.proxy(for: base) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIPickerViewDelegate) + -> Disposable { + return RxPickerViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + return RxPickerViewDataSourceProxy.proxy(for: base) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + */ + public var itemSelected: ControlEvent<(row: Int, component: Int)> { + let source = delegate + .methodInvoked(#selector(UIPickerViewDelegate.pickerView(_:didSelectRow:inComponent:))) + .map { + return (row: try castOrThrow(Int.self, $0[1]), component: try castOrThrow(Int.self, $0[2])) + } + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `pickerView:didSelectRow:inComponent:`. + + It can be only used when one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods is used to bind observable sequence, + or any other data source conforming to a `ViewDataSourceType` protocol. + + ``` + pickerView.rx.modelSelected(MyModel.self) + .map { ... + ``` + - parameter modelType: Type of a Model which bound to the dataSource + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent<[T]> { + let source = itemSelected.flatMap { [weak view = self.base as UIPickerView] _, component -> Observable<[T]> in + guard let view = view else { + return Observable.empty() + } + + let model: [T] = try (0 ..< view.numberOfComponents).map { component in + let row = view.selectedRow(inComponent: component) + return try view.rx.model(at: IndexPath(row: row, section: component)) + } + + return Observable.just(model) + } + + return ControlEvent(events: source) + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter titleForRow: Transform between sequence elements and row titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemTitles) { (row, element) in + return element.title + } + .disposed(by: disposeBag) + + */ + + public func itemTitles + (_ source: Source) + -> (_ titleForRow: @escaping (Int, Sequence.Element) -> String?) + -> Disposable where Source.Element == Sequence { + return { titleForRow in + let adapter = RxStringPickerViewAdapter(titleForRow: titleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter attributedTitleForRow: Transform between sequence elements and row attributed titles. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.itemAttributedTitles) { (row, element) in + return NSAttributedString(string: element.title) + } + .disposed(by: disposeBag) + + */ + + public func itemAttributedTitles + (_ source: Source) + -> (_ attributedTitleForRow: @escaping (Int, Sequence.Element) -> NSAttributedString?) + -> Disposable where Source.Element == Sequence { + return { attributedTitleForRow in + let adapter = RxAttributedStringPickerViewAdapter(attributedTitleForRow: attributedTitleForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows. + + - parameter source: Observable sequence of items. + - parameter viewForRow: Transform between sequence elements and row views. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: pickerView.rx.items) { (row, element, view) in + guard let myView = view as? MyView else { + let view = MyView() + view.configure(with: element) + return view + } + myView.configure(with: element) + return myView + } + .disposed(by: disposeBag) + + */ + + public func items + (_ source: Source) + -> (_ viewForRow: @escaping (Int, Sequence.Element, UIView?) -> UIView) + -> Disposable where Source.Element == Sequence { + return { viewForRow in + let adapter = RxPickerViewAdapter(viewForRow: viewForRow) + return self.items(adapter: adapter)(source) + } + } + + /** + Binds sequences of elements to picker view rows using a custom reactive adapter used to perform the transformation. + This method will retain the adapter for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the adapter will present latest element + until the subscription isn't disposed. + + - parameter adapter: Adapter used to transform elements to picker components. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items(adapter: Adapter) + -> (_ source: Source) + -> Disposable where Source.Element == Adapter.Element { + return { source in + let delegateSubscription = self.setDelegate(adapter) + let dataSourceSubscription = source.subscribeProxyDataSource(ofObject: self.base, dataSource: adapter, retainDataSource: true, binding: { [weak pickerView = self.base] (_: RxPickerViewDataSourceProxy, event) in + guard let pickerView = pickerView else { return } + adapter.pickerView(pickerView, observedEvent: event) + }) + return Disposables.create(delegateSubscription, dataSourceSubscription) + } + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.itemTitles, rx.itemAttributedTitles, items(_ source: O)` methods was used.") + + return castOrFatalError(try dataSource.model(at: indexPath)) + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift new file mode 100644 index 0000000..cdb10be --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIRefreshControl+Rx.swift @@ -0,0 +1,28 @@ +// +// UIRefreshControl+Rx.swift +// RxCocoa +// +// Created by Yosuke Ishikawa on 1/31/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIRefreshControl { + /// Bindable sink for `beginRefreshing()`, `endRefreshing()` methods. + public var isRefreshing: Binder { + return Binder(self.base) { refreshControl, refresh in + if refresh { + refreshControl.beginRefreshing() + } else { + refreshControl.endRefreshing() + } + } + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift new file mode 100644 index 0000000..f90e1c2 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift @@ -0,0 +1,131 @@ +// +// UIScrollView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UIScrollView { + public typealias EndZoomEvent = (view: UIView?, scale: CGFloat) + public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer) + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxScrollViewDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `contentOffset`. + public var contentOffset: ControlProperty { + let proxy = RxScrollViewDelegateProxy.proxy(for: base) + + let bindingObserver = Binder(self.base) { scrollView, contentOffset in + scrollView.contentOffset = contentOffset + } + + return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver) + } + + /// Reactive wrapper for delegate method `scrollViewDidScroll` + public var didScroll: ControlEvent { + let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating` + public var willBeginDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDecelerating` + public var didEndDecelerating: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginDragging` + public var willBeginDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)` + public var willEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:))) + .map { value -> WillEndDraggingEvent in + let velocity = try castOrThrow(CGPoint.self, value[1]) + let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2]) + + guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown } + let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout.size) + + return (velocity, typedPointer) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)` + public var didEndDragging: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in + return try castOrThrow(Bool.self, value[1]) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidZoom` + public var didZoom: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in } + return ControlEvent(events: source) + } + + + /// Reactive wrapper for delegate method `scrollViewDidScrollToTop` + public var didScrollToTop: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation` + public var didEndScrollingAnimation: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)` + public var willBeginZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in + return try castOptionalOrThrow(UIView.self, value[1] as AnyObject) + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)` + public var didEndZooming: ControlEvent { + let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in + return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2])) + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UIScrollViewDelegate) + -> Disposable { + return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift new file mode 100644 index 0000000..3892b1c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISearchBar+Rx.swift @@ -0,0 +1,136 @@ +// +// UISearchBar+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISearchBar { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxSearchBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak searchBar = self.base as UISearchBar] () -> Observable in + let text = searchBar?.text + + let textDidChange = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:textDidChange:))) ?? Observable.empty()) + let didEndEditing = (searchBar?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) ?? Observable.empty()) + + return Observable.merge(textDidChange, didEndEditing) + .map { _ in searchBar?.text ?? "" } + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (searchBar, text: String?) in + searchBar.text = text + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `selectedScopeButtonIndex` property. + public var selectedScopeButtonIndex: ControlProperty { + let source: Observable = Observable.deferred { [weak source = self.base as UISearchBar] () -> Observable in + let index = source?.selectedScopeButtonIndex ?? 0 + + return (source?.rx.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBar(_:selectedScopeButtonIndexDidChange:))) ?? Observable.empty()) + .map { a in + return try castOrThrow(Int.self, a[1]) + } + .startWith(index) + } + + let bindingObserver = Binder(self.base) { (searchBar, index: Int) in + searchBar.selectedScopeButtonIndex = index + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + +#if os(iOS) + /// Reactive wrapper for delegate method `searchBarCancelButtonClicked`. + public var cancelButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarCancelButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarBookmarkButtonClicked`. + public var bookmarkButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarBookmarkButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarResultsListButtonClicked`. + public var resultsListButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarResultsListButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } +#endif + + /// Reactive wrapper for delegate method `searchBarSearchButtonClicked`. + public var searchButtonClicked: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarSearchButtonClicked(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidBeginEditing`. + public var textDidBeginEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidBeginEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Reactive wrapper for delegate method `searchBarTextDidEndEditing`. + public var textDidEndEditing: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UISearchBarDelegate.searchBarTextDidEndEditing(_:))) + .map { _ in + return () + } + return ControlEvent(events: source) + } + + /// Installs delegate as forwarding delegate on `delegate`. + /// Delegate won't be retained. + /// + /// It enables using normal delegate mechanism with reactive delegate mechanism. + /// + /// - parameter delegate: Delegate object. + /// - returns: Disposable object that can be used to unbind the delegate. + public func setDelegate(_ delegate: UISearchBarDelegate) + -> Disposable { + RxSearchBarDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift new file mode 100644 index 0000000..4f524a5 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISearchController+Rx.swift @@ -0,0 +1,58 @@ +// +// UISearchController+Rx.swift +// RxCocoa +// +// Created by Segii Shulga on 3/17/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + + import RxSwift + import UIKit + + extension Reactive where Base: UISearchController { + /// Reactive wrapper for `delegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + return RxSearchControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message. + public var didDismiss: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.didDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var didPresent: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.didPresentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var present: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.presentSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willDismiss: Observable { + return delegate + .methodInvoked(#selector(UISearchControllerDelegate.willDismissSearchController(_:))) + .map { _ in } + } + + /// Reactive wrapper for `delegate` message. + public var willPresent: Observable { + return delegate + .methodInvoked( #selector(UISearchControllerDelegate.willPresentSearchController(_:))) + .map { _ in } + } + + } + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift new file mode 100644 index 0000000..1a62662 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISegmentedControl+Rx.swift @@ -0,0 +1,54 @@ +// +// UISegmentedControl+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISegmentedControl { + /// Reactive wrapper for `selectedSegmentIndex` property. + public var selectedSegmentIndex: ControlProperty { + value + } + + /// Reactive wrapper for `selectedSegmentIndex` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { segmentedControl in + segmentedControl.selectedSegmentIndex + }, setter: { segmentedControl, value in + segmentedControl.selectedSegmentIndex = value + } + ) + } + + /// Reactive wrapper for `setEnabled(_:forSegmentAt:)` + public func enabledForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, segmentEnabled -> Void in + segmentedControl.setEnabled(segmentEnabled, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setTitle(_:forSegmentAt:)` + public func titleForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, title -> Void in + segmentedControl.setTitle(title, forSegmentAt: index) + } + } + + /// Reactive wrapper for `setImage(_:forSegmentAt:)` + public func imageForSegment(at index: Int) -> Binder { + return Binder(self.base) { segmentedControl, image -> Void in + segmentedControl.setImage(image, forSegmentAt: index) + } + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift new file mode 100644 index 0000000..07d4adb --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISlider+Rx.swift @@ -0,0 +1,29 @@ +// +// UISlider+Rx.swift +// RxCocoa +// +// Created by Alexander van der Werff on 28/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UISlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { slider in + slider.value + }, setter: { slider, value in + slider.value = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift new file mode 100644 index 0000000..29f6386 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UIStepper+Rx.swift @@ -0,0 +1,29 @@ +// +// UIStepper+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 9/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UIStepper { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { stepper in + stepper.value + }, setter: { stepper, value in + stepper.value = value + } + ) + } +} + +#endif + diff --git a/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift new file mode 100644 index 0000000..6e116b3 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UISwitch+Rx.swift @@ -0,0 +1,38 @@ +// +// UISwitch+Rx.swift +// RxCocoa +// +// Created by Carlos García on 8/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UISwitch { + + /// Reactive wrapper for `isOn` property. + public var isOn: ControlProperty { + value + } + + /// Reactive wrapper for `isOn` property. + /// + /// ⚠️ Versions prior to iOS 10.2 were leaking `UISwitch`'s, so on those versions + /// underlying observable sequence won't complete when nothing holds a strong reference + /// to `UISwitch`. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { uiSwitch in + uiSwitch.isOn + }, setter: { uiSwitch, value in + uiSwitch.isOn = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift new file mode 100644 index 0000000..e989667 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITabBar+Rx.swift @@ -0,0 +1,92 @@ +// +// UITabBar+Rx.swift +// RxCocoa +// +// Created by Jesse Farless on 5/13/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBar { + + /// Reactive wrapper for `delegate` message `tabBar(_:willBeginCustomizing:)`. + public var willBeginCustomizing: ControlEvent<[UITabBarItem]> { + + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didBeginCustomizing:)`. + public var didBeginCustomizing: ControlEvent<[UITabBarItem]> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didBeginCustomizing:))) + .map { a in + return try castOrThrow([UITabBarItem].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:willEndCustomizing:changed:)`. + public var willEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didEndCustomizing:changed:)`. + public var didEndCustomizing: ControlEvent<([UITabBarItem], Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (([UITabBarItem], Bool)) in + let items = try castOrThrow([UITabBarItem].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (items, changed) + } + + return ControlEvent(events: source) + } + +} +#endif + +/** + iOS and tvOS + */ + +extension Reactive where Base: UITabBar { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBar(_:didSelect:)`. + public var didSelectItem: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarDelegate.tabBar(_:didSelect:))) + .map { a in + return try castOrThrow(UITabBarItem.self, a[1]) + } + + return ControlEvent(events: source) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift new file mode 100644 index 0000000..4b48e8e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITabBarController+Rx.swift @@ -0,0 +1,79 @@ +// +// UITabBarController+Rx.swift +// RxCocoa +// +// Created by Yusuke Kita on 2016/12/07. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +/** + iOS only + */ +#if os(iOS) +extension Reactive where Base: UITabBarController { + + /// Reactive wrapper for `delegate` message `tabBarController:willBeginCustomizing:`. + public var willBeginCustomizing: ControlEvent<[UIViewController]> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willBeginCustomizing:))) + .map { a in + return try castOrThrow([UIViewController].self, a[1]) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:willEndCustomizing:changed:`. + public var willEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:willEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didEndCustomizing:changed:`. + public var didEndCustomizing: ControlEvent<(viewControllers: [UIViewController], changed: Bool)> { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didEndCustomizing:changed:))) + .map { (a: [Any]) -> (viewControllers: [UIViewController], changed: Bool) in + let viewControllers = try castOrThrow([UIViewController].self, a[1]) + let changed = try castOrThrow(Bool.self, a[2]) + return (viewControllers, changed) + } + + return ControlEvent(events: source) + } +} +#endif + +/** + iOS and tvOS + */ + + extension Reactive where Base: UITabBarController { + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTabBarControllerDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `delegate` message `tabBarController:didSelect:`. + public var didSelect: ControlEvent { + let source = delegate.methodInvoked(#selector(UITabBarControllerDelegate.tabBarController(_:didSelect:))) + .map { a in + return try castOrThrow(UIViewController.self, a[1]) + } + + return ControlEvent(events: source) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift new file mode 100644 index 0000000..b217133 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITableView+Rx.swift @@ -0,0 +1,429 @@ +// +// UITableView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 4/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +// Items + +extension Reactive where Base: UITableView { + + /** + Binds sequences of elements to table view rows. + + - parameter source: Observable sequence of items. + - parameter cellFactory: Transform between sequence elements and view cells. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items) { (tableView, row, element) in + let cell = tableView.dequeueReusableCell(withIdentifier: "Cell")! + cell.textLabel?.text = "\(element) @ row \(row)" + return cell + } + .disposed(by: disposeBag) + + */ + public func items + (_ source: Source) + -> (_ cellFactory: @escaping (UITableView, Int, Sequence.Element) -> UITableViewCell) + -> Disposable + where Source.Element == Sequence { + return { cellFactory in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper(cellFactory: cellFactory) + return self.items(dataSource: dataSource)(source) + } + } + + /** + Binds sequences of elements to table view rows. + + - parameter cellIdentifier: Identifier used to dequeue cells. + - parameter source: Observable sequence of items. + - parameter configureCell: Transform between sequence elements and view cells. + - parameter cellType: Type of table view cell. + - returns: Disposable object that can be used to unbind. + + Example: + + let items = Observable.just([ + "First Item", + "Second Item", + "Third Item" + ]) + + items + .bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { (row, element, cell) in + cell.textLabel?.text = "\(element) @ row \(row)" + } + .disposed(by: disposeBag) + */ + public func items + (cellIdentifier: String, cellType: Cell.Type = Cell.self) + -> (_ source: Source) + -> (_ configureCell: @escaping (Int, Sequence.Element, Cell) -> Void) + -> Disposable + where Source.Element == Sequence { + return { source in + return { configureCell in + let dataSource = RxTableViewReactiveArrayDataSourceSequenceWrapper { tv, i, item in + let indexPath = IndexPath(item: i, section: 0) + let cell = tv.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! Cell + configureCell(i, item, cell) + return cell + } + return self.items(dataSource: dataSource)(source) + } + } + } + + + /** + Binds sequences of elements to table view rows using a custom reactive data used to perform the transformation. + This method will retain the data source for as long as the subscription isn't disposed (result `Disposable` + being disposed). + In case `source` observable sequence terminates successfully, the data source will present latest element + until the subscription isn't disposed. + + - parameter dataSource: Data source used to transform elements to view cells. + - parameter source: Observable sequence of items. + - returns: Disposable object that can be used to unbind. + */ + public func items< + DataSource: RxTableViewDataSourceType & UITableViewDataSource, + Source: ObservableType> + (dataSource: DataSource) + -> (_ source: Source) + -> Disposable + where DataSource.Element == Source.Element { + return { source in + // This is called for sideeffects only, and to make sure delegate proxy is in place when + // data source is being bound. + // This is needed because theoretically the data source subscription itself might + // call `self.rx.delegate`. If that happens, it might cause weird side effects since + // setting data source will set delegate, and UITableView might get into a weird state. + // Therefore it's better to set delegate proxy first, just to be sure. + _ = self.delegate + // Strong reference is needed because data source is in use until result subscription is disposed + return source.subscribeProxyDataSource(ofObject: self.base, dataSource: dataSource as UITableViewDataSource, retainDataSource: true) { [weak tableView = self.base] (_: RxTableViewDataSourceProxy, event) -> Void in + guard let tableView = tableView else { + return + } + dataSource.tableView(tableView, observedEvent: event) + } + } + } + +} + +extension Reactive where Base: UITableView { + /** + Reactive wrapper for `dataSource`. + + For more information take a look at `DelegateProxyType` protocol documentation. + */ + public var dataSource: DelegateProxy { + RxTableViewDataSourceProxy.proxy(for: base) + } + + /** + Installs data source as forwarding delegate on `rx.dataSource`. + Data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter dataSource: Data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setDataSource(_ dataSource: UITableViewDataSource) + -> Disposable { + RxTableViewDataSourceProxy.installForwardDelegate(dataSource, retainDelegate: false, onProxyForObject: self.base) + } + + // events + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + */ + public var itemSelected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + */ + public var itemDeselected: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didDeselectRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didHighlightRowAt:`. + */ + public var itemHighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didHighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didUnhighlightRowAt:`. + */ + public var itemUnhighlighted: ControlEvent { + let source = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUnhighlightRowAt:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:accessoryButtonTappedForRowWithIndexPath:`. + */ + public var itemAccessoryButtonTapped: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:accessoryButtonTappedForRowWith:))) + .map { a in + return try castOrThrow(IndexPath.self, a[1]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemInserted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .insert + } + .map { a in + return (try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + */ + public var itemDeleted: ControlEvent { + let source = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:commit:forRowAt:))) + .filter { a in + return UITableViewCell.EditingStyle(rawValue: (try castOrThrow(NSNumber.self, a[1])).intValue) == .delete + } + .map { a in + return try castOrThrow(IndexPath.self, a[2]) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:moveRowAtIndexPath:toIndexPath:`. + */ + public var itemMoved: ControlEvent { + let source: Observable = self.dataSource.methodInvoked(#selector(UITableViewDataSource.tableView(_:moveRowAt:to:))) + .map { a in + return (try castOrThrow(IndexPath.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:willDisplayCell:forRowAtIndexPath:`. + */ + public var willDisplayCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:willDisplay:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didEndDisplayingCell:forRowAtIndexPath:`. + */ + public var didEndDisplayingCell: ControlEvent { + let source: Observable = self.delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didEndDisplaying:forRowAt:))) + .map { a in + return (try castOrThrow(UITableViewCell.self, a[1]), try castOrThrow(IndexPath.self, a[2])) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didSelectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelSelected(MyModel.self) + .map { ... + ``` + */ + public func modelSelected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemSelected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:didDeselectRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeselected(MyModel.self) + .map { ... + ``` + */ + public func modelDeselected(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeselected.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Reactive wrapper for `delegate` message `tableView:commitEditingStyle:forRowAtIndexPath:`. + + It can be only used when one of the `rx.itemsWith*` methods is used to bind observable sequence, + or any other data source conforming to `SectionedViewDataSourceType` protocol. + + ``` + tableView.rx.modelDeleted(MyModel.self) + .map { ... + ``` + */ + public func modelDeleted(_ modelType: T.Type) -> ControlEvent { + let source: Observable = self.itemDeleted.flatMap { [weak view = self.base as UITableView] indexPath -> Observable in + guard let view = view else { + return Observable.empty() + } + + return Observable.just(try view.rx.model(at: indexPath)) + } + + return ControlEvent(events: source) + } + + /** + Synchronous helper method for retrieving a model at indexPath through a reactive data source. + */ + public func model(at indexPath: IndexPath) throws -> T { + let dataSource: SectionedViewDataSourceType = castOrFatalError(self.dataSource.forwardToDelegate(), message: "This method only works in case one of the `rx.items*` methods was used.") + + let element = try dataSource.model(at: indexPath) + + return castOrFatalError(element) + } +} + +@available(iOS 10.0, tvOS 10.0, *) +extension Reactive where Base: UITableView { + + /// Reactive wrapper for `prefetchDataSource`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var prefetchDataSource: DelegateProxy { + RxTableViewDataSourcePrefetchingProxy.proxy(for: base) + } + + /** + Installs prefetch data source as forwarding delegate on `rx.prefetchDataSource`. + Prefetch data source won't be retained. + + It enables using normal delegate mechanism with reactive delegate mechanism. + + - parameter prefetchDataSource: Prefetch data source object. + - returns: Disposable object that can be used to unbind the data source. + */ + public func setPrefetchDataSource(_ prefetchDataSource: UITableViewDataSourcePrefetching) + -> Disposable { + return RxTableViewDataSourcePrefetchingProxy.installForwardDelegate(prefetchDataSource, retainDelegate: false, onProxyForObject: self.base) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:prefetchRowsAt:)`. + public var prefetchRows: ControlEvent<[IndexPath]> { + let source = RxTableViewDataSourcePrefetchingProxy.proxy(for: base).prefetchRowsPublishSubject + return ControlEvent(events: source) + } + + /// Reactive wrapper for `prefetchDataSource` message `tableView(_:cancelPrefetchingForRowsAt:)`. + public var cancelPrefetchingForRows: ControlEvent<[IndexPath]> { + let source = prefetchDataSource.methodInvoked(#selector(UITableViewDataSourcePrefetching.tableView(_:cancelPrefetchingForRowsAt:))) + .map { a in + return try castOrThrow(Array.self, a[1]) + } + + return ControlEvent(events: source) + } + +} +#endif + +#if os(tvOS) + + extension Reactive where Base: UITableView { + + /** + Reactive wrapper for `delegate` message `tableView:didUpdateFocusInContext:withAnimationCoordinator:`. + */ + public var didUpdateFocusInContextWithAnimationCoordinator: ControlEvent<(context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator)> { + + let source = delegate.methodInvoked(#selector(UITableViewDelegate.tableView(_:didUpdateFocusIn:with:))) + .map { a -> (context: UITableViewFocusUpdateContext, animationCoordinator: UIFocusAnimationCoordinator) in + let context = try castOrThrow(UITableViewFocusUpdateContext.self, a[1]) + let animationCoordinator = try castOrThrow(UIFocusAnimationCoordinator.self, a[2]) + return (context: context, animationCoordinator: animationCoordinator) + } + + return ControlEvent(events: source) + } + } +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift new file mode 100644 index 0000000..614fecc --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITextField+Rx.swift @@ -0,0 +1,55 @@ +// +// UITextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import RxSwift +import UIKit + +extension Reactive where Base: UITextField { + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.text + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is imporant for proper input + // when IME input method is used. + if textField.text != value { + textField.text = value + } + } + ) + } + + /// Bindable sink for `attributedText` property. + public var attributedText: ControlProperty { + return base.rx.controlPropertyWithDefaultEvents( + getter: { textField in + textField.attributedText + }, + setter: { textField, value in + // This check is important because setting text value always clears control state + // including marked text selection which is imporant for proper input + // when IME input method is used. + if textField.attributedText != value { + textField.attributedText = value + } + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift new file mode 100644 index 0000000..497ab66 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/UITextView+Rx.swift @@ -0,0 +1,125 @@ +// +// UITextView+Rx.swift +// RxCocoa +// +// Created by Yuta ToKoRo on 7/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(tvOS) + +import UIKit +import RxSwift + +extension Reactive where Base: UITextView { + /// Reactive wrapper for `text` property + public var text: ControlProperty { + value + } + + /// Reactive wrapper for `text` property. + public var value: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let text = textView?.text + + let textChanged = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because text storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.textStorage.string + } + ?? Observable.empty() + + return textChanged + .startWith(text) + } + + let bindingObserver = Binder(self.base) { (textView, text: String?) in + // This check is important because setting text value always clears control state + // including marked text selection which is imporant for proper input + // when IME input method is used. + if textView.text != text { + textView.text = text + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + + /// Reactive wrapper for `attributedText` property. + public var attributedText: ControlProperty { + let source: Observable = Observable.deferred { [weak textView = self.base] in + let attributedText = textView?.attributedText + + let textChanged: Observable = textView?.textStorage + // This project uses text storage notifications because + // that's the only way to catch autocorrect changes + // in all cases. Other suggestions are welcome. + .rx.didProcessEditingRangeChangeInLength + // This observe on is here because attributedText storage + // will emit event while process is not completely done, + // so rebinding a value will cause an exception to be thrown. + .observe(on:MainScheduler.asyncInstance) + .map { _ in + return textView?.attributedText + } + ?? Observable.empty() + + return textChanged + .startWith(attributedText) + } + + let bindingObserver = Binder(self.base) { (textView, attributedText: NSAttributedString?) in + // This check is important because setting text value always clears control state + // including marked text selection which is imporant for proper input + // when IME input method is used. + if textView.attributedText != attributedText { + textView.attributedText = attributedText + } + } + + return ControlProperty(values: source, valueSink: bindingObserver) + } + + /// Reactive wrapper for `delegate` message. + public var didBeginEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidBeginEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didEndEditing: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidEndEditing(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChange: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChange(_:))) + .map { _ in + return () + }) + } + + /// Reactive wrapper for `delegate` message. + public var didChangeSelection: ControlEvent<()> { + return ControlEvent<()>(events: self.delegate.methodInvoked(#selector(UITextViewDelegate.textViewDidChangeSelection(_:))) + .map { _ in + return () + }) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift b/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift new file mode 100644 index 0000000..b3b4d84 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/iOS/WKWebView+Rx.swift @@ -0,0 +1,57 @@ +// +// WKWebView+Rx.swift +// RxCocoa +// +// Created by Giuseppe Lanza on 14/02/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +#if os(iOS) || os(macOS) + +import RxSwift +import WebKit + +@available(iOS 8.0, OSX 10.10, OSXApplicationExtension 10.10, *) +extension Reactive where Base: WKWebView { + + /// Reactive wrapper for `navigationDelegate`. + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var navigationDelegate: DelegateProxy { + RxWKNavigationDelegateProxy.proxy(for: base) + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didCommit: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didCommit:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didStartLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didStartProvisionalNavigation:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFinishLoad: Observable { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFinish:))) + .map { a in try castOrThrow(WKNavigation.self, a[1]) } + } + + /// Reactive wrapper for `navigationDelegate` message. + public var didFailLoad: Observable<(WKNavigation, Error)> { + navigationDelegate + .methodInvoked(#selector(WKNavigationDelegate.webView(_:didFail:withError:))) + .map { a in + ( + try castOrThrow(WKNavigation.self, a[1]), + try castOrThrow(Error.self, a[2]) + ) + } + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift new file mode 100644 index 0000000..7c22361 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSButton+Rx.swift @@ -0,0 +1,33 @@ +// +// NSButton+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSButton { + + /// Reactive wrapper for control event. + public var tap: ControlEvent { + self.controlEvent + } + + /// Reactive wrapper for `state` property`. + public var state: ControlProperty { + return self.base.rx.controlProperty( + getter: { control in + return control.state + }, setter: { (control: NSButton, state: NSControl.StateValue) in + control.state = state + } + ) + } +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift new file mode 100644 index 0000000..534f40c --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSControl+Rx.swift @@ -0,0 +1,87 @@ +// +// NSControl+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +private var rx_value_key: UInt8 = 0 +private var rx_control_events_key: UInt8 = 0 + +extension Reactive where Base: NSControl { + + /// Reactive wrapper for control event. + public var controlEvent: ControlEvent<()> { + MainScheduler.ensureRunningOnMainThread() + + let source = self.lazyInstanceObservable(&rx_control_events_key) { () -> Observable in + Observable.create { [weak control = self.base] observer in + MainScheduler.ensureRunningOnMainThread() + + guard let control = control else { + observer.on(.completed) + return Disposables.create() + } + + let observer = ControlTarget(control: control) { _ in + observer.on(.next(())) + } + + return observer + } + .take(until: self.deallocated) + .share() + } + + return ControlEvent(events: source) + } + + /// Creates a `ControlProperty` that is triggered by target/action pattern value updates. + /// + /// - parameter getter: Property value getter. + /// - parameter setter: Property value setter. + public func controlProperty( + getter: @escaping (Base) -> T, + setter: @escaping (Base, T) -> Void + ) -> ControlProperty { + MainScheduler.ensureRunningOnMainThread() + + let source = self.base.rx.lazyInstanceObservable(&rx_value_key) { () -> Observable<()> in + return Observable.create { [weak weakControl = self.base] (observer: AnyObserver<()>) in + guard let control = weakControl else { + observer.on(.completed) + return Disposables.create() + } + + observer.on(.next(())) + + let observer = ControlTarget(control: control) { _ in + if weakControl != nil { + observer.on(.next(())) + } + } + + return observer + } + .take(until: self.deallocated) + .share(replay: 1, scope: .whileConnected) + } + .flatMap { [weak base] _ -> Observable in + guard let control = base else { return Observable.empty() } + return Observable.just(getter(control)) + } + + let bindingObserver = Binder(self.base, binding: setter) + + return ControlProperty(values: source, valueSink: bindingObserver) + } +} + + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift new file mode 100644 index 0000000..2e5b19a --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSSlider+Rx.swift @@ -0,0 +1,30 @@ +// +// NSSlider+Rx.swift +// RxCocoa +// +// Created by Junior B. on 24/05/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import RxSwift +import Cocoa + +extension Reactive where Base: NSSlider { + + /// Reactive wrapper for `value` property. + public var value: ControlProperty { + return self.base.rx.controlProperty( + getter: { control -> Double in + return control.doubleValue + }, + setter: { control, value in + control.doubleValue = value + } + ) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift new file mode 100644 index 0000000..ce69f9e --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSTextField+Rx.swift @@ -0,0 +1,87 @@ +// +// NSTextField+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 5/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextField`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextFieldDelegateProxy + : DelegateProxy + , DelegateProxyType + , NSTextFieldDelegate { + + /// Typed parent object. + public weak private(set) var textField: NSTextField? + + /// Initializes `RxTextFieldDelegateProxy` + /// + /// - parameter textField: Parent object for delegate proxy. + init(textField: NSTextField) { + self.textField = textField + super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextFieldDelegateProxy(textField: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + open func controlTextDidChange(_ notification: Notification) { + let textField: NSTextField = castOrFatalError(notification.object) + let nextValue = textField.stringValue + self.textSubject.on(.next(nextValue)) + _forwardToDelegate?.controlTextDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextFieldDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextFieldDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextField { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextFieldDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `text` property. + public var text: ControlProperty { + let delegate = RxTextFieldDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textField = self.base] in + delegate.textSubject.startWith(textField?.stringValue) + }.take(until: self.deallocated) + + let observer = Binder(self.base) { (control, value: String?) in + control.stringValue = value ?? "" + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift new file mode 100644 index 0000000..c3134e4 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSTextView+Rx.swift @@ -0,0 +1,94 @@ +// +// NSTextView+Rx.swift +// RxCocoa +// +// Created by Cee on 8/5/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + +import Cocoa +import RxSwift + +/// Delegate proxy for `NSTextView`. +/// +/// For more information take a look at `DelegateProxyType`. +open class RxTextViewDelegateProxy: DelegateProxy, DelegateProxyType, NSTextViewDelegate { + + #if compiler(>=5.2) + /// Typed parent object. + /// + /// - note: Since Swift 5.2 and Xcode 11.4, Apple have suddenly + /// disallowed using `weak` for NSTextView. For more details + /// see this GitHub Issue: https://git.io/JvSRn + public private(set) var textView: NSTextView? + #else + /// Typed parent object. + public weak private(set) var textView: NSTextView? + #endif + + /// Initializes `RxTextViewDelegateProxy` + /// + /// - parameter textView: Parent object for delegate proxy. + init(textView: NSTextView) { + self.textView = textView + super.init(parentObject: textView, delegateProxy: RxTextViewDelegateProxy.self) + } + + public static func registerKnownImplementations() { + self.register { RxTextViewDelegateProxy(textView: $0) } + } + + fileprivate let textSubject = PublishSubject() + + // MARK: Delegate methods + + open func textDidChange(_ notification: Notification) { + let textView: NSTextView = castOrFatalError(notification.object) + let nextValue = textView.string + self.textSubject.on(.next(nextValue)) + self._forwardToDelegate?.textDidChange?(notification) + } + + // MARK: Delegate proxy methods + + /// For more information take a look at `DelegateProxyType`. + open class func currentDelegate(for object: ParentObject) -> NSTextViewDelegate? { + object.delegate + } + + /// For more information take a look at `DelegateProxyType`. + open class func setCurrentDelegate(_ delegate: NSTextViewDelegate?, to object: ParentObject) { + object.delegate = delegate + } + +} + +extension Reactive where Base: NSTextView { + + /// Reactive wrapper for `delegate`. + /// + /// For more information take a look at `DelegateProxyType` protocol documentation. + public var delegate: DelegateProxy { + RxTextViewDelegateProxy.proxy(for: self.base) + } + + /// Reactive wrapper for `string` property. + public var string: ControlProperty { + let delegate = RxTextViewDelegateProxy.proxy(for: self.base) + + let source = Observable.deferred { [weak textView = self.base] in + delegate.textSubject.startWith(textView?.string ?? "") + }.take(until: self.deallocated) + + let observer = Binder(self.base) { control, value in + control.string = value + } + + return ControlProperty(values: source, valueSink: observer.asObserver()) + } + +} + +#endif diff --git a/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift b/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift new file mode 100644 index 0000000..f4256d1 --- /dev/null +++ b/Pods/RxCocoa/RxCocoa/macOS/NSView+Rx.swift @@ -0,0 +1,21 @@ +// +// NSView+Rx.swift +// RxCocoa +// +// Created by Krunoslav Zaher on 12/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) + import Cocoa + import RxSwift + + extension Reactive where Base: NSView { + /// Bindable sink for `alphaValue` property. + public var alpha: Binder { + return Binder(self.base) { view, value in + view.alphaValue = value + } + } + } +#endif diff --git a/Pods/RxRelay/LICENSE.md b/Pods/RxRelay/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxRelay/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/RxRelay/README.md b/Pods/RxRelay/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/Pods/RxRelay/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+
Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.2.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.2.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxRelay/RxRelay/BehaviorRelay.swift b/Pods/RxRelay/RxRelay/BehaviorRelay.swift new file mode 100644 index 0000000..e02fc8f --- /dev/null +++ b/Pods/RxRelay/RxRelay/BehaviorRelay.swift @@ -0,0 +1,42 @@ +// +// BehaviorRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 10/7/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// BehaviorRelay is a wrapper for `BehaviorSubject`. +/// +/// Unlike `BehaviorSubject` it can't terminate with error or completed. +public final class BehaviorRelay: ObservableType { + private let subject: BehaviorSubject + + /// Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Current value of behavior subject + public var value: Element { + // this try! is ok because subject can't error out or be disposed + return try! self.subject.value() + } + + /// Initializes behavior relay with initial value. + public init(value: Element) { + self.subject = BehaviorSubject(value: value) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/Pods/RxRelay/RxRelay/Observable+Bind.swift b/Pods/RxRelay/RxRelay/Observable+Bind.swift new file mode 100644 index 0000000..7a2efc7 --- /dev/null +++ b/Pods/RxRelay/RxRelay/Observable+Bind.swift @@ -0,0 +1,149 @@ +// +// Observable+Bind.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +extension ObservableType { + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter to: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: PublishRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to publish relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target publish relays for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [PublishRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to publish relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter to: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: BehaviorRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to behavior relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target behavior relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [BehaviorRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + + - parameter to: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + public func bind(to relays: ReplayRelay...) -> Disposable { + self.map { $0 as Element? }.bind(to: relays) + } + + /** + Creates new subscription and sends elements to replay relay(s). + In case error occurs in debug mode, `fatalError` will be raised. + In case error occurs in release mode, `error` will be logged. + - parameter to: Target replay relay for sequence elements. + - returns: Disposable object that can be used to unsubscribe the observer. + */ + private func bind(to relays: [ReplayRelay]) -> Disposable { + subscribe { e in + switch e { + case let .next(element): + relays.forEach { + $0.accept(element) + } + case let .error(error): + rxFatalErrorInDebug("Binding error to behavior relay: \(error)") + case .completed: + break + } + } + } +} diff --git a/Pods/RxRelay/RxRelay/PublishRelay.swift b/Pods/RxRelay/RxRelay/PublishRelay.swift new file mode 100644 index 0000000..a9c8ac4 --- /dev/null +++ b/Pods/RxRelay/RxRelay/PublishRelay.swift @@ -0,0 +1,36 @@ +// +// PublishRelay.swift +// RxRelay +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// PublishRelay is a wrapper for `PublishSubject`. +/// +/// Unlike `PublishSubject` it can't terminate with error or completed. +public final class PublishRelay: ObservableType { + private let subject: PublishSubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + /// Initializes with internal empty subject. + public init() { + self.subject = PublishSubject() + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObservable() + } +} diff --git a/Pods/RxRelay/RxRelay/ReplayRelay.swift b/Pods/RxRelay/RxRelay/ReplayRelay.swift new file mode 100644 index 0000000..3cc87cd --- /dev/null +++ b/Pods/RxRelay/RxRelay/ReplayRelay.swift @@ -0,0 +1,50 @@ +// +// ReplayRelay.swift +// RxRelay +// +// Created by Zsolt Kovacs on 12/22/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import RxSwift + +/// ReplayRelay is a wrapper for `ReplaySubject`. +/// +/// Unlike `ReplaySubject` it can't terminate with an error or complete. +public final class ReplayRelay: ObservableType { + private let subject: ReplaySubject + + // Accepts `event` and emits it to subscribers + public func accept(_ event: Element) { + self.subject.onNext(event) + } + + private init(subject: ReplaySubject) { + self.subject = subject + } + + /// Creates new instance of `ReplayRelay` that replays at most `bufferSize` last elements sent to it. + /// + /// - parameter bufferSize: Maximal number of elements to replay to observers after subscription. + /// - returns: New instance of replay relay. + public static func create(bufferSize: Int) -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.create(bufferSize: bufferSize)) + } + + /// Creates a new instance of `ReplayRelay` that buffers all the sent to it. + /// To avoid filling up memory, developer needs to make sure that the use case will only ever store a 'reasonable' + /// number of elements. + public static func createUnbound() -> ReplayRelay { + ReplayRelay(subject: ReplaySubject.createUnbounded()) + } + + /// Subscribes observer + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.subject.subscribe(observer) + } + + /// - returns: Canonical interface for push style sequence + public func asObservable() -> Observable { + self.subject.asObserver() + } +} diff --git a/Pods/RxRelay/RxRelay/Utils.swift b/Pods/RxRelay/RxRelay/Utils.swift new file mode 100644 index 0000000..5954fb9 --- /dev/null +++ b/Pods/RxRelay/RxRelay/Utils.swift @@ -0,0 +1,17 @@ +// +// Utils.swift +// RxRelay +// +// Created by Shai Mishali on 09/04/2019. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} diff --git a/Pods/RxSwift/LICENSE.md b/Pods/RxSwift/LICENSE.md new file mode 100644 index 0000000..e32511b --- /dev/null +++ b/Pods/RxSwift/LICENSE.md @@ -0,0 +1,9 @@ +**The MIT License** +**Copyright © 2015 Krunoslav Zaher, Shai Mishali** +**All rights reserved.** + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Pods/RxSwift/Platform/AtomicInt.swift b/Pods/RxSwift/Platform/AtomicInt.swift new file mode 100644 index 0000000..98479fd --- /dev/null +++ b/Pods/RxSwift/Platform/AtomicInt.swift @@ -0,0 +1,71 @@ +// +// AtomicInt.swift +// Platform +// +// Created by Krunoslav Zaher on 10/28/18. +// Copyright © 2018 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +final class AtomicInt: NSLock { + fileprivate var value: Int32 + public init(_ value: Int32 = 0) { + self.value = value + } +} + +@discardableResult +@inline(__always) +func add(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value += value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func sub(_ this: AtomicInt, _ value: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value -= value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func fetchOr(_ this: AtomicInt, _ mask: Int32) -> Int32 { + this.lock() + let oldValue = this.value + this.value |= mask + this.unlock() + return oldValue +} + +@inline(__always) +func load(_ this: AtomicInt) -> Int32 { + this.lock() + let oldValue = this.value + this.unlock() + return oldValue +} + +@discardableResult +@inline(__always) +func increment(_ this: AtomicInt) -> Int32 { + add(this, 1) +} + +@discardableResult +@inline(__always) +func decrement(_ this: AtomicInt) -> Int32 { + sub(this, 1) +} + +@inline(__always) +func isFlagSet(_ this: AtomicInt, _ mask: Int32) -> Bool { + (load(this) & mask) != 0 +} diff --git a/Pods/RxSwift/Platform/DataStructures/Bag.swift b/Pods/RxSwift/Platform/DataStructures/Bag.swift new file mode 100644 index 0000000..5720a3b --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/Bag.swift @@ -0,0 +1,181 @@ +// +// Bag.swift +// Platform +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Swift + +let arrayDictionaryMaxSize = 30 + +struct BagKey { + /** + Unique identifier for object added to `Bag`. + + It's underlying type is UInt64. If we assume there in an idealized CPU that works at 4GHz, + it would take ~150 years of continuous running time for it to overflow. + */ + fileprivate let rawValue: UInt64 +} + +/** +Data structure that represents a bag of elements typed `T`. + +Single element can be stored multiple times. + +Time and space complexity of insertion and deletion is O(n). + +It is suitable for storing small number of elements. +*/ +struct Bag : CustomDebugStringConvertible { + /// Type of identifier for inserted elements. + typealias KeyType = BagKey + + typealias Entry = (key: BagKey, value: T) + + private var _nextKey: BagKey = BagKey(rawValue: 0) + + // data + + // first fill inline variables + var _key0: BagKey? + var _value0: T? + + // then fill "array dictionary" + var _pairs = ContiguousArray() + + // last is sparse dictionary + var _dictionary: [BagKey: T]? + + var _onlyFastPath = true + + /// Creates new empty `Bag`. + init() { + } + + /** + Inserts `value` into bag. + + - parameter element: Element to insert. + - returns: Key that can be used to remove element from bag. + */ + mutating func insert(_ element: T) -> BagKey { + let key = _nextKey + + _nextKey = BagKey(rawValue: _nextKey.rawValue &+ 1) + + if _key0 == nil { + _key0 = key + _value0 = element + return key + } + + _onlyFastPath = false + + if _dictionary != nil { + _dictionary![key] = element + return key + } + + if _pairs.count < arrayDictionaryMaxSize { + _pairs.append((key: key, value: element)) + return key + } + + _dictionary = [key: element] + + return key + } + + /// - returns: Number of elements in bag. + var count: Int { + let dictionaryCount: Int = _dictionary?.count ?? 0 + return (_value0 != nil ? 1 : 0) + _pairs.count + dictionaryCount + } + + /// Removes all elements from bag and clears capacity. + mutating func removeAll() { + _key0 = nil + _value0 = nil + + _pairs.removeAll(keepingCapacity: false) + _dictionary?.removeAll(keepingCapacity: false) + } + + /** + Removes element with a specific `key` from bag. + + - parameter key: Key that identifies element to remove from bag. + - returns: Element that bag contained, or nil in case element was already removed. + */ + mutating func removeKey(_ key: BagKey) -> T? { + if _key0 == key { + _key0 = nil + let value = _value0! + _value0 = nil + return value + } + + if let existingObject = _dictionary?.removeValue(forKey: key) { + return existingObject + } + + for i in 0 ..< _pairs.count where _pairs[i].key == key { + let value = _pairs[i].value + _pairs.remove(at: i) + return value + } + + return nil + } +} + +extension Bag { + /// A textual representation of `self`, suitable for debugging. + var debugDescription : String { + "\(self.count) elements in Bag" + } +} + +extension Bag { + /// Enumerates elements inside the bag. + /// + /// - parameter action: Enumeration closure. + func forEach(_ action: (T) -> Void) { + if _onlyFastPath { + if let value0 = _value0 { + action(value0) + } + return + } + + let value0 = _value0 + let dictionary = _dictionary + + if let value0 = value0 { + action(value0) + } + + for i in 0 ..< _pairs.count { + action(_pairs[i].value) + } + + if dictionary?.count ?? 0 > 0 { + for element in dictionary!.values { + action(element) + } + } + } +} + +extension BagKey: Hashable { + func hash(into hasher: inout Hasher) { + hasher.combine(rawValue) + } +} + +func ==(lhs: BagKey, rhs: BagKey) -> Bool { + lhs.rawValue == rhs.rawValue +} diff --git a/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift b/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift new file mode 100644 index 0000000..75d7bea --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/InfiniteSequence.swift @@ -0,0 +1,23 @@ +// +// InfiniteSequence.swift +// Platform +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Sequence that repeats `repeatedValue` infinite number of times. +struct InfiniteSequence : Sequence { + typealias Iterator = AnyIterator + + private let repeatedValue: Element + + init(repeatedValue: Element) { + self.repeatedValue = repeatedValue + } + + func makeIterator() -> Iterator { + let repeatedValue = self.repeatedValue + return AnyIterator { repeatedValue } + } +} diff --git a/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift b/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift new file mode 100644 index 0000000..9ed856b --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/PriorityQueue.swift @@ -0,0 +1,111 @@ +// +// PriorityQueue.swift +// Platform +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct PriorityQueue { + private let hasHigherPriority: (Element, Element) -> Bool + private let isEqual: (Element, Element) -> Bool + + private var elements = [Element]() + + init(hasHigherPriority: @escaping (Element, Element) -> Bool, isEqual: @escaping (Element, Element) -> Bool) { + self.hasHigherPriority = hasHigherPriority + self.isEqual = isEqual + } + + mutating func enqueue(_ element: Element) { + elements.append(element) + bubbleToHigherPriority(elements.count - 1) + } + + func peek() -> Element? { + elements.first + } + + var isEmpty: Bool { + elements.count == 0 + } + + mutating func dequeue() -> Element? { + guard let front = peek() else { + return nil + } + + removeAt(0) + + return front + } + + mutating func remove(_ element: Element) { + for i in 0 ..< elements.count { + if self.isEqual(elements[i], element) { + removeAt(i) + return + } + } + } + + private mutating func removeAt(_ index: Int) { + let removingLast = index == elements.count - 1 + if !removingLast { + elements.swapAt(index, elements.count - 1) + } + + _ = elements.popLast() + + if !removingLast { + bubbleToHigherPriority(index) + bubbleToLowerPriority(index) + } + } + + private mutating func bubbleToHigherPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + + while unbalancedIndex > 0 { + let parentIndex = (unbalancedIndex - 1) / 2 + guard self.hasHigherPriority(elements[unbalancedIndex], elements[parentIndex]) else { break } + elements.swapAt(unbalancedIndex, parentIndex) + unbalancedIndex = parentIndex + } + } + + private mutating func bubbleToLowerPriority(_ initialUnbalancedIndex: Int) { + precondition(initialUnbalancedIndex >= 0) + precondition(initialUnbalancedIndex < elements.count) + + var unbalancedIndex = initialUnbalancedIndex + while true { + let leftChildIndex = unbalancedIndex * 2 + 1 + let rightChildIndex = unbalancedIndex * 2 + 2 + + var highestPriorityIndex = unbalancedIndex + + if leftChildIndex < elements.count && self.hasHigherPriority(elements[leftChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = leftChildIndex + } + + if rightChildIndex < elements.count && self.hasHigherPriority(elements[rightChildIndex], elements[highestPriorityIndex]) { + highestPriorityIndex = rightChildIndex + } + + guard highestPriorityIndex != unbalancedIndex else { break } + elements.swapAt(highestPriorityIndex, unbalancedIndex) + + unbalancedIndex = highestPriorityIndex + } + } +} + +extension PriorityQueue : CustomDebugStringConvertible { + var debugDescription: String { + elements.debugDescription + } +} diff --git a/Pods/RxSwift/Platform/DataStructures/Queue.swift b/Pods/RxSwift/Platform/DataStructures/Queue.swift new file mode 100644 index 0000000..625d473 --- /dev/null +++ b/Pods/RxSwift/Platform/DataStructures/Queue.swift @@ -0,0 +1,148 @@ +// +// Queue.swift +// Platform +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Data structure that represents queue. + +Complexity of `enqueue`, `dequeue` is O(1) when number of operations is +averaged over N operations. + +Complexity of `peek` is O(1). +*/ +struct Queue: Sequence { + /// Type of generator. + typealias Generator = AnyIterator + + private let resizeFactor = 2 + + private var storage: ContiguousArray + private var innerCount = 0 + private var pushNextIndex = 0 + private let initialCapacity: Int + + /** + Creates new queue. + + - parameter capacity: Capacity of newly created queue. + */ + init(capacity: Int) { + initialCapacity = capacity + + storage = ContiguousArray(repeating: nil, count: capacity) + } + + private var dequeueIndex: Int { + let index = pushNextIndex - count + return index < 0 ? index + storage.count : index + } + + /// - returns: Is queue empty. + var isEmpty: Bool { count == 0 } + + /// - returns: Number of elements inside queue. + var count: Int { innerCount } + + /// - returns: Element in front of a list of elements to `dequeue`. + func peek() -> T { + precondition(count > 0) + + return storage[dequeueIndex]! + } + + mutating private func resizeTo(_ size: Int) { + var newStorage = ContiguousArray(repeating: nil, count: size) + + let count = self.count + + let dequeueIndex = self.dequeueIndex + let spaceToEndOfQueue = storage.count - dequeueIndex + + // first batch is from dequeue index to end of array + let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) + // second batch is wrapped from start of array to end of queue + let numberOfElementsInSecondBatch = count - countElementsInFirstBatch + + newStorage[0 ..< countElementsInFirstBatch] = storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] + newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = storage[0 ..< numberOfElementsInSecondBatch] + + self.innerCount = count + pushNextIndex = count + storage = newStorage + } + + /// Enqueues `element`. + /// + /// - parameter element: Element to enqueue. + mutating func enqueue(_ element: T) { + if count == storage.count { + resizeTo(Swift.max(storage.count, 1) * resizeFactor) + } + + storage[pushNextIndex] = element + pushNextIndex += 1 + innerCount += 1 + + if pushNextIndex >= storage.count { + pushNextIndex -= storage.count + } + } + + private mutating func dequeueElementOnly() -> T { + precondition(count > 0) + + let index = dequeueIndex + + defer { + storage[index] = nil + innerCount -= 1 + } + + return storage[index]! + } + + /// Dequeues element or throws an exception in case queue is empty. + /// + /// - returns: Dequeued element. + mutating func dequeue() -> T? { + if self.count == 0 { + return nil + } + + defer { + let downsizeLimit = storage.count / (resizeFactor * resizeFactor) + if count < downsizeLimit && downsizeLimit >= initialCapacity { + resizeTo(storage.count / resizeFactor) + } + } + + return dequeueElementOnly() + } + + /// - returns: Generator of contained elements. + func makeIterator() -> AnyIterator { + var i = dequeueIndex + var innerCount = count + + return AnyIterator { + if innerCount == 0 { + return nil + } + + defer { + innerCount -= 1 + i += 1 + } + + if i >= self.storage.count { + i -= self.storage.count + } + + return self.storage[i] + } + } +} diff --git a/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift b/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift new file mode 100644 index 0000000..aaf24ca --- /dev/null +++ b/Pods/RxSwift/Platform/DispatchQueue+Extensions.swift @@ -0,0 +1,21 @@ +// +// DispatchQueue+Extensions.swift +// Platform +// +// Created by Krunoslav Zaher on 10/22/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch + +extension DispatchQueue { + private static var token: DispatchSpecificKey<()> = { + let key = DispatchSpecificKey<()>() + DispatchQueue.main.setSpecific(key: key, value: ()) + return key + }() + + static var isMain: Bool { + DispatchQueue.getSpecific(key: token) != nil + } +} diff --git a/Pods/RxSwift/Platform/Platform.Darwin.swift b/Pods/RxSwift/Platform/Platform.Darwin.swift new file mode 100644 index 0000000..eacc194 --- /dev/null +++ b/Pods/RxSwift/Platform/Platform.Darwin.swift @@ -0,0 +1,35 @@ +// +// Platform.Darwin.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) + + import Darwin + import Foundation + + extension Thread { + static func setThreadLocalStorageValue(_ value: T?, forKey key: NSCopying) { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + if let newValue = value { + threadDictionary[key] = newValue + } + else { + threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: NSCopying) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxSwift/Platform/Platform.Linux.swift b/Pods/RxSwift/Platform/Platform.Linux.swift new file mode 100644 index 0000000..52a3e3a --- /dev/null +++ b/Pods/RxSwift/Platform/Platform.Linux.swift @@ -0,0 +1,32 @@ +// +// Platform.Linux.swift +// Platform +// +// Created by Krunoslav Zaher on 12/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) + + import Foundation + + extension Thread { + + static func setThreadLocalStorageValue(_ value: T?, forKey key: String) { + if let newValue = value { + Thread.current.threadDictionary[key] = newValue + } + else { + Thread.current.threadDictionary[key] = nil + } + } + + static func getThreadLocalStorageValueForKey(_ key: String) -> T? { + let currentThread = Thread.current + let threadDictionary = currentThread.threadDictionary + + return threadDictionary[key] as? T + } + } + +#endif diff --git a/Pods/RxSwift/Platform/RecursiveLock.swift b/Pods/RxSwift/Platform/RecursiveLock.swift new file mode 100644 index 0000000..10b9bbb --- /dev/null +++ b/Pods/RxSwift/Platform/RecursiveLock.swift @@ -0,0 +1,34 @@ +// +// RecursiveLock.swift +// Platform +// +// Created by Krunoslav Zaher on 12/18/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +#if TRACE_RESOURCES + class RecursiveLock: NSRecursiveLock { + override init() { + _ = Resources.incrementTotal() + super.init() + } + + override func lock() { + super.lock() + _ = Resources.incrementTotal() + } + + override func unlock() { + super.unlock() + _ = Resources.decrementTotal() + } + + deinit { + _ = Resources.decrementTotal() + } + } +#else + typealias RecursiveLock = NSRecursiveLock +#endif diff --git a/Pods/RxSwift/README.md b/Pods/RxSwift/README.md new file mode 100644 index 0000000..2033016 --- /dev/null +++ b/Pods/RxSwift/README.md @@ -0,0 +1,254 @@ +

+RxSwift Logo +
+Build Status +Supported Platforms: iOS, macOS, tvOS, watchOS & Linux +
+ + + +

+ +Rx is a [generic abstraction of computation](https://youtu.be/looJcaeboBY) expressed through `Observable` interface, which lets you broadcast and subscribe to values and other events from an `Observable` stream. + +RxSwift is the Swift-specific implementation of the [Reactive Extensions](http://reactivex.io) standard. + +

RxSwift Observable Example of a price constantly changing and updating the app's UI

+ +While this version aims to stay true to the original spirit and naming conventions of Rx, this projects also aims to provide a true Swift-first API for Rx APIs. + +Cross platform documentation can be found on [ReactiveX.io](http://reactivex.io/). + +Like other Rx implementation, RxSwift's intention is to enable easy composition of asynchronous operations and streams of data in the form of `Observable` objects and a suite of methods to transform and compose these pieces of asynchronous work. + +KVO observation, async operations, UI Events and other streams of data are all unified under [abstraction of sequence](Documentation/GettingStarted.md#observables-aka-sequences). This is the reason why Rx is so simple, elegant and powerful. + +## I came here because I want to ... + +###### ... understand + +* [why use rx?](Documentation/Why.md) +* [the basics, getting started with RxSwift](Documentation/GettingStarted.md) +* [traits](Documentation/Traits.md) - what are `Single`, `Completable`, `Maybe`, `Driver`, and `ControlProperty` ... and why do they exist? +* [testing](Documentation/UnitTests.md) +* [tips and common errors](Documentation/Tips.md) +* [debugging](Documentation/GettingStarted.md#debugging) +* [the math behind Rx](Documentation/MathBehindRx.md) +* [what are hot and cold observable sequences?](Documentation/HotAndColdObservables.md) + +###### ... install + +* Integrate RxSwift/RxCocoa with my app. [Installation Guide](#installation) + +###### ... hack around + +* with the example app. [Running Example App](Documentation/ExampleApp.md) +* with operators in playgrounds. [Playgrounds](Documentation/Playgrounds.md) + +###### ... interact + +* All of this is great, but it would be nice to talk with other people using RxSwift and exchange experiences.
[Join Slack Channel](http://slack.rxswift.org) +* Report a problem using the library. [Open an Issue With Bug Template](.github/ISSUE_TEMPLATE.md) +* Request a new feature. [Open an Issue With Feature Request Template](Documentation/NewFeatureRequestTemplate.md) +* Help out [Check out contribution guide](CONTRIBUTING.md) + +###### ... compare + +* [with Combine and ReactiveSwift](Documentation/ComparisonWithOtherLibraries.md). + +###### ... understand the structure + +RxSwift is as compositional as the asynchronous work it drives. The core unit is RxSwift itself, while other dependencies can be added for UI Work, testing, and more. + +It comprises five separate components depending on each other in the following way: + +```none +┌──────────────┐ ┌──────────────┐ +│ RxCocoa ├────▶ RxRelay │ +└───────┬──────┘ └──────┬───────┘ + │ │ +┌───────▼──────────────────▼───────┐ +│ RxSwift │ +└───────▲──────────────────▲───────┘ + │ │ +┌───────┴──────┐ ┌──────┴───────┐ +│ RxTest │ │ RxBlocking │ +└──────────────┘ └──────────────┘ +``` + +* **RxSwift**: The core of RxSwift, providing the Rx standard as (mostly) defined by [ReactiveX](https://reactivex.io). It has no other dependencies. +* **RxCocoa**: Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both `RxSwift` and `RxRelay`. +* **RxRelay**: Provides `PublishRelay`, `BehaviorRelay` and `ReplayRelay`, three [simple wrappers around Subjects](https://github.com/ReactiveX/RxSwift/blob/main/Documentation/Subjects.md#relays). It depends on `RxSwift`. +* **RxTest** and **RxBlocking**: Provides testing capabilities for Rx-based systems. It depends on `RxSwift`. + +## Usage + + + + + + + + + + + + + + + + + + + +
Here's an exampleIn Action
Define search for GitHub repositories ...
+let searchResults = searchBar.rx.text.orEmpty
+    .throttle(.milliseconds(300), scheduler: MainScheduler.instance)
+    .distinctUntilChanged()
+    .flatMapLatest { query -> Observable<[Repository]> in
+        if query.isEmpty {
+            return .just([])
+        }
+        return searchGitHub(query)
+            .catchAndReturn([])
+    }
+    .observe(on: MainScheduler.instance)
... then bind the results to your tableview
+searchResults
+    .bind(to: tableView.rx.items(cellIdentifier: "Cell")) {
+        (index, repository: Repository, cell) in
+        cell.textLabel?.text = repository.name
+        cell.detailTextLabel?.text = repository.url
+    }
+    .disposed(by: disposeBag)
+ + +## Requirements + +* Xcode 12.x +* Swift 5.x + +For Xcode 11 and below, [use RxSwift 5.x](https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1). + +## Installation + +RxSwift doesn't contain any external dependencies. + +These are currently the supported installation options: + +### Manual + +Open Rx.xcworkspace, choose `RxExample` and hit run. This method will build everything and run the sample app + +### [CocoaPods](https://guides.cocoapods.org/using/using-cocoapods.html) + +```ruby +# Podfile +use_frameworks! + +target 'YOUR_TARGET_NAME' do + pod 'RxSwift', '6.2.0' + pod 'RxCocoa', '6.2.0' +end + +# RxTest and RxBlocking make the most sense in the context of unit/integration tests +target 'YOUR_TESTING_TARGET' do + pod 'RxBlocking', '6.2.0' + pod 'RxTest', '6.2.0' +end +``` + +Replace `YOUR_TARGET_NAME` and then, in the `Podfile` directory, type: + +```bash +$ pod install +``` + +### XCFrameworks + +Each release starting with RxSwift 6 includes `*.xcframework` framework binaries. + +Simply drag the needed framework binaries to your **Frameworks, Libraries, and Embedded Content** section under your target's **General** tab. + +> **Note**: If you're using `RxCocoa`, be sure to also drag **RxCocoaRuntime.xcframework** before importing `RxCocoa`. + +XCFrameworks instructions + +### [Carthage](https://github.com/Carthage/Carthage) + +Add this to `Cartfile` + +``` +github "ReactiveX/RxSwift" "6.2.0" +``` + +```bash +$ carthage update +``` + +#### Carthage as a Static Library + +Carthage defaults to building RxSwift as a Dynamic Library. + +If you wish to build RxSwift as a Static Library using Carthage you may use the script below to manually modify the framework type before building with Carthage: + +```bash +carthage update RxSwift --platform iOS --no-build +sed -i -e 's/MACH_O_TYPE = mh_dylib/MACH_O_TYPE = staticlib/g' Carthage/Checkouts/RxSwift/Rx.xcodeproj/project.pbxproj +carthage build RxSwift --platform iOS +``` + +### [Swift Package Manager](https://github.com/apple/swift-package-manager) + +> **Note**: There is a critical cross-dependency bug affecting many projects including RxSwift in Swift Package Manager. We've [filed a bug (SR-12303)](https://bugs.swift.org/browse/SR-12303) in early 2020 but have no answer yet. Your mileage may vary. A partial workaround can be found [here](https://github.com/ReactiveX/RxSwift/issues/2127#issuecomment-717830502). + +Create a `Package.swift` file. + +```swift +// swift-tools-version:5.0 + +import PackageDescription + +let package = Package( + name: "RxTestProject", + dependencies: [ + .package(url: "https://github.com/ReactiveX/RxSwift.git", .exact("6.2.0")) + ], + targets: [ + .target(name: "RxTestProject", dependencies: ["RxSwift", "RxCocoa"]) + ] +) +``` + +```bash +$ swift build +``` + +To build or test a module with RxTest dependency, set `TEST=1`. + +```bash +$ TEST=1 swift test +``` + +### Manually using git submodules + +* Add RxSwift as a submodule + +```bash +$ git submodule add git@github.com:ReactiveX/RxSwift.git +``` + +* Drag `Rx.xcodeproj` into Project Navigator +* Go to `Project > Targets > Build Phases > Link Binary With Libraries`, click `+` and select `RxSwift`, `RxCocoa` and `RxRelay` targets + +## References + +* [http://reactivex.io/](http://reactivex.io/) +* [Reactive Extensions GitHub (GitHub)](https://github.com/Reactive-Extensions) +* [RxSwift RayWenderlich.com Book](https://store.raywenderlich.com/products/rxswift-reactive-programming-with-swift) +* [RxSwift: Debunking the myth of hard (YouTube)](https://www.youtube.com/watch?v=GdvLP0ZAhhc) +* [Boxue.io RxSwift Online Course](https://boxueio.com/series/rxswift-101) (Chinese 🇨🇳) +* [Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx) (video)](https://youtu.be/looJcaeboBY) +* [Reactive Programming Overview (Jafar Husain from Netflix)](https://youtu.be/-8Y1-lE6NSA) +* [Subject/Observer is Dual to Iterator (paper)](http://csl.stanford.edu/~christos/pldi2010.fit/meijer.duality.pdf) +* [Rx standard sequence operators visualized (visualization tool)](http://rxmarbles.com/) +* [Haskell](https://www.haskell.org/) diff --git a/Pods/RxSwift/RxSwift/AnyObserver.swift b/Pods/RxSwift/RxSwift/AnyObserver.swift new file mode 100644 index 0000000..e92cc81 --- /dev/null +++ b/Pods/RxSwift/RxSwift/AnyObserver.swift @@ -0,0 +1,69 @@ +// +// AnyObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObserverType`. +/// +/// Forwards operations to an arbitrary underlying observer with the same `Element` type, hiding the specifics of the underlying observer type. +public struct AnyObserver : ObserverType { + /// Anonymous event handler type. + public typealias EventHandler = (Event) -> Void + + private let observer: EventHandler + + /// Construct an instance whose `on(event)` calls `eventHandler(event)` + /// + /// - parameter eventHandler: Event handler that observes sequences events. + public init(eventHandler: @escaping EventHandler) { + self.observer = eventHandler + } + + /// Construct an instance whose `on(event)` calls `observer.on(event)` + /// + /// - parameter observer: Observer that receives sequence events. + public init(_ observer: Observer) where Observer.Element == Element { + self.observer = observer.on + } + + /// Send `event` to this observer. + /// + /// - parameter event: Event instance. + public func on(_ event: Event) { + self.observer(event) + } + + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + self + } +} + +extension AnyObserver { + /// Collection of `AnyObserver`s + typealias s = Bag<(Event) -> Void> +} + +extension ObserverType { + /// Erases type of observer and returns canonical observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(self) + } + + /// Transforms observer of type R to type E using custom transform method. + /// Each event sent to result observer is transformed and sent to `self`. + /// + /// - returns: observer that transforms events. + public func mapObserver(_ transform: @escaping (Result) throws -> Element) -> AnyObserver { + AnyObserver { e in + self.on(e.map(transform)) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Binder.swift b/Pods/RxSwift/RxSwift/Binder.swift new file mode 100644 index 0000000..1aae095 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Binder.swift @@ -0,0 +1,59 @@ +// +// Binder.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/** + Observer that enforces interface binding rules: + * can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged) + * ensures binding is performed on a specific scheduler + + `Binder` doesn't retain target and in case target is released, element isn't bound. + + By default it binds elements on main scheduler. + */ +public struct Binder: ObserverType { + public typealias Element = Value + + private let binding: (Event) -> Void + + /// Initializes `Binder` + /// + /// - parameter target: Target object. + /// - parameter scheduler: Scheduler used to bind the events. + /// - parameter binding: Binding logic. + public init(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> Void) { + weak var weakTarget = target + + self.binding = { event in + switch event { + case .next(let element): + _ = scheduler.schedule(element) { element in + if let target = weakTarget { + binding(target, element) + } + return Disposables.create() + } + case .error(let error): + rxFatalErrorInDebug("Binding error: \(error)") + case .completed: + break + } + } + } + + /// Binds next element to owner view as described in `binding`. + public func on(_ event: Event) { + self.binding(event) + } + + /// Erases type of observer. + /// + /// - returns: type erased observer. + public func asObserver() -> AnyObserver { + AnyObserver(eventHandler: self.on) + } +} diff --git a/Pods/RxSwift/RxSwift/Cancelable.swift b/Pods/RxSwift/RxSwift/Cancelable.swift new file mode 100644 index 0000000..1fa7a67 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Cancelable.swift @@ -0,0 +1,13 @@ +// +// Cancelable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents disposable resource with state tracking. +public protocol Cancelable : Disposable { + /// Was resource disposed. + var isDisposed: Bool { get } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift b/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift new file mode 100644 index 0000000..502597e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/AsyncLock.swift @@ -0,0 +1,100 @@ +// +// AsyncLock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +In case nobody holds this lock, the work will be queued and executed immediately +on thread that is requesting lock. + +In case there is somebody currently holding that lock, action will be enqueued. +When owned of the lock finishes with it's processing, it will also execute +and pending work. + +That means that enqueued work could possibly be executed later on a different thread. +*/ +final class AsyncLock + : Disposable + , Lock + , SynchronizedDisposeType { + typealias Action = () -> Void + + private var _lock = SpinLock() + + private var queue: Queue = Queue(capacity: 0) + + private var isExecuting: Bool = false + private var hasFaulted: Bool = false + + // lock { + func lock() { + self._lock.lock() + } + + func unlock() { + self._lock.unlock() + } + // } + + private func enqueue(_ action: I) -> I? { + self.lock(); defer { self.unlock() } + if self.hasFaulted { + return nil + } + + if self.isExecuting { + self.queue.enqueue(action) + return nil + } + + self.isExecuting = true + + return action + } + + private func dequeue() -> I? { + self.lock(); defer { self.unlock() } + if !self.queue.isEmpty { + return self.queue.dequeue() + } + else { + self.isExecuting = false + return nil + } + } + + func invoke(_ action: I) { + let firstEnqueuedAction = self.enqueue(action) + + if let firstEnqueuedAction = firstEnqueuedAction { + firstEnqueuedAction.invoke() + } + else { + // action is enqueued, it's somebody else's concern now + return + } + + while true { + let nextAction = self.dequeue() + + if let nextAction = nextAction { + nextAction.invoke() + } + else { + return + } + } + } + + func dispose() { + self.synchronizedDispose() + } + + func synchronized_dispose() { + self.queue = Queue(capacity: 0) + self.hasFaulted = true + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/Lock.swift b/Pods/RxSwift/RxSwift/Concurrency/Lock.swift new file mode 100644 index 0000000..7232f23 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/Lock.swift @@ -0,0 +1,23 @@ +// +// Lock.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol Lock { + func lock() + func unlock() +} + +// https://lists.swift.org/pipermail/swift-dev/Week-of-Mon-20151214/000321.html +typealias SpinLock = RecursiveLock + +extension RecursiveLock : Lock { + @inline(__always) + final func performLocked(_ action: () -> T) -> T { + self.lock(); defer { self.unlock() } + return action() + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift b/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift new file mode 100644 index 0000000..8a98007 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/LockOwnerType.swift @@ -0,0 +1,16 @@ +// +// LockOwnerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol LockOwnerType: AnyObject, Lock { + var lock: RecursiveLock { get } +} + +extension LockOwnerType { + func lock() { self.lock.lock() } + func unlock() { self.lock.unlock() } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift new file mode 100644 index 0000000..527a2fb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedDisposeType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedDisposeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedDisposeType: AnyObject, Disposable, Lock { + func synchronized_dispose() +} + +extension SynchronizedDisposeType { + func synchronizedDispose() { + self.lock(); defer { self.unlock() } + self.synchronized_dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift new file mode 100644 index 0000000..19168d7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedOnType.swift @@ -0,0 +1,18 @@ +// +// SynchronizedOnType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedOnType: AnyObject, ObserverType, Lock { + func synchronized_on(_ event: Event) +} + +extension SynchronizedOnType { + func synchronizedOn(_ event: Event) { + self.lock(); defer { self.unlock() } + self.synchronized_on(event) + } +} diff --git a/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift new file mode 100644 index 0000000..988b86f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Concurrency/SynchronizedUnsubscribeType.swift @@ -0,0 +1,13 @@ +// +// SynchronizedUnsubscribeType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol SynchronizedUnsubscribeType: AnyObject { + associatedtype DisposeKey + + func synchronizedUnsubscribe(_ disposeKey: DisposeKey) +} diff --git a/Pods/RxSwift/RxSwift/ConnectableObservableType.swift b/Pods/RxSwift/RxSwift/ConnectableObservableType.swift new file mode 100644 index 0000000..52bf93c --- /dev/null +++ b/Pods/RxSwift/RxSwift/ConnectableObservableType.swift @@ -0,0 +1,19 @@ +// +// ConnectableObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents an observable sequence wrapper that can be connected and disconnected from its underlying observable sequence. +*/ +public protocol ConnectableObservableType : ObservableType { + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + func connect() -> Disposable +} diff --git a/Pods/RxSwift/RxSwift/Date+Dispatch.swift b/Pods/RxSwift/RxSwift/Date+Dispatch.swift new file mode 100644 index 0000000..90f70c5 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Date+Dispatch.swift @@ -0,0 +1,64 @@ +// +// Date+Dispatch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/14/19. +// Copyright © 2019 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +extension DispatchTimeInterval { + var convertToSecondsFactor: Double { + switch self { + case .nanoseconds: return 1_000_000_000.0 + case .microseconds: return 1_000_000.0 + case .milliseconds: return 1_000.0 + case .seconds: return 1.0 + case .never: fatalError() + @unknown default: fatalError() + } + } + + func map(_ transform: (Int, Double) -> Int) -> DispatchTimeInterval { + switch self { + case .nanoseconds(let value): return .nanoseconds(transform(value, 1_000_000_000.0)) + case .microseconds(let value): return .microseconds(transform(value, 1_000_000.0)) + case .milliseconds(let value): return .milliseconds(transform(value, 1_000.0)) + case .seconds(let value): return .seconds(transform(value, 1.0)) + case .never: return .never + @unknown default: fatalError() + } + } + + var isNow: Bool { + switch self { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): return value == 0 + case .never: return false + @unknown default: fatalError() + } + } + + internal func reduceWithSpanBetween(earlierDate: Date, laterDate: Date) -> DispatchTimeInterval { + return self.map { value, factor in + let interval = laterDate.timeIntervalSince(earlierDate) + let remainder = Double(value) - interval * factor + guard remainder > 0 else { return 0 } + return Int(remainder.rounded(.toNearestOrAwayFromZero)) + } + } +} + +extension Date { + + internal func addingDispatchInterval(_ dispatchInterval: DispatchTimeInterval) -> Date { + switch dispatchInterval { + case .nanoseconds(let value), .microseconds(let value), .milliseconds(let value), .seconds(let value): + return self.addingTimeInterval(TimeInterval(value) / dispatchInterval.convertToSecondsFactor) + case .never: return Date.distantFuture + @unknown default: fatalError() + } + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposable.swift b/Pods/RxSwift/RxSwift/Disposable.swift new file mode 100644 index 0000000..b79c77a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposable.swift @@ -0,0 +1,13 @@ +// +// Disposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource. +public protocol Disposable { + /// Dispose resource. + func dispose() +} diff --git a/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift new file mode 100644 index 0000000..591aafa --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/AnonymousDisposable.swift @@ -0,0 +1,59 @@ +// +// AnonymousDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an Action-based disposable. +/// +/// When dispose method is called, disposal action will be dereferenced. +private final class AnonymousDisposable : DisposeBase, Cancelable { + public typealias DisposeAction = () -> Void + + private let disposed = AtomicInt(0) + private var disposeAction: DisposeAction? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter disposeAction: Disposal action which will be run upon calling `dispose`. + private init(_ disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + // Non-deprecated version of the constructor, used by `Disposables.create(with:)` + fileprivate init(disposeAction: @escaping DisposeAction) { + self.disposeAction = disposeAction + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + fileprivate func dispose() { + if fetchOr(self.disposed, 1) == 0 { + if let action = self.disposeAction { + self.disposeAction = nil + action() + } + } + } +} + +extension Disposables { + + /// Constructs a new disposable with the given action used for disposal. + /// + /// - parameter dispose: Disposal action which will be run upon calling `dispose`. + public static func create(with dispose: @escaping () -> Void) -> Cancelable { + AnonymousDisposable(disposeAction: dispose) + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift new file mode 100644 index 0000000..a3d4937 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/BinaryDisposable.swift @@ -0,0 +1,53 @@ +// +// BinaryDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents two disposable resources that are disposed together. +private final class BinaryDisposable : DisposeBase, Cancelable { + + private let disposed = AtomicInt(0) + + // state + private var disposable1: Disposable? + private var disposable2: Disposable? + + /// - returns: Was resource disposed. + var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /// Constructs new binary disposable from two disposables. + /// + /// - parameter disposable1: First disposable + /// - parameter disposable2: Second disposable + init(_ disposable1: Disposable, _ disposable2: Disposable) { + self.disposable1 = disposable1 + self.disposable2 = disposable2 + super.init() + } + + /// Calls the disposal action if and only if the current instance hasn't been disposed yet. + /// + /// After invoking disposal action, disposal action will be dereferenced. + func dispose() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable1?.dispose() + self.disposable2?.dispose() + self.disposable1 = nil + self.disposable2 = nil + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable) -> Cancelable { + BinaryDisposable(disposable1, disposable2) + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift new file mode 100644 index 0000000..c7d73e9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/BooleanDisposable.swift @@ -0,0 +1,33 @@ +// +// BooleanDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that can be checked for disposal status. +public final class BooleanDisposable : Cancelable { + + internal static let BooleanDisposableTrue = BooleanDisposable(isDisposed: true) + private var disposed = false + + /// Initializes a new instance of the `BooleanDisposable` class + public init() { + } + + /// Initializes a new instance of the `BooleanDisposable` class with given value + public init(isDisposed: Bool) { + self.disposed = isDisposed + } + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Sets the status to disposed, which can be observer through the `isDisposed` property. + public func dispose() { + self.disposed = true + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift new file mode 100644 index 0000000..bb4efe6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/CompositeDisposable.swift @@ -0,0 +1,147 @@ +// +// CompositeDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a group of disposable resources that are disposed together. +public final class CompositeDisposable : DisposeBase, Cancelable { + /// Key used to remove disposable from composite disposable + public struct DisposeKey { + fileprivate let key: BagKey + fileprivate init(key: BagKey) { + self.key = key + } + } + + private var lock = SpinLock() + + // state + private var disposables: Bag? = Bag() + + public var isDisposed: Bool { + self.lock.performLocked { self.disposables == nil } + } + + public override init() { + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { + // This overload is here to make sure we are using optimized version up to 4 arguments. + _ = self.disposables!.insert(disposable1) + _ = self.disposables!.insert(disposable2) + _ = self.disposables!.insert(disposable3) + _ = self.disposables!.insert(disposable4) + + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /// Initializes a new instance of composite disposable with the specified number of disposables. + public init(disposables: [Disposable]) { + for disposable in disposables { + _ = self.disposables!.insert(disposable) + } + } + + /** + Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. + + - parameter disposable: Disposable to add. + - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already + disposed `nil` will be returned. + */ + public func insert(_ disposable: Disposable) -> DisposeKey? { + let key = self._insert(disposable) + + if key == nil { + disposable.dispose() + } + + return key + } + + private func _insert(_ disposable: Disposable) -> DisposeKey? { + self.lock.performLocked { + let bagKey = self.disposables?.insert(disposable) + return bagKey.map(DisposeKey.init) + } + } + + /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. + public var count: Int { + self.lock.performLocked { self.disposables?.count ?? 0 } + } + + /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. + /// + /// - parameter disposeKey: Key used to identify disposable to be removed. + public func remove(for disposeKey: DisposeKey) { + self._remove(for: disposeKey)?.dispose() + } + + private func _remove(for disposeKey: DisposeKey) -> Disposable? { + self.lock.performLocked { self.disposables?.removeKey(disposeKey.key) } + } + + /// Disposes all disposables in the group and removes them from the group. + public func dispose() { + if let disposables = self._dispose() { + disposeAll(in: disposables) + } + } + + private func _dispose() -> Bag? { + self.lock.performLocked { + let current = self.disposables + self.disposables = nil + return current + } + } +} + +extension Disposables { + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { + CompositeDisposable(disposable1, disposable2, disposable3) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { + var disposables = disposables + disposables.append(disposable1) + disposables.append(disposable2) + disposables.append(disposable3) + return CompositeDisposable(disposables: disposables) + } + + /// Creates a disposable with the given disposables. + public static func create(_ disposables: [Disposable]) -> Cancelable { + switch disposables.count { + case 2: + return Disposables.create(disposables[0], disposables[1]) + default: + return CompositeDisposable(disposables: disposables) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/Disposables.swift b/Pods/RxSwift/RxSwift/Disposables/Disposables.swift new file mode 100644 index 0000000..8cd6e28 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/Disposables.swift @@ -0,0 +1,13 @@ +// +// Disposables.swift +// RxSwift +// +// Created by Mohsen Ramezanpoor on 01/08/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/// A collection of utility methods for common disposable operations. +public struct Disposables { + private init() {} +} + diff --git a/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift b/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift new file mode 100644 index 0000000..1a673bc --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/DisposeBag.swift @@ -0,0 +1,144 @@ +// +// DisposeBag.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension Disposable { + /// Adds `self` to `bag` + /// + /// - parameter bag: `DisposeBag` to add `self` to. + public func disposed(by bag: DisposeBag) { + bag.insert(self) + } +} + +/** +Thread safe bag that disposes added disposables on `deinit`. + +This returns ARC (RAII) like resource management to `RxSwift`. + +In case contained disposables need to be disposed, just put a different dispose bag +or create a new one in its place. + + self.existingDisposeBag = DisposeBag() + +In case explicit disposal is necessary, there is also `CompositeDisposable`. +*/ +public final class DisposeBag: DisposeBase { + + private var lock = SpinLock() + + // state + private var disposables = [Disposable]() + private var isDisposed = false + + /// Constructs new empty dispose bag. + public override init() { + super.init() + } + + /// Adds `disposable` to be disposed when dispose bag is being deinited. + /// + /// - parameter disposable: Disposable to add. + public func insert(_ disposable: Disposable) { + self._insert(disposable)?.dispose() + } + + private func _insert(_ disposable: Disposable) -> Disposable? { + self.lock.performLocked { + if self.isDisposed { + return disposable + } + + self.disposables.append(disposable) + + return nil + } + } + + /// This is internal on purpose, take a look at `CompositeDisposable` instead. + private func dispose() { + let oldDisposables = self._dispose() + + for disposable in oldDisposables { + disposable.dispose() + } + } + + private func _dispose() -> [Disposable] { + self.lock.performLocked { + let disposables = self.disposables + + self.disposables.removeAll(keepingCapacity: false) + self.isDisposed = true + + return disposables + } + } + + deinit { + self.dispose() + } +} + +extension DisposeBag { + /// Convenience init allows a list of disposables to be gathered for disposal. + public convenience init(disposing disposables: Disposable...) { + self.init() + self.disposables += disposables + } + + /// Convenience init which utilizes a function builder to let you pass in a list of + /// disposables to make a DisposeBag of. + public convenience init(@DisposableBuilder builder: () -> [Disposable]) { + self.init(disposing: builder()) + } + + /// Convenience init allows an array of disposables to be gathered for disposal. + public convenience init(disposing disposables: [Disposable]) { + self.init() + self.disposables += disposables + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(_ disposables: Disposable...) { + self.insert(disposables) + } + + /// Convenience function allows a list of disposables to be gathered for disposal. + public func insert(@DisposableBuilder builder: () -> [Disposable]) { + self.insert(builder()) + } + + /// Convenience function allows an array of disposables to be gathered for disposal. + public func insert(_ disposables: [Disposable]) { + self.lock.performLocked { + if self.isDisposed { + disposables.forEach { $0.dispose() } + } else { + self.disposables += disposables + } + } + } + + /// A function builder accepting a list of Disposables and returning them as an array. + #if swift(>=5.4) + @resultBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #else + @_functionBuilder + public struct DisposableBuilder { + public static func buildBlock(_ disposables: Disposable...) -> [Disposable] { + return disposables + } + } + #endif + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift b/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift new file mode 100644 index 0000000..0d4b2fb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/DisposeBase.swift @@ -0,0 +1,22 @@ +// +// DisposeBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for all disposables. +public class DisposeBase { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift new file mode 100644 index 0000000..dd436ba --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/NopDisposable.swift @@ -0,0 +1,30 @@ +// +// NopDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable that does nothing on disposal. +/// +/// Nop = No Operation +private struct NopDisposable : Disposable { + + fileprivate static let noOp: Disposable = NopDisposable() + + private init() { + + } + + /// Does nothing. + public func dispose() { + } +} + +extension Disposables { + /** + Creates a disposable that does nothing on disposal. + */ + static public func create() -> Disposable { NopDisposable.noOp } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift new file mode 100644 index 0000000..a59f778 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/RefCountDisposable.swift @@ -0,0 +1,112 @@ +// +// RefCountDisposable.swift +// RxSwift +// +// Created by Junior B. on 10/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. +public final class RefCountDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + private var disposable = nil as Disposable? + private var primaryDisposed = false + private var count = 0 + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.lock.performLocked { self.disposable == nil } + } + + /// Initializes a new instance of the `RefCountDisposable`. + public init(disposable: Disposable) { + self.disposable = disposable + super.init() + } + + /** + Holds a dependent disposable that when disposed decreases the refcount on the underlying disposable. + + When getter is called, a dependent disposable contributing to the reference count that manages the underlying disposable's lifetime is returned. + */ + public func retain() -> Disposable { + self.lock.performLocked { + if self.disposable != nil { + do { + _ = try incrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable increment failed") + } + + return RefCountInnerDisposable(self) + } else { + return Disposables.create() + } + } + } + + /// Disposes the underlying disposable only when all dependent disposables have been disposed. + public func dispose() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable, !self.primaryDisposed { + self.primaryDisposed = true + + if self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } + + fileprivate func release() { + let oldDisposable: Disposable? = self.lock.performLocked { + if let oldDisposable = self.disposable { + do { + _ = try decrementChecked(&self.count) + } catch { + rxFatalError("RefCountDisposable decrement on release failed") + } + + guard self.count >= 0 else { + rxFatalError("RefCountDisposable counter is lower than 0") + } + + if self.primaryDisposed && self.count == 0 { + self.disposable = nil + return oldDisposable + } + } + + return nil + } + + if let disposable = oldDisposable { + disposable.dispose() + } + } +} + +internal final class RefCountInnerDisposable: DisposeBase, Disposable +{ + private let parent: RefCountDisposable + private let isDisposed = AtomicInt(0) + + init(_ parent: RefCountDisposable) { + self.parent = parent + super.init() + } + + internal func dispose() + { + if fetchOr(self.isDisposed, 1) == 0 { + self.parent.release() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift new file mode 100644 index 0000000..2cf997b --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift @@ -0,0 +1,50 @@ +// +// ScheduledDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in + sd.disposeInner() + return Disposables.create() +} + +/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler. +public final class ScheduledDisposable : Cancelable { + public let scheduler: ImmediateSchedulerType + + private let disposed = AtomicInt(0) + + // state + private var disposable: Disposable? + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + /** + Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`. + + - parameter scheduler: Scheduler where the disposable resource will be disposed on. + - parameter disposable: Disposable resource to dispose on the given scheduler. + */ + public init(scheduler: ImmediateSchedulerType, disposable: Disposable) { + self.scheduler = scheduler + self.disposable = disposable + } + + /// Disposes the wrapped disposable on the provided scheduler. + public func dispose() { + _ = self.scheduler.schedule(self, action: disposeScheduledDisposable) + } + + func disposeInner() { + if fetchOr(self.disposed, 1) == 0 { + self.disposable!.dispose() + self.disposable = nil + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift new file mode 100644 index 0000000..ef4690d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SerialDisposable.swift @@ -0,0 +1,73 @@ +// +// SerialDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. +public final class SerialDisposable : DisposeBase, Cancelable { + private var lock = SpinLock() + + // state + private var current = nil as Disposable? + private var disposed = false + + /// - returns: Was resource disposed. + public var isDisposed: Bool { + self.disposed + } + + /// Initializes a new instance of the `SerialDisposable`. + override public init() { + super.init() + } + + /** + Gets or sets the underlying disposable. + + Assigning this property disposes the previous disposable object. + + If the `SerialDisposable` has already been disposed, assignment to this property causes immediate disposal of the given disposable object. + */ + public var disposable: Disposable { + get { + self.lock.performLocked { + self.current ?? Disposables.create() + } + } + set (newDisposable) { + let disposable: Disposable? = self.lock.performLocked { + if self.isDisposed { + return newDisposable + } + else { + let toDispose = self.current + self.current = newDisposable + return toDispose + } + } + + if let disposable = disposable { + disposable.dispose() + } + } + } + + /// Disposes the underlying disposable as well as all future replacements. + public func dispose() { + self._dispose()?.dispose() + } + + private func _dispose() -> Disposable? { + self.lock.performLocked { + guard !self.isDisposed else { return nil } + + self.disposed = true + let current = self.current + self.current = nil + return current + } + } +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift new file mode 100644 index 0000000..d7307d6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SingleAssignmentDisposable.swift @@ -0,0 +1,70 @@ +// +// SingleAssignmentDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** +Represents a disposable resource which only allows a single assignment of its underlying disposable resource. + +If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an exception. +*/ +public final class SingleAssignmentDisposable : DisposeBase, Cancelable { + + private enum DisposeState: Int32 { + case disposed = 1 + case disposableSet = 2 + } + + // state + private let state = AtomicInt(0) + private var disposable = nil as Disposable? + + /// - returns: A value that indicates whether the object is disposed. + public var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + /// Initializes a new instance of the `SingleAssignmentDisposable`. + public override init() { + super.init() + } + + /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined. + /// + /// **Throws exception if the `SingleAssignmentDisposable` has already been assigned to.** + public func setDisposable(_ disposable: Disposable) { + self.disposable = disposable + + let previousState = fetchOr(self.state, DisposeState.disposableSet.rawValue) + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + rxFatalError("oldState.disposable != nil") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + disposable.dispose() + self.disposable = nil + } + } + + /// Disposes the underlying disposable. + public func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.disposableSet.rawValue) != 0 { + guard let disposable = self.disposable else { + rxFatalError("Disposable not set") + } + disposable.dispose() + self.disposable = nil + } + } + +} diff --git a/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift b/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift new file mode 100644 index 0000000..a406c84 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Disposables/SubscriptionDisposable.swift @@ -0,0 +1,21 @@ +// +// SubscriptionDisposable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct SubscriptionDisposable : Disposable { + private let key: T.DisposeKey + private weak var owner: T? + + init(owner: T, key: T.DisposeKey) { + self.owner = owner + self.key = key + } + + func dispose() { + self.owner?.synchronizedUnsubscribe(self.key) + } +} diff --git a/Pods/RxSwift/RxSwift/Errors.swift b/Pods/RxSwift/RxSwift/Errors.swift new file mode 100644 index 0000000..d2d2917 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Errors.swift @@ -0,0 +1,52 @@ +// +// Errors.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +let RxErrorDomain = "RxErrorDomain" +let RxCompositeFailures = "RxCompositeFailures" + +/// Generic Rx error codes. +public enum RxError + : Swift.Error + , CustomDebugStringConvertible { + /// Unknown error occurred. + case unknown + /// Performing an action on disposed object. + case disposed(object: AnyObject) + /// Arithmetic overflow error. + case overflow + /// Argument out of range error. + case argumentOutOfRange + /// Sequence doesn't contain any elements. + case noElements + /// Sequence contains more than one element. + case moreThanOneElement + /// Timeout error. + case timeout +} + +extension RxError { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + switch self { + case .unknown: + return "Unknown error occurred." + case .disposed(let object): + return "Object `\(object)` was already disposed." + case .overflow: + return "Arithmetic overflow occurred." + case .argumentOutOfRange: + return "Argument out of range." + case .noElements: + return "Sequence doesn't contain any elements." + case .moreThanOneElement: + return "Sequence contains more than one element." + case .timeout: + return "Sequence timeout." + } + } +} diff --git a/Pods/RxSwift/RxSwift/Event.swift b/Pods/RxSwift/RxSwift/Event.swift new file mode 100644 index 0000000..01861a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Event.swift @@ -0,0 +1,104 @@ +// +// Event.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a sequence event. +/// +/// Sequence grammar: +/// **next\* (error | completed)** +@frozen public enum Event { + /// Next element is produced. + case next(Element) + + /// Sequence terminated with an error. + case error(Swift.Error) + + /// Sequence completed successfully. + case completed +} + +extension Event: CustomDebugStringConvertible { + /// Description of event. + public var debugDescription: String { + switch self { + case .next(let value): + return "next(\(value))" + case .error(let error): + return "error(\(error))" + case .completed: + return "completed" + } + } +} + +extension Event { + /// Is `completed` or `error` event. + public var isStopEvent: Bool { + switch self { + case .next: return false + case .error, .completed: return true + } + } + + /// If `next` event, returns element value. + public var element: Element? { + if case .next(let value) = self { + return value + } + return nil + } + + /// If `error` event, returns error. + public var error: Swift.Error? { + if case .error(let error) = self { + return error + } + return nil + } + + /// If `completed` event, returns `true`. + public var isCompleted: Bool { + if case .completed = self { + return true + } + return false + } +} + +extension Event { + /// Maps sequence elements using transform. If error happens during the transform, `.error` + /// will be returned as value. + public func map(_ transform: (Element) throws -> Result) -> Event { + do { + switch self { + case let .next(element): + return .next(try transform(element)) + case let .error(error): + return .error(error) + case .completed: + return .completed + } + } + catch let e { + return .error(e) + } + } +} + +/// A type that can be converted to `Event`. +public protocol EventConvertible { + /// Type of element in event + associatedtype Element + + /// Event representation of this instance + var event: Event { get } +} + +extension Event: EventConvertible { + /// Event representation of this instance + public var event: Event { self } +} diff --git a/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift b/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift new file mode 100644 index 0000000..9794683 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Extensions/Bag+Rx.swift @@ -0,0 +1,50 @@ +// +// Bag+Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/19/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + + +// MARK: forEach + +@inline(__always) +func dispatch(_ bag: Bag<(Event) -> Void>, _ event: Event) { + bag._value0?(event) + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value(event) + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element(event) + } + } +} + +/// Dispatches `dispose` to all disposables contained inside bag. +func disposeAll(in bag: Bag) { + bag._value0?.dispose() + + if bag._onlyFastPath { + return + } + + let pairs = bag._pairs + for i in 0 ..< pairs.count { + pairs[i].value.dispose() + } + + if let dictionary = bag._dictionary { + for element in dictionary.values { + element.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/GroupedObservable.swift b/Pods/RxSwift/RxSwift/GroupedObservable.swift new file mode 100644 index 0000000..189a8c4 --- /dev/null +++ b/Pods/RxSwift/RxSwift/GroupedObservable.swift @@ -0,0 +1,35 @@ +// +// GroupedObservable.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an observable sequence of elements that have a common key. +public struct GroupedObservable : ObservableType { + /// Gets the common key. + public let key: Key + + private let source: Observable + + /// Initializes grouped observable sequence with key and source observable sequence. + /// + /// - parameter key: Grouped observable sequence key + /// - parameter source: Observable sequence that represents sequence of elements for the key + /// - returns: Grouped observable sequence of elements for the specific key + public init(key: Key, source: Observable) { + self.key = key + self.source = source + } + + /// Subscribes `observer` to receive events for this sequence. + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.source.subscribe(observer) + } + + /// Converts `self` to `Observable` sequence. + public func asObservable() -> Observable { + self.source + } +} diff --git a/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift b/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift new file mode 100644 index 0000000..954fbf0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ImmediateSchedulerType.swift @@ -0,0 +1,36 @@ +// +// ImmediateSchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/31/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents an object that immediately schedules units of work. +public protocol ImmediateSchedulerType { + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable +} + +extension ImmediateSchedulerType { + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRecursive(_ state: State, action: @escaping (_ state: State, _ recurse: (State) -> Void) -> Void) -> Disposable { + let recursiveScheduler = RecursiveImmediateScheduler(action: action, scheduler: self) + + recursiveScheduler.schedule(state) + + return Disposables.create(with: recursiveScheduler.dispose) + } +} diff --git a/Pods/RxSwift/RxSwift/Observable.swift b/Pods/RxSwift/RxSwift/Observable.swift new file mode 100644 index 0000000..93a3ed7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observable.swift @@ -0,0 +1,31 @@ +// +// Observable.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// A type-erased `ObservableType`. +/// +/// It represents a push style sequence. +public class Observable : ObservableType { + init() { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + rxAbstractMethod() + } + + public func asObservable() -> Observable { self } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + diff --git a/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift b/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift new file mode 100644 index 0000000..0f56a81 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableConvertibleType.swift @@ -0,0 +1,18 @@ +// +// ObservableConvertibleType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Type that can be converted to observable sequence (`Observable`). +public protocol ObservableConvertibleType { + /// Type of elements in sequence. + associatedtype Element + + /// Converts `self` to `Observable` sequence. + /// + /// - returns: Observable sequence that represents `self`. + func asObservable() -> Observable +} diff --git a/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift b/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift new file mode 100644 index 0000000..ac850c3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableType+Extensions.swift @@ -0,0 +1,174 @@ +// +// ObservableType+Extensions.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if DEBUG + import Foundation +#endif + +extension ObservableType { + /** + Subscribes an event handler to an observable sequence. + + - parameter on: Action to invoke for each event in the observable sequence. + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe(_ on: @escaping (Event) -> Void) -> Disposable { + let observer = AnonymousObserver { e in + on(e) + } + return self.asObservable().subscribe(observer) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + Also, take in an object and provide an unretained, safe to use (i.e. not implicitly unwrapped), reference to it along with the events emitted by the sequence. + + - Note: If `object` can't be retained, none of the other closures will be invoked. + + - parameter object: The object to provide an unretained reference on. + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + with object: Object, + onNext: ((Object, Element) -> Void)? = nil, + onError: ((Object, Swift.Error) -> Void)? = nil, + onCompleted: ((Object) -> Void)? = nil, + onDisposed: ((Object) -> Void)? = nil + ) -> Disposable { + subscribe( + onNext: { [weak object] in + guard let object = object else { return } + onNext?(object, $0) + }, + onError: { [weak object] in + guard let object = object else { return } + onError?(object, $0) + }, + onCompleted: { [weak object] in + guard let object = object else { return } + onCompleted?(object) + }, + onDisposed: { [weak object] in + guard let object = object else { return } + onDisposed?(object) + } + ) + } + + /** + Subscribes an element handler, an error handler, a completion handler and disposed handler to an observable sequence. + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter onDisposed: Action to invoke upon any type of termination of sequence (if the sequence has + gracefully completed, errored, or if the generation is canceled by disposing subscription). + - returns: Subscription object used to unsubscribe from the observable sequence. + */ + public func subscribe( + onNext: ((Element) -> Void)? = nil, + onError: ((Swift.Error) -> Void)? = nil, + onCompleted: (() -> Void)? = nil, + onDisposed: (() -> Void)? = nil + ) -> Disposable { + let disposable: Disposable + + if let disposed = onDisposed { + disposable = Disposables.create(with: disposed) + } + else { + disposable = Disposables.create() + } + + #if DEBUG + let synchronizationTracker = SynchronizationTracker() + #endif + + let callStack = Hooks.recordCallStackOnError ? Hooks.customCaptureSubscriptionCallstack() : [] + + let observer = AnonymousObserver { event in + + #if DEBUG + synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { synchronizationTracker.unregister() } + #endif + + switch event { + case .next(let value): + onNext?(value) + case .error(let error): + if let onError = onError { + onError(error) + } + else { + Hooks.defaultErrorHandler(callStack, error) + } + disposable.dispose() + case .completed: + onCompleted?() + disposable.dispose() + } + } + return Disposables.create( + self.asObservable().subscribe(observer), + disposable + ) + } +} + +import Foundation + +extension Hooks { + public typealias DefaultErrorHandler = (_ subscriptionCallStack: [String], _ error: Error) -> Void + public typealias CustomCaptureSubscriptionCallstack = () -> [String] + + private static let lock = RecursiveLock() + private static var _defaultErrorHandler: DefaultErrorHandler = { subscriptionCallStack, error in + #if DEBUG + let serializedCallStack = subscriptionCallStack.joined(separator: "\n") + print("Unhandled error happened: \(error)") + if !serializedCallStack.isEmpty { + print("subscription called from:\n\(serializedCallStack)") + } + #endif + } + private static var _customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack = { + #if DEBUG + return Thread.callStackSymbols + #else + return [] + #endif + } + + /// Error handler called in case onError handler wasn't provided. + public static var defaultErrorHandler: DefaultErrorHandler { + get { + lock.performLocked { _defaultErrorHandler } + } + set { + lock.performLocked { _defaultErrorHandler = newValue } + } + } + + /// Subscription callstack block to fetch custom callstack information. + public static var customCaptureSubscriptionCallstack: CustomCaptureSubscriptionCallstack { + get { + lock.performLocked { _customCaptureSubscriptionCallstack } + } + set { + lock.performLocked { _customCaptureSubscriptionCallstack = newValue } + } + } +} + diff --git a/Pods/RxSwift/RxSwift/ObservableType.swift b/Pods/RxSwift/RxSwift/ObservableType.swift new file mode 100644 index 0000000..279bf7f --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObservableType.swift @@ -0,0 +1,45 @@ +// +// ObservableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Represents a push style sequence. +public protocol ObservableType: ObservableConvertibleType { + /** + Subscribes `observer` to receive events for this sequence. + + ### Grammar + + **Next\* (Error | Completed)?** + + * sequences can produce zero or more elements so zero or more `Next` events can be sent to `observer` + * once an `Error` or `Completed` event is sent, the sequence terminates and can't produce any other elements + + It is possible that events are sent from different threads, but no two events can be sent concurrently to + `observer`. + + ### Resource Management + + When sequence sends `Complete` or `Error` event all internal resources that compute sequence elements + will be freed. + + To cancel production of sequence elements and free resources immediately, call `dispose` on returned + subscription. + + - returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources. + */ + func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element +} + +extension ObservableType { + + /// Default implementation of converting `ObservableType` to `Observable`. + public func asObservable() -> Observable { + // temporary workaround + //return Observable.create(subscribe: self.subscribe) + Observable.create { o in self.subscribe(o) } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AddRef.swift b/Pods/RxSwift/RxSwift/Observables/AddRef.swift new file mode 100644 index 0000000..a96dfcb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AddRef.swift @@ -0,0 +1,44 @@ +// +// AddRef.swift +// RxSwift +// +// Created by Junior B. on 30/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AddRefSink : Sink, ObserverType { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final class AddRef : Producer { + + private let source: Observable + private let refCount: RefCountDisposable + + init(source: Observable, refCount: RefCountDisposable) { + self.source = source + self.refCount = refCount + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let releaseDisposable = self.refCount.retain() + let sink = AddRefSink(observer: observer, cancel: cancel) + let subscription = Disposables.create(releaseDisposable, self.source.subscribe(sink)) + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Amb.swift b/Pods/RxSwift/RxSwift/Observables/Amb.swift new file mode 100644 index 0000000..efc17a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Amb.swift @@ -0,0 +1,157 @@ +// +// Amb.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - returns: An observable sequence that surfaces any of the given sequences, whichever reacted first. + */ + public static func amb(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + sequence.reduce(Observable.never()) { a, o in + a.amb(o.asObservable()) + } + } +} + +extension ObservableType { + + /** + Propagates the observable sequence that reacts first. + + - seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html) + + - parameter right: Second observable sequence. + - returns: An observable sequence that surfaces either of the given sequences, whichever reacted first. + */ + public func amb + (_ right: O2) + -> Observable where O2.Element == Element { + Amb(left: self.asObservable(), right: right.asObservable()) + } +} + +private enum AmbState { + case neither + case left + case right +} + +final private class AmbObserver: ObserverType { + typealias Element = Observer.Element + typealias Parent = AmbSink + typealias This = AmbObserver + typealias Sink = (This, Event) -> Void + + private let parent: Parent + fileprivate var sink: Sink + fileprivate var cancel: Disposable + + init(parent: Parent, cancel: Disposable, sink: @escaping Sink) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + + self.parent = parent + self.sink = sink + self.cancel = cancel + } + + func on(_ event: Event) { + self.sink(self, event) + if event.isStopEvent { + self.cancel.dispose() + } + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final private class AmbSink: Sink { + typealias Element = Observer.Element + typealias Parent = Amb + typealias AmbObserverType = AmbObserver + + private let parent: Parent + + private let lock = RecursiveLock() + // state + private var choice = AmbState.neither + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let disposeAll = Disposables.create(subscription1, subscription2) + + let forwardEvent = { (o: AmbObserverType, event: Event) -> Void in + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + let decide = { (o: AmbObserverType, event: Event, me: AmbState, otherSubscription: Disposable) in + self.lock.performLocked { + if self.choice == .neither { + self.choice = me + o.sink = forwardEvent + o.cancel = disposeAll + otherSubscription.dispose() + } + + if self.choice == me { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + } + } + + let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .left, subscription2) + } + + let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in + decide(o, e, .right, subscription1) + } + + subscription1.setDisposable(self.parent.left.subscribe(sink1)) + subscription2.setDisposable(self.parent.right.subscribe(sink2)) + + return disposeAll + } +} + +final private class Amb: Producer { + fileprivate let left: Observable + fileprivate let right: Observable + + init(left: Observable, right: Observable) { + self.left = left + self.right = right + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AmbSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift b/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift new file mode 100644 index 0000000..6fa6257 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AsMaybe.swift @@ -0,0 +1,48 @@ +// +// AsMaybe.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsMaybeSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class AsMaybe: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsMaybeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/AsSingle.swift b/Pods/RxSwift/RxSwift/Observables/AsSingle.swift new file mode 100644 index 0000000..b39932f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/AsSingle.swift @@ -0,0 +1,51 @@ +// +// AsSingle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class AsSingleSink : Sink, ObserverType { + typealias Element = Observer.Element + + private var element: Event? + + func on(_ event: Event) { + switch event { + case .next: + if self.element != nil { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + } + + self.element = event + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if let element = self.element { + self.forwardOn(element) + self.forwardOn(.completed) + } + else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class AsSingle: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AsSingleSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Buffer.swift b/Pods/RxSwift/RxSwift/Observables/Buffer.swift new file mode 100644 index 0000000..087c4cf --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Buffer.swift @@ -0,0 +1,138 @@ +// +// Buffer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a buffer that's sent out when either it's full or a given amount of time has elapsed, using the specified scheduler to run timers. + + A useful real-world analogy of this overload is the behavior of a ferry leaving the dock when all seats are taken, or at the scheduled time of departure, whichever event occurs first. + + - seealso: [buffer operator on reactivex.io](http://reactivex.io/documentation/operators/buffer.html) + + - parameter timeSpan: Maximum time length of a buffer. + - parameter count: Maximum element count of a buffer. + - parameter scheduler: Scheduler to run buffering timers on. + - returns: An observable sequence of buffers. + */ + public func buffer(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable<[Element]> { + BufferTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class BufferTimeCount: Producer<[Element]> { + + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [Element] { + let sink = BufferTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class BufferTimeCountSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == [Element] { + typealias Parent = BufferTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + // state + private let timerD = SerialDisposable() + private var buffer = [Element]() + private var windowID = 0 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.createTimer(self.windowID) + return Disposables.create(timerD, parent.source.subscribe(self)) + } + + func startNewWindowAndSendCurrentOne() { + self.windowID = self.windowID &+ 1 + let windowID = self.windowID + + let buffer = self.buffer + self.buffer = [] + self.forwardOn(.next(buffer)) + + self.createTimer(windowID) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.buffer.append(element) + + if self.buffer.count == self.parent.count { + self.startNewWindowAndSendCurrentOne() + } + + case .error(let error): + self.buffer = [] + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(self.buffer)) + self.forwardOn(.completed) + self.dispose() + } + } + + func createTimer(_ windowID: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowID != windowID { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let disposable = self.parent.scheduler.scheduleRelative(windowID, dueTime: self.parent.timeSpan) { previousWindowID in + self.lock.performLocked { + if previousWindowID != self.windowID { + return + } + + self.startNewWindowAndSendCurrentOne() + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposable) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Catch.swift b/Pods/RxSwift/RxSwift/Observables/Catch.swift new file mode 100644 index 0000000..2efd660 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Catch.swift @@ -0,0 +1,275 @@ +// +// Catch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + public func `catch`(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + Catch(source: self.asObservable(), handler: handler) + } + + /** + Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter handler: Error handler function, producing another observable sequence. + - returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred. + */ + @available(*, deprecated, renamed: "catch(_:)") + public func catchError(_ handler: @escaping (Swift.Error) throws -> Observable) + -> Observable { + `catch`(handler) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + public func catchAndReturn(_ element: Element) + -> Observable { + Catch(source: self.asObservable(), handler: { _ in Observable.just(element) }) + } + + /** + Continues an observable sequence that is terminated by an error with a single element. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - parameter element: Last element in an observable sequence in case error occurs. + - returns: An observable sequence containing the source sequence's elements, followed by the `element` in case an error occurred. + */ + @available(*, deprecated, renamed: "catchAndReturn(_:)") + public func catchErrorJustReturn(_ element: Element) + -> Observable { + catchAndReturn(element) + } +} + +extension ObservableType { + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + @available(*, deprecated, renamed: "catch(onSuccess:onFailure:onDisposed:)") + public static func catchError(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + `catch`(sequence: sequence) + } + + /** + Continues an observable sequence that is terminated by an error with the next observable sequence. + + - seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html) + + - returns: An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. + */ + public static func `catch`(sequence: Sequence) -> Observable + where Sequence.Element == Observable { + CatchSequence(sources: sequence) + } +} + +extension ObservableType { + + /** + Repeats the source observable sequence until it successfully terminates. + + **This could potentially create an infinite sequence.** + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - returns: Observable sequence to repeat until it successfully terminates. + */ + public func retry() -> Observable { + CatchSequence(sources: InfiniteSequence(repeatedValue: self.asObservable())) + } + + /** + Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates. + + If you encounter an error and want it to retry once, then you must use `retry(2)` + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter maxAttemptCount: Maximum number of times to repeat the sequence. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. + */ + public func retry(_ maxAttemptCount: Int) + -> Observable { + CatchSequence(sources: Swift.repeatElement(self.asObservable(), count: maxAttemptCount)) + } +} + +// catch with callback + +final private class CatchSinkProxy: ObserverType { + typealias Element = Observer.Element + typealias Parent = CatchSink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.parent.forwardOn(event) + + switch event { + case .next: + break + case .error, .completed: + self.parent.dispose() + } + } +} + +final private class CatchSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = Catch + + private let parent: Parent + private let subscription = SerialDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let d1 = SingleAssignmentDisposable() + self.subscription.disposable = d1 + d1.setDisposable(self.parent.source.subscribe(self)) + + return self.subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .completed: + self.forwardOn(event) + self.dispose() + case .error(let error): + do { + let catchSequence = try self.parent.handler(error) + + let observer = CatchSinkProxy(parent: self) + + self.subscription.disposable = catchSequence.subscribe(observer) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Catch: Producer { + typealias Handler = (Swift.Error) throws -> Observable + + fileprivate let source: Observable + fileprivate let handler: Handler + + init(source: Observable, handler: @escaping Handler) { + self.source = source + self.handler = handler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// catch enumerable + +final private class CatchSequenceSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = CatchSequence + + private var lastError: Swift.Error? + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error(let error): + self.lastError = error + self.schedule(.moveNext) + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let onError = observable as? CatchSequence { + return (onError.sources.makeIterator(), nil) + } + else { + return nil + } + } +} + +final private class CatchSequence: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + let sources: Sequence + + init(sources: Sequence) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = CatchSequenceSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift new file mode 100644 index 0000000..4350851 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest+Collection.swift @@ -0,0 +1,165 @@ +// +// CombineLatest+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/29/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + CombineLatestCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever any of the observable sequences produces an element. + + - seealso: [combinelatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + CombineLatestCollectionType(sources: collection, resultSelector: { $0 }) + } +} + +final private class CombineLatestCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = CombineLatestCollectionType + typealias SourceElement = Collection.Element.Element + + let parent: Parent + + let lock = RecursiveLock() + + // state + var numberOfValues = 0 + var values: [SourceElement?] + var isDone: [Bool] + var numberOfDone = 0 + var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [SourceElement?](repeating: nil, count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + if self.values[atIndex] == nil { + self.numberOfValues += 1 + } + + self.values[atIndex] = element + + if self.numberOfValues < self.parent.count { + let numberOfOthersThatAreDone = self.numberOfDone - (self.isDone[atIndex] ? 1 : 0) + if numberOfOthersThatAreDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + let result = try self.parent.resultSelector(self.values.map { $0! }) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + + self.subscriptions[j].setDisposable(disposable) + + j += 1 + } + + if self.parent.sources.isEmpty { + do { + let result = try self.parent.resultSelector([]) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return Disposables.create(subscriptions) + } +} + +final private class CombineLatestCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift new file mode 100644 index 0000000..e69bbab --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest+arity.swift @@ -0,0 +1,843 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// CombineLatest+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return CombineLatest2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class CombineLatestSink2_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest2 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2) + } +} + +final class CombineLatest2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return CombineLatest3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class CombineLatestSink3_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest3 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3) + } +} + +final class CombineLatest3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return CombineLatest4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class CombineLatestSink4_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest4 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4) + } +} + +final class CombineLatest4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return CombineLatest5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class CombineLatestSink5_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest5 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5) + } +} + +final class CombineLatest5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return CombineLatest6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class CombineLatestSink6_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest6 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6) + } +} + +final class CombineLatest6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return CombineLatest7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class CombineLatestSink7_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest7 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7) + } +} + +final class CombineLatest7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - parameter resultSelector: Function to invoke whenever any of the sources produces an element. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever any of the observable sequences produces an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func combineLatest + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return CombineLatest8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class CombineLatestSink8_ : CombineLatestSink { + typealias Result = Observer.Element + typealias Parent = CombineLatest8 + + let parent: Parent + + var latestElement1: E1! = nil + var latestElement2: E2! = nil + var latestElement3: E3! = nil + var latestElement4: E4! = nil + var latestElement5: E5! = nil + var latestElement6: E6! = nil + var latestElement7: E7! = nil + var latestElement8: E8! = nil + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = CombineLatestObserver(lock: self.lock, parent: self, index: 0, setLatestValue: { (e: E1) -> Void in self.latestElement1 = e }, this: subscription1) + let observer2 = CombineLatestObserver(lock: self.lock, parent: self, index: 1, setLatestValue: { (e: E2) -> Void in self.latestElement2 = e }, this: subscription2) + let observer3 = CombineLatestObserver(lock: self.lock, parent: self, index: 2, setLatestValue: { (e: E3) -> Void in self.latestElement3 = e }, this: subscription3) + let observer4 = CombineLatestObserver(lock: self.lock, parent: self, index: 3, setLatestValue: { (e: E4) -> Void in self.latestElement4 = e }, this: subscription4) + let observer5 = CombineLatestObserver(lock: self.lock, parent: self, index: 4, setLatestValue: { (e: E5) -> Void in self.latestElement5 = e }, this: subscription5) + let observer6 = CombineLatestObserver(lock: self.lock, parent: self, index: 5, setLatestValue: { (e: E6) -> Void in self.latestElement6 = e }, this: subscription6) + let observer7 = CombineLatestObserver(lock: self.lock, parent: self, index: 6, setLatestValue: { (e: E7) -> Void in self.latestElement7 = e }, this: subscription7) + let observer8 = CombineLatestObserver(lock: self.lock, parent: self, index: 7, setLatestValue: { (e: E8) -> Void in self.latestElement8 = e }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.latestElement1, self.latestElement2, self.latestElement3, self.latestElement4, self.latestElement5, self.latestElement6, self.latestElement7, self.latestElement8) + } +} + +final class CombineLatest8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = CombineLatestSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift b/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift new file mode 100644 index 0000000..caa0256 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CombineLatest.swift @@ -0,0 +1,131 @@ +// +// CombineLatest.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol CombineLatestProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class CombineLatestSink + : Sink + , CombineLatestProtocol { + typealias Element = Observer.Element + + let lock = RecursiveLock() + + private let arity: Int + private var numberOfValues = 0 + private var numberOfDone = 0 + private var hasValue: [Bool] + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.arity = arity + self.hasValue = [Bool](repeating: false, count: arity) + self.isDone = [Bool](repeating: false, count: arity) + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func next(_ index: Int) { + if !self.hasValue[index] { + self.hasValue[index] = true + self.numberOfValues += 1 + } + + if self.numberOfValues == self.arity { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + else { + var allOthersDone = true + + for i in 0 ..< self.arity { + if i != index && !self.isDone[i] { + allOthersDone = false + break + } + } + + if allOthersDone { + self.forwardOn(.completed) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + if self.isDone[index] { + return + } + + self.isDone[index] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.arity { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class CombineLatestObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private let parent: CombineLatestProtocol + + let lock: RecursiveLock + private let index: Int + private let this: Disposable + private let setLatestValue: ValueSetter + + init(lock: RecursiveLock, parent: CombineLatestProtocol, index: Int, setLatestValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setLatestValue = setLatestValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.setLatestValue(value) + self.parent.next(self.index) + case .error(let error): + self.this.dispose() + self.parent.fail(error) + case .completed: + self.this.dispose() + self.parent.done(self.index) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/CompactMap.swift b/Pods/RxSwift/RxSwift/Observables/CompactMap.swift new file mode 100644 index 0000000..7dbcdfb --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/CompactMap.swift @@ -0,0 +1,76 @@ +// +// CompactMap.swift +// RxSwift +// +// Created by Michael Long on 04/09/2019. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into an optional form and filters all optional results. + + - parameter transform: A transform function to apply to each source element and which returns an element or nil. + - returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source. + + */ + public func compactMap(_ transform: @escaping (Element) throws -> Result?) + -> Observable { + CompactMap(source: self.asObservable(), transform: transform) + } +} + +final private class CompactMapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType? + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + if let mappedElement = try self.transform(element) { + self.forwardOn(.next(mappedElement)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class CompactMap: Producer { + typealias Transform = (SourceType) throws -> ResultType? + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = CompactMapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Concat.swift b/Pods/RxSwift/RxSwift/Observables/Concat.swift new file mode 100644 index 0000000..b2fb1a2 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Concat.swift @@ -0,0 +1,131 @@ +// +// Concat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Concatenates the second observable sequence to `self` upon successful termination of `self`. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - parameter second: Second observable sequence. + - returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence. + */ + public func concat(_ second: Source) -> Observable where Source.Element == Element { + Observable.concat([self.asObservable(), second.asObservable()]) + } +} + +extension ObservableType { + /** + Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sequence: Sequence) -> Observable + where Sequence.Element == Observable { + return Concat(sources: sequence, count: nil) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ collection: Collection) -> Observable + where Collection.Element == Observable { + return Concat(sources: collection, count: Int64(collection.count)) + } + + /** + Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully. + + This operator has tail recursive optimizations that will prevent stack overflow. + + Optimizations will be performed in cases equivalent to following: + + [1, [2, [3, .....].concat()].concat].concat() + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each given sequence, in sequential order. + */ + public static func concat(_ sources: Observable ...) -> Observable { + Concat(sources: sources, count: Int64(sources.count)) + } +} + +final private class ConcatSink + : TailRecursiveSink + , ObserverType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event){ + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.schedule(.moveNext) + } + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + source.subscribe(self) + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + if let source = observable as? Concat { + return (source.sources.makeIterator(), source.count) + } + else { + return nil + } + } +} + +final private class Concat: Producer where Sequence.Element: ObservableConvertibleType { + typealias Element = Sequence.Element.Element + + fileprivate let sources: Sequence + fileprivate let count: IntMax? + + init(sources: Sequence, count: IntMax?) { + self.sources = sources + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ConcatSink(observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), self.count)) + return (sink: sink, subscription: subscription) + } +} + diff --git a/Pods/RxSwift/RxSwift/Observables/Create.swift b/Pods/RxSwift/RxSwift/Observables/Create.swift new file mode 100644 index 0000000..ca81442 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Create.swift @@ -0,0 +1,78 @@ +// +// Create.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: create + + /** + Creates an observable sequence from a specified subscribe method implementation. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method. + - returns: The observable sequence with the specified implementation for the `subscribe` method. + */ + public static func create(_ subscribe: @escaping (AnyObserver) -> Disposable) -> Observable { + AnonymousObservable(subscribe) + } +} + +final private class AnonymousObservableSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = AnonymousObservable + + // state + private let isStopped = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + switch event { + case .next: + if load(self.isStopped) == 1 { + return + } + self.forwardOn(event) + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.forwardOn(event) + self.dispose() + } + } + } + + func run(_ parent: Parent) -> Disposable { + parent.subscribeHandler(AnyObserver(self)) + } +} + +final private class AnonymousObservable: Producer { + typealias SubscribeHandler = (AnyObserver) -> Disposable + + let subscribeHandler: SubscribeHandler + + init(_ subscribeHandler: @escaping SubscribeHandler) { + self.subscribeHandler = subscribeHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = AnonymousObservableSink(observer: observer, cancel: cancel) + let subscription = sink.run(self) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Debounce.swift b/Pods/RxSwift/RxSwift/Observables/Debounce.swift new file mode 100644 index 0000000..dfab004 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Debounce.swift @@ -0,0 +1,119 @@ +// +// Debounce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/11/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Debounce(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DebounceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Debounce + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var id = 0 as UInt64 + private var value: Element? + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.id = self.id &+ 1 + let currentId = self.id + self.value = element + + + let scheduler = self.parent.scheduler + let dueTime = self.parent.dueTime + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + d.setDisposable(scheduler.scheduleRelative(currentId, dueTime: dueTime, action: self.propagate)) + case .error: + self.value = nil + self.forwardOn(event) + self.dispose() + case .completed: + if let value = self.value { + self.value = nil + self.forwardOn(.next(value)) + } + self.forwardOn(.completed) + self.dispose() + } + } + + func propagate(_ currentId: UInt64) -> Disposable { + self.lock.performLocked { + let originalValue = self.value + + if let value = originalValue, self.id == currentId { + self.value = nil + self.forwardOn(.next(value)) + } + + return Disposables.create() + } + } +} + +final private class Debounce: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DebounceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/Pods/RxSwift/RxSwift/Observables/Debug.swift b/Pods/RxSwift/RxSwift/Observables/Debug.swift new file mode 100644 index 0000000..762e394 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Debug.swift @@ -0,0 +1,102 @@ +// +// Debug.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Prints received events for all observers on standard output. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter identifier: Identifier that is printed together with event description to standard output. + - parameter trimOutput: Should output be trimmed to max 40 characters. + - returns: An observable sequence whose events are printed to standard output. + */ + public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function) + -> Observable { + return Debug(source: self, identifier: identifier, trimOutput: trimOutput, file: file, line: line, function: function) + } +} + +private let dateFormat = "yyyy-MM-dd HH:mm:ss.SSS" + +private func logEvent(_ identifier: String, dateFormat: DateFormatter, content: String) { + print("\(dateFormat.string(from: Date())): \(identifier) -> \(content)") +} + +final private class DebugSink: Sink, ObserverType where Observer.Element == Source.Element { + typealias Element = Observer.Element + typealias Parent = Debug + + private let parent: Parent + private let timestampFormatter = DateFormatter() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.timestampFormatter.dateFormat = dateFormat + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "subscribed") + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + let maxEventTextLength = 40 + let eventText = "\(event)" + + let eventNormalized = (eventText.count > maxEventTextLength) && self.parent.trimOutput + ? String(eventText.prefix(maxEventTextLength / 2)) + "..." + String(eventText.suffix(maxEventTextLength / 2)) + : eventText + + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "Event \(eventNormalized)") + + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + + override func dispose() { + if !self.isDisposed { + logEvent(self.parent.identifier, dateFormat: self.timestampFormatter, content: "isDisposed") + } + super.dispose() + } +} + +final private class Debug: Producer { + fileprivate let identifier: String + fileprivate let trimOutput: Bool + private let source: Source + + init(source: Source, identifier: String?, trimOutput: Bool, file: String, line: UInt, function: String) { + self.trimOutput = trimOutput + if let identifier = identifier { + self.identifier = identifier + } + else { + let trimmedFile: String + if let lastIndex = file.lastIndex(of: "/") { + trimmedFile = String(file[file.index(after: lastIndex) ..< file.endIndex]) + } + else { + trimmedFile = file + } + self.identifier = "\(trimmedFile):\(line) (\(function))" + } + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = DebugSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Decode.swift b/Pods/RxSwift/RxSwift/Observables/Decode.swift new file mode 100644 index 0000000..8bc7342 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Decode.swift @@ -0,0 +1,34 @@ +// +// Decode.swift +// RxSwift +// +// Created by Shai Mishali on 24/07/2020. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +public extension ObservableType where Element == Data { + /// Attempt to decode the emitted `Data` using a provided decoder. + /// + /// - parameter type: A `Decodable`-conforming type to attempt to decode to + /// - parameter decoder: A capable decoder, e.g. `JSONDecoder` or `PropertyListDecoder` + /// + /// - note: If using a custom decoder, it must conform to the `DataDecoder` protocol. + /// + /// - returns: An `Observable` of the decoded type + func decode(type: Item.Type, + decoder: Decoder) -> Observable { + map { try decoder.decode(type, from: $0) } + } +} + +/// Represents an entity capable of decoding raw `Data` +/// into a concrete `Decodable` type +public protocol DataDecoder { + func decode(_ type: Item.Type, from data: Data) throws -> Item +} + +extension JSONDecoder: DataDecoder {} +extension PropertyListDecoder: DataDecoder {} diff --git a/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift b/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift new file mode 100644 index 0000000..8d133d8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DefaultIfEmpty.swift @@ -0,0 +1,66 @@ +// +// DefaultIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Emits elements from the source observable sequence, or a default element if the source observable sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter default: Default element to be sent if the source does not emit any elements + - returns: An observable sequence which emits default element end completes in case the original sequence is empty + */ + public func ifEmpty(default: Element) -> Observable { + DefaultIfEmpty(source: self.asObservable(), default: `default`) + } +} + +final private class DefaultIfEmptySink: Sink, ObserverType { + typealias Element = Observer.Element + private let `default`: Element + private var isEmpty = true + + init(default: Element, observer: Observer, cancel: Cancelable) { + self.default = `default` + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.isEmpty { + self.forwardOn(.next(self.default)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class DefaultIfEmpty: Producer { + private let source: Observable + private let `default`: SourceType + + init(source: Observable, `default`: SourceType) { + self.source = source + self.default = `default` + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = DefaultIfEmptySink(default: self.default, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Deferred.swift b/Pods/RxSwift/RxSwift/Observables/Deferred.swift new file mode 100644 index 0000000..b81cb16 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Deferred.swift @@ -0,0 +1,75 @@ +// +// Deferred.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. + + - seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html) + + - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. + - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. + */ + public static func deferred(_ observableFactory: @escaping () throws -> Observable) + -> Observable { + Deferred(observableFactory: observableFactory) + } +} + +final private class DeferredSink: Sink, ObserverType where Source.Element == Observer.Element { + typealias Element = Observer.Element + + private let observableFactory: () throws -> Source + + init(observableFactory: @escaping () throws -> Source, observer: Observer, cancel: Cancelable) { + self.observableFactory = observableFactory + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let result = try self.observableFactory() + return result.subscribe(self) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + + switch event { + case .next: + break + case .error: + self.dispose() + case .completed: + self.dispose() + } + } +} + +final private class Deferred: Producer { + typealias Factory = () throws -> Source + + private let observableFactory : Factory + + init(observableFactory: @escaping Factory) { + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == Source.Element { + let sink = DeferredSink(observableFactory: self.observableFactory, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Delay.swift b/Pods/RxSwift/RxSwift/Observables/Delay.swift new file mode 100644 index 0000000..9f71c32 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Delay.swift @@ -0,0 +1,174 @@ +// +// Delay.swift +// RxSwift +// +// Created by tarunon on 2016/02/09. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the source by. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: the source Observable shifted in time by the specified delay. + */ + public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Delay(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySink + : Sink + , ObserverType { + typealias Element = Observer.Element + typealias Source = Observable + typealias DisposeKey = Bag.KeyType + + private let lock = RecursiveLock() + + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + private let sourceSubscription = SingleAssignmentDisposable() + private let cancelable = SerialDisposable() + + // is scheduled some action + private var active = false + // is "run loop" on different scheduler running + private var running = false + private var errorEvent: Event? + + // state + private var queue = Queue<(eventTime: RxTime, event: Event)>(capacity: 0) + + init(observer: Observer, dueTime: RxTimeInterval, scheduler: SchedulerType, cancel: Cancelable) { + self.dueTime = dueTime + self.scheduler = scheduler + super.init(observer: observer, cancel: cancel) + } + + // All of these complications in this method are caused by the fact that + // error should be propagated immediately. Error can be potentially received on different + // scheduler so this process needs to be synchronized somehow. + // + // Another complication is that scheduler is potentially concurrent so internal queue is used. + func drainQueue(state: (), scheduler: AnyRecursiveScheduler<()>) { + self.lock.lock() + let hasFailed = self.errorEvent != nil + if !hasFailed { + self.running = true + } + self.lock.unlock() + + if hasFailed { + return + } + + var ranAtLeastOnce = false + + while true { + self.lock.lock() + let errorEvent = self.errorEvent + + let eventToForwardImmediately = ranAtLeastOnce ? nil : self.queue.dequeue()?.event + let nextEventToScheduleOriginalTime: Date? = ranAtLeastOnce && !self.queue.isEmpty ? self.queue.peek().eventTime : nil + + if errorEvent == nil { + if eventToForwardImmediately != nil { + } + else if nextEventToScheduleOriginalTime != nil { + self.running = false + } + else { + self.running = false + self.active = false + } + } + self.lock.unlock() + + if let errorEvent = errorEvent { + self.forwardOn(errorEvent) + self.dispose() + return + } + else { + if let eventToForwardImmediately = eventToForwardImmediately { + ranAtLeastOnce = true + self.forwardOn(eventToForwardImmediately) + if case .completed = eventToForwardImmediately { + self.dispose() + return + } + } + else if let nextEventToScheduleOriginalTime = nextEventToScheduleOriginalTime { + scheduler.schedule((), dueTime: self.dueTime.reduceWithSpanBetween(earlierDate: nextEventToScheduleOriginalTime, laterDate: self.scheduler.now)) + return + } + else { + return + } + } + } + } + + func on(_ event: Event) { + if event.isStopEvent { + self.sourceSubscription.dispose() + } + + switch event { + case .error: + self.lock.lock() + let shouldSendImmediately = !self.running + self.queue = Queue(capacity: 0) + self.errorEvent = event + self.lock.unlock() + + if shouldSendImmediately { + self.forwardOn(event) + self.dispose() + } + default: + self.lock.lock() + let shouldSchedule = !self.active + self.active = true + self.queue.enqueue((self.scheduler.now, event)) + self.lock.unlock() + + if shouldSchedule { + self.cancelable.disposable = self.scheduler.scheduleRecursive((), dueTime: self.dueTime, action: self.drainQueue) + } + } + } + + func run(source: Observable) -> Disposable { + self.sourceSubscription.setDisposable(source.subscribe(self)) + return Disposables.create(sourceSubscription, cancelable) + } +} + +final private class Delay: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySink(observer: observer, dueTime: self.dueTime, scheduler: self.scheduler, cancel: cancel) + let subscription = sink.run(source: self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift b/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift new file mode 100644 index 0000000..fd8c495 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DelaySubscription.swift @@ -0,0 +1,58 @@ +// +// DelaySubscription.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers. + + - seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html) + + - parameter dueTime: Relative time shift of the subscription. + - parameter scheduler: Scheduler to run the subscription delay timer on. + - returns: Time-shifted sequence. + */ + public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + DelaySubscription(source: self.asObservable(), dueTime: dueTime, scheduler: scheduler) + } +} + +final private class DelaySubscriptionSink + : Sink, ObserverType { + typealias Element = Observer.Element + + func on(_ event: Event) { + self.forwardOn(event) + if event.isStopEvent { + self.dispose() + } + } + +} + +final private class DelaySubscription: Producer { + private let source: Observable + private let dueTime: RxTimeInterval + private let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DelaySubscriptionSink(observer: observer, cancel: cancel) + let subscription = self.scheduler.scheduleRelative((), dueTime: self.dueTime) { _ in + return self.source.subscribe(sink) + } + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift b/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift new file mode 100644 index 0000000..2ccd546 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Dematerialize.swift @@ -0,0 +1,51 @@ +// +// Dematerialize.swift +// RxSwift +// +// Created by Jamie Pinkham on 3/13/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: EventConvertible { + /** + Convert any previously materialized Observable into it's original form. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: The dematerialized observable sequence. + */ + public func dematerialize() -> Observable { + Dematerialize(source: self.asObservable()) + } + +} + +private final class DematerializeSink: Sink, ObserverType where Observer.Element == T.Element { + fileprivate func on(_ event: Event) { + switch event { + case .next(let element): + self.forwardOn(element.event) + if element.event.isStopEvent { + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Dematerialize: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == T.Element { + let sink = DematerializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift b/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift new file mode 100644 index 0000000..c127b5a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/DistinctUntilChanged.swift @@ -0,0 +1,137 @@ +// +// DistinctUntilChanged.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: Equatable { + + /** + Returns an observable sequence that contains only distinct contiguous elements according to equality operator. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence. + */ + public func distinctUntilChanged() + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: { ($0 == $1) }) + } +} + +extension ObservableType { + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> Key) + -> Observable { + self.distinctUntilChanged(keySelector, comparer: { $0 == $1 }) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence. + */ + public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool) + -> Observable { + self.distinctUntilChanged({ $0 }, comparer: comparer) + } + + /** + Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - parameter keySelector: A function to compute the comparison key for each element. + - parameter comparer: Equality comparer for computed key values. + - returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence. + */ + public func distinctUntilChanged(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool) + -> Observable { + return DistinctUntilChanged(source: self.asObservable(), selector: keySelector, comparer: comparer) + } + + /** + Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object. + + - seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html) + + - returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path + */ + public func distinctUntilChanged(at keyPath: KeyPath) -> + Observable { + self.distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] } + } +} + +final private class DistinctUntilChangedSink: Sink, ObserverType { + typealias Element = Observer.Element + + private let parent: DistinctUntilChanged + private var currentKey: Key? + + init(parent: DistinctUntilChanged, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let key = try self.parent.selector(value) + var areEqual = false + if let currentKey = self.currentKey { + areEqual = try self.parent.comparer(currentKey, key) + } + + if areEqual { + return + } + + self.currentKey = key + + self.forwardOn(event) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class DistinctUntilChanged: Producer { + typealias KeySelector = (Element) throws -> Key + typealias EqualityComparer = (Key, Key) throws -> Bool + + private let source: Observable + fileprivate let selector: KeySelector + fileprivate let comparer: EqualityComparer + + init(source: Observable, selector: @escaping KeySelector, comparer: @escaping EqualityComparer) { + self.source = source + self.selector = selector + self.comparer = comparer + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = DistinctUntilChangedSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Do.swift b/Pods/RxSwift/RxSwift/Observables/Do.swift new file mode 100644 index 0000000..3c8c68b --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Do.swift @@ -0,0 +1,112 @@ +// +// Do.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence. + + - seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html) + + - parameter onNext: Action to invoke for each element in the observable sequence. + - parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream. + - parameter onError: Action to invoke upon errored termination of the observable sequence. + - parameter afterError: Action to invoke after errored termination of the observable sequence. + - parameter onCompleted: Action to invoke upon graceful termination of the observable sequence. + - parameter afterCompleted: Action to invoke after graceful termination of the observable sequence. + - parameter onSubscribe: Action to invoke before subscribing to source observable sequence. + - parameter onSubscribed: Action to invoke after subscribing to source observable sequence. + - parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed. + - returns: The source sequence with the side-effecting behavior applied. + */ + public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, afterError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) + -> Observable { + return Do(source: self.asObservable(), eventHandler: { e in + switch e { + case .next(let element): + try onNext?(element) + case .error(let e): + try onError?(e) + case .completed: + try onCompleted?() + } + }, afterEventHandler: { e in + switch e { + case .next(let element): + try afterNext?(element) + case .error(let e): + try afterError?(e) + case .completed: + try afterCompleted?() + } + }, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose) + } +} + +final private class DoSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + + init(eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, observer: Observer, cancel: Cancelable) { + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + do { + try self.eventHandler(event) + self.forwardOn(event) + try self.afterEventHandler(event) + if event.isStopEvent { + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Do: Producer { + typealias EventHandler = (Event) throws -> Void + typealias AfterEventHandler = (Event) throws -> Void + + private let source: Observable + private let eventHandler: EventHandler + private let afterEventHandler: AfterEventHandler + private let onSubscribe: (() -> Void)? + private let onSubscribed: (() -> Void)? + private let onDispose: (() -> Void)? + + init(source: Observable, eventHandler: @escaping EventHandler, afterEventHandler: @escaping AfterEventHandler, onSubscribe: (() -> Void)?, onSubscribed: (() -> Void)?, onDispose: (() -> Void)?) { + self.source = source + self.eventHandler = eventHandler + self.afterEventHandler = afterEventHandler + self.onSubscribe = onSubscribe + self.onSubscribed = onSubscribed + self.onDispose = onDispose + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + self.onSubscribe?() + let sink = DoSink(eventHandler: self.eventHandler, afterEventHandler: self.afterEventHandler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + self.onSubscribed?() + let onDispose = self.onDispose + let allSubscriptions = Disposables.create { + subscription.dispose() + onDispose?() + } + return (sink: sink, subscription: allSubscriptions) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ElementAt.swift b/Pods/RxSwift/RxSwift/Observables/ElementAt.swift new file mode 100644 index 0000000..3f09c70 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ElementAt.swift @@ -0,0 +1,105 @@ +// +// ElementAt.swift +// RxSwift +// +// Created by Junior B. on 21/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + @available(*, deprecated, renamed: "element(at:)") + public func elementAt(_ index: Int) + -> Observable { + element(at: index) + } + + /** + Returns a sequence emitting only element _n_ emitted by an Observable + + - seealso: [elementAt operator on reactivex.io](http://reactivex.io/documentation/operators/elementat.html) + + - parameter index: The index of the required element (starting from 0). + - returns: An observable sequence that emits the desired element as its own sole emission. + */ + public func element(at index: Int) + -> Observable { + ElementAt(source: self.asObservable(), index: index, throwOnEmpty: true) + } +} + +final private class ElementAtSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = ElementAt + + let parent: Parent + var i: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.i = parent.index + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next: + + if self.i == 0 { + self.forwardOn(event) + self.forwardOn(.completed) + self.dispose() + } + + do { + _ = try decrementChecked(&self.i) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + if self.parent.throwOnEmpty { + self.forwardOn(.error(RxError.argumentOutOfRange)) + } else { + self.forwardOn(.completed) + } + + self.dispose() + } + } +} + +final private class ElementAt: Producer { + let source: Observable + let throwOnEmpty: Bool + let index: Int + + init(source: Observable, index: Int, throwOnEmpty: Bool) { + if index < 0 { + rxFatalError("index can't be negative") + } + + self.source = source + self.index = index + self.throwOnEmpty = throwOnEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceType { + let sink = ElementAtSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Empty.swift b/Pods/RxSwift/RxSwift/Observables/Empty.swift new file mode 100644 index 0000000..9ca5965 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Empty.swift @@ -0,0 +1,27 @@ +// +// Empty.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. + + - seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence with no elements. + */ + public static func empty() -> Observable { + EmptyProducer() + } +} + +final private class EmptyProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Enumerated.swift b/Pods/RxSwift/RxSwift/Observables/Enumerated.swift new file mode 100644 index 0000000..ef8a0ff --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Enumerated.swift @@ -0,0 +1,61 @@ +// +// Enumerated.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/6/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Enumerates the elements of an observable sequence. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - returns: An observable sequence that contains tuples of source sequence elements and their indexes. + */ + public func enumerated() + -> Observable<(index: Int, element: Element)> { + Enumerated(source: self.asObservable()) + } +} + +final private class EnumeratedSink: Sink, ObserverType where Observer.Element == (index: Int, element: Element) { + var index = 0 + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let nextIndex = try incrementChecked(&self.index) + let next = (index: nextIndex, element: value) + self.forwardOn(.next(next)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class Enumerated: Producer<(index: Int, element: Element)> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == (index: Int, element: Element) { + let sink = EnumeratedSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Error.swift b/Pods/RxSwift/RxSwift/Observables/Error.swift new file mode 100644 index 0000000..2e722d6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Error.swift @@ -0,0 +1,33 @@ +// +// Error.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that terminates with an `error`. + + - seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: The observable sequence that terminates with specified error. + */ + public static func error(_ error: Swift.Error) -> Observable { + ErrorProducer(error: error) + } +} + +final private class ErrorProducer: Producer { + private let error: Swift.Error + + init(error: Swift.Error) { + self.error = error + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.error(self.error)) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Filter.swift b/Pods/RxSwift/RxSwift/Observables/Filter.swift new file mode 100644 index 0000000..61d3ce7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Filter.swift @@ -0,0 +1,86 @@ +// +// Filter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Filters the elements of an observable sequence based on a predicate. + + - seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that contains elements from the input sequence that satisfy the condition. + */ + public func filter(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + Filter(source: self.asObservable(), predicate: predicate) + } +} + +extension ObservableType { + /** + Skips elements and completes (or errors) when the observable sequence completes (or errors). Equivalent to filter that always returns false. + + - seealso: [ignoreElements operator on reactivex.io](http://reactivex.io/documentation/operators/ignoreelements.html) + + - returns: An observable sequence that skips all elements of the source sequence. + */ + public func ignoreElements() + -> Observable { + self.flatMap { _ in Observable.empty() } + } +} + +final private class FilterSink: Sink, ObserverType { + typealias Predicate = (Element) throws -> Bool + typealias Element = Observer.Element + + private let predicate: Predicate + + init(predicate: @escaping Predicate, observer: Observer, cancel: Cancelable) { + self.predicate = predicate + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let satisfies = try self.predicate(value) + if satisfies { + self.forwardOn(.next(value)) + } + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed, .error: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class Filter: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + private let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = FilterSink(predicate: self.predicate, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/First.swift b/Pods/RxSwift/RxSwift/Observables/First.swift new file mode 100644 index 0000000..0014114 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/First.swift @@ -0,0 +1,41 @@ +// +// First.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/31/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +private final class FirstSink : Sink, ObserverType where Observer.Element == Element? { + typealias Parent = First + + func on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + self.forwardOn(.completed) + self.dispose() + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.next(nil)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class First: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? { + let sink = FirstSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Generate.swift b/Pods/RxSwift/RxSwift/Observables/Generate.swift new file mode 100644 index 0000000..7b924b3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Generate.swift @@ -0,0 +1,87 @@ +// +// Generate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler + to run the loop send out observer messages. + + - seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html) + + - parameter initialState: Initial state. + - parameter condition: Condition to terminate generation (upon returning `false`). + - parameter iterate: Iteration step function. + - parameter scheduler: Scheduler on which to run the generator loop. + - returns: The generated sequence. + */ + public static func generate(initialState: Element, condition: @escaping (Element) throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: @escaping (Element) throws -> Element) -> Observable { + Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler) + } +} + +final private class GenerateSink: Sink { + typealias Parent = Generate + + private let parent: Parent + + private var state: Sequence + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.state = parent.initialState + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(true) { isFirst, recurse -> Void in + do { + if !isFirst { + self.state = try self.parent.iterate(self.state) + } + + if try self.parent.condition(self.state) { + let result = try self.parent.resultSelector(self.state) + self.forwardOn(.next(result)) + + recurse(false) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + } + } +} + +final private class Generate: Producer { + fileprivate let initialState: Sequence + fileprivate let condition: (Sequence) throws -> Bool + fileprivate let iterate: (Sequence) throws -> Sequence + fileprivate let resultSelector: (Sequence) throws -> Element + fileprivate let scheduler: ImmediateSchedulerType + + init(initialState: Sequence, condition: @escaping (Sequence) throws -> Bool, iterate: @escaping (Sequence) throws -> Sequence, resultSelector: @escaping (Sequence) throws -> Element, scheduler: ImmediateSchedulerType) { + self.initialState = initialState + self.condition = condition + self.iterate = iterate + self.resultSelector = resultSelector + self.scheduler = scheduler + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = GenerateSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/GroupBy.swift b/Pods/RxSwift/RxSwift/Observables/GroupBy.swift new file mode 100644 index 0000000..88cbda7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/GroupBy.swift @@ -0,0 +1,133 @@ +// +// GroupBy.swift +// RxSwift +// +// Created by Tomi Koskinen on 01/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /* + Groups the elements of an observable sequence according to a specified key selector function. + + - seealso: [groupBy operator on reactivex.io](http://reactivex.io/documentation/operators/groupby.html) + + - parameter keySelector: A function to extract the key for each element. + - returns: A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. + */ + public func groupBy(keySelector: @escaping (Element) throws -> Key) + -> Observable> { + GroupBy(source: self.asObservable(), selector: keySelector) + } +} + +final private class GroupedObservableImpl: Observable { + private var subject: PublishSubject + private var refCount: RefCountDisposable + + init(subject: PublishSubject, refCount: RefCountDisposable) { + self.subject = subject + self.refCount = refCount + } + + override public func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + let release = self.refCount.retain() + let subscription = self.subject.subscribe(observer) + return Disposables.create(release, subscription) + } +} + + +final private class GroupBySink + : Sink + , ObserverType where Observer.Element == GroupedObservable { + typealias ResultType = Observer.Element + typealias Parent = GroupBy + + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + private var refCountDisposable: RefCountDisposable! + private var groupedSubjectTable: [Key: PublishSubject] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.groupedSubjectTable = [Key: PublishSubject]() + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.refCountDisposable = RefCountDisposable(disposable: self.subscription) + + self.subscription.setDisposable(self.parent.source.subscribe(self)) + + return self.refCountDisposable + } + + private func onGroupEvent(key: Key, value: Element) { + if let writer = self.groupedSubjectTable[key] { + writer.on(.next(value)) + } else { + let writer = PublishSubject() + self.groupedSubjectTable[key] = writer + + let group = GroupedObservable( + key: key, + source: GroupedObservableImpl(subject: writer, refCount: refCountDisposable) + ) + + self.forwardOn(.next(group)) + writer.on(.next(value)) + } + } + + final func on(_ event: Event) { + switch event { + case let .next(value): + do { + let groupKey = try self.parent.selector(value) + self.onGroupEvent(key: groupKey, value: value) + } + catch let e { + self.error(e) + return + } + case let .error(e): + self.error(e) + case .completed: + self.forwardOnGroups(event: .completed) + self.forwardOn(.completed) + self.subscription.dispose() + self.dispose() + } + } + + final func error(_ error: Swift.Error) { + self.forwardOnGroups(event: .error(error)) + self.forwardOn(.error(error)) + self.subscription.dispose() + self.dispose() + } + + final func forwardOnGroups(event: Event) { + for writer in self.groupedSubjectTable.values { + writer.on(event) + } + } +} + +final private class GroupBy: Producer> { + typealias KeySelector = (Element) throws -> Key + + fileprivate let source: Observable + fileprivate let selector: KeySelector + + init(source: Observable, selector: @escaping KeySelector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == GroupedObservable { + let sink = GroupBySink(parent: self, observer: observer, cancel: cancel) + return (sink: sink, subscription: sink.run()) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Just.swift b/Pods/RxSwift/RxSwift/Observables/Just.swift new file mode 100644 index 0000000..9349083 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Just.swift @@ -0,0 +1,87 @@ +// +// Just.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element) -> Observable { + Just(element: element) + } + + /** + Returns an observable sequence that contains a single element. + + - seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html) + + - parameter element: Single element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the single element on. + - returns: An observable sequence containing the single specified element. + */ + public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Observable { + JustScheduled(element: element, scheduler: scheduler) + } +} + +final private class JustScheduledSink: Sink { + typealias Parent = JustScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let scheduler = self.parent.scheduler + return scheduler.schedule(self.parent.element) { element in + self.forwardOn(.next(element)) + return scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class JustScheduled: Producer { + fileprivate let scheduler: ImmediateSchedulerType + fileprivate let element: Element + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.element = element + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = JustScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class Just: Producer { + private let element: Element + + init(element: Element) { + self.element = element + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + observer.on(.next(self.element)) + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Map.swift b/Pods/RxSwift/RxSwift/Observables/Map.swift new file mode 100644 index 0000000..0691273 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Map.swift @@ -0,0 +1,77 @@ +// +// Map.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a new form. + + - seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html) + + - parameter transform: A transform function to apply to each source element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source. + + */ + public func map(_ transform: @escaping (Element) throws -> Result) + -> Observable { + Map(source: self.asObservable(), transform: transform) + } +} + +final private class MapSink: Sink, ObserverType { + typealias Transform = (SourceType) throws -> ResultType + + typealias ResultType = Observer.Element + typealias Element = SourceType + + private let transform: Transform + + init(transform: @escaping Transform, observer: Observer, cancel: Cancelable) { + self.transform = transform + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + let mappedElement = try self.transform(element) + self.forwardOn(.next(mappedElement)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Map: Producer { + typealias Transform = (SourceType) throws -> ResultType + + private let source: Observable + + private let transform: Transform + + init(source: Observable, transform: @escaping Transform) { + self.source = source + self.transform = transform + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = MapSink(transform: self.transform, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Materialize.swift b/Pods/RxSwift/RxSwift/Observables/Materialize.swift new file mode 100644 index 0000000..e2577be --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Materialize.swift @@ -0,0 +1,44 @@ +// +// Materialize.swift +// RxSwift +// +// Created by sergdort on 08/03/2017. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Convert any Observable into an Observable of its events. + - seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html) + - returns: An observable sequence that wraps events in an Event. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable. + */ + public func materialize() -> Observable> { + Materialize(source: self.asObservable()) + } +} + +private final class MaterializeSink: Sink, ObserverType where Observer.Element == Event { + + func on(_ event: Event) { + self.forwardOn(.next(event)) + if event.isStopEvent { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Materialize: Producer> { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MaterializeSink(observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Merge.swift b/Pods/RxSwift/RxSwift/Observables/Merge.swift new file mode 100644 index 0000000..51a6462 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Merge.swift @@ -0,0 +1,600 @@ +// +// Merge.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/28/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + + - seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence. + */ + public func flatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMap(source: self.asObservable(), selector: selector) + } + +} + +extension ObservableType { + + /** + Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. + If element is received while there is some projected observable sequence being merged it will simply be ignored. + + - seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel. + - returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated. + */ + public func flatMapFirst(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapFirst(source: self.asObservable(), selector: selector) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Merges elements from all observable sequences in the given enumerable sequence into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public func merge() -> Observable { + Merge(source: self.asObservable()) + } + + /** + Merges elements from all inner observable sequences into a single observable sequence, limiting the number of concurrent subscriptions to inner sequences. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter maxConcurrent: Maximum number of inner observable sequences being subscribed to concurrently. + - returns: The observable sequence that merges the elements of the inner sequences. + */ + public func merge(maxConcurrent: Int) + -> Observable { + MergeLimited(source: self.asObservable(), maxConcurrent: maxConcurrent) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Concatenates all inner observable sequences, as long as the previous observable sequence terminated successfully. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + public func concat() -> Observable { + self.merge(maxConcurrent: 1) + } +} + +extension ObservableType { + /** + Merges elements from all observable sequences from collection into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Collection) -> Observable where Collection.Element == Observable { + MergeArray(sources: Array(sources)) + } + + /** + Merges elements from all observable sequences from array into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Array of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: [Observable]) -> Observable { + MergeArray(sources: sources) + } + + /** + Merges elements from all observable sequences into a single observable sequence. + + - seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html) + + - parameter sources: Collection of observable sequences to merge. + - returns: The observable sequence that merges the elements of the observable sequences. + */ + public static func merge(_ sources: Observable...) -> Observable { + MergeArray(sources: sources) + } +} + +// MARK: concatMap + +extension ObservableType { + /** + Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence. + + - seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html) + + - returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order. + */ + + public func concatMap(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return ConcatMap(source: self.asObservable(), selector: selector) + } +} + +private final class MergeLimitedSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where SourceSequence.Element == Observer.Element { + typealias Element = Observer.Element + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Parent = MergeLimitedSink + + private let parent: Parent + private let disposeKey: DisposeKey + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + if let next = self.parent.queue.dequeue() { + self.parent.subscribe(next, group: self.parent.group) + } + else { + self.parent.activeCount -= 1 + + if self.parent.stopped && self.parent.activeCount == 0 { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + } + } + } +} + +private final class ConcatMapSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(maxConcurrent: 1, observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeLimitedBasicSink: MergeLimitedSink where Observer.Element == SourceSequence.Element { + + override func performMap(_ element: SourceSequence) throws -> SourceSequence { + element + } +} + +private class MergeLimitedSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias QueueType = Queue + + let maxConcurrent: Int + + let lock = RecursiveLock() + + // state + var stopped = false + var activeCount = 0 + var queue = QueueType(capacity: 2) + + let sourceSubscription = SingleAssignmentDisposable() + let group = CompositeDisposable() + + init(maxConcurrent: Int, observer: Observer, cancel: Cancelable) { + self.maxConcurrent = maxConcurrent + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let disposable = source.subscribe(self) + self.sourceSubscription.setDisposable(disposable) + return self.group + } + + func subscribe(_ innerSource: SourceSequence, group: CompositeDisposable) { + let subscription = SingleAssignmentDisposable() + + let key = group.insert(subscription) + + if let key = key { + let observer = MergeLimitedSinkIter(parent: self, disposeKey: key) + + let disposable = innerSource.asObservable().subscribe(observer) + subscription.setDisposable(disposable) + } + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + let subscribe: Bool + if self.activeCount < self.maxConcurrent { + self.activeCount += 1 + subscribe = true + } + else { + do { + let value = try self.performMap(element) + self.queue.enqueue(value) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + subscribe = false + } + + if subscribe { + do { + return try self.performMap(element) + } catch { + self.forwardOn(.error(error)) + self.dispose() + } + } + + return nil + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let sequence = self.nextElementArrived(element: element) { + self.subscribe(sequence, group: self.group) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + if self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + else { + self.sourceSubscription.dispose() + } + + self.stopped = true + } + } + } +} + +final private class MergeLimited: Producer { + private let source: Observable + private let maxConcurrent: Int + + init(source: Observable, maxConcurrent: Int) { + self.source = source + self.maxConcurrent = maxConcurrent + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeLimitedBasicSink(maxConcurrent: self.maxConcurrent, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +// MARK: Merge + +private final class MergeBasicSink : MergeSink where Observer.Element == Source.Element { + override func performMap(_ element: Source) throws -> Source { + element + } +} + +// MARK: flatMap + +private final class FlatMapSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +// MARK: FlatMapFirst + +private final class FlatMapFirstSink : MergeSink where Observer.Element == SourceSequence.Element { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let selector: Selector + + override var subscribeNext: Bool { + self.activeCount == 0 + } + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceElement) throws -> SourceSequence { + try self.selector(element) + } +} + +private final class MergeSinkIter : ObserverType where Observer.Element == SourceSequence.Element { + typealias Parent = MergeSink + typealias DisposeKey = CompositeDisposable.DisposeKey + typealias Element = Observer.Element + + private let parent: Parent + private let disposeKey: DisposeKey + + init(parent: Parent, disposeKey: DisposeKey) { + self.parent = parent + self.disposeKey = disposeKey + } + + func on(_ event: Event) { + self.parent.lock.performLocked { + switch event { + case .next(let value): + self.parent.forwardOn(.next(value)) + case .error(let error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + case .completed: + self.parent.group.remove(for: self.disposeKey) + self.parent.activeCount -= 1 + self.parent.checkCompleted() + } + } + } +} + + +private class MergeSink + : Sink + , ObserverType where Observer.Element == SourceSequence.Element { + typealias ResultType = Observer.Element + typealias Element = SourceElement + + let lock = RecursiveLock() + + var subscribeNext: Bool { + true + } + + // state + let group = CompositeDisposable() + let sourceSubscription = SingleAssignmentDisposable() + + var activeCount = 0 + var stopped = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func performMap(_ element: SourceElement) throws -> SourceSequence { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: SourceElement) -> SourceSequence? { + self.lock.performLocked { + if !self.subscribeNext { + return nil + } + + do { + let value = try self.performMap(element) + self.activeCount += 1 + return value + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return nil + } + } + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let value = self.nextElementArrived(element: element) { + self.subscribeInner(value.asObservable()) + } + case .error(let error): + self.lock.performLocked { + self.forwardOn(.error(error)) + self.dispose() + } + case .completed: + self.lock.performLocked { + self.stopped = true + self.sourceSubscription.dispose() + self.checkCompleted() + } + } + } + + func subscribeInner(_ source: Observable) { + let iterDisposable = SingleAssignmentDisposable() + if let disposeKey = self.group.insert(iterDisposable) { + let iter = MergeSinkIter(parent: self, disposeKey: disposeKey) + let subscription = source.subscribe(iter) + iterDisposable.setDisposable(subscription) + } + } + + func run(_ sources: [Observable]) -> Disposable { + self.activeCount += sources.count + + for source in sources { + self.subscribeInner(source) + } + + self.stopped = true + + self.checkCompleted() + + return self.group + } + + @inline(__always) + func checkCompleted() { + if self.stopped && self.activeCount == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + + func run(_ source: Observable) -> Disposable { + _ = self.group.insert(self.sourceSubscription) + + let subscription = source.subscribe(self) + self.sourceSubscription.setDisposable(subscription) + + return self.group + } +} + +// MARK: Producers + +final private class FlatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapFirst: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = FlatMapFirstSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class ConcatMap: Producer { + typealias Selector = (SourceElement) throws -> SourceSequence + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = ConcatMapSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final class Merge : Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == SourceSequence.Element { + let sink = MergeBasicSink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class MergeArray: Producer { + private let sources: [Observable] + + init(sources: [Observable]) { + self.sources = sources + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = MergeBasicSink, Observer>(observer: observer, cancel: cancel) + let subscription = sink.run(self.sources) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Multicast.swift b/Pods/RxSwift/RxSwift/Observables/Multicast.swift new file mode 100644 index 0000000..1ebcf02 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Multicast.swift @@ -0,0 +1,405 @@ +// +// Multicast.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/** + Represents an observable wrapper that can be connected and disconnected from its underlying observable sequence. + */ +public class ConnectableObservable + : Observable + , ConnectableObservableType { + + /** + Connects the observable wrapper to its source. All subscribed observers will receive values from the underlying observable sequence as long as the connection is established. + + - returns: Disposable used to disconnect the observable wrapper from its source, causing subscribed observer to stop receiving values from the underlying observable sequence. + */ + public func connect() -> Disposable { + rxAbstractMethod() + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. + + Each subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's invocation. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subjectSelector: Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. + - parameter selector: Selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. + */ + public func multicast(_ subjectSelector: @escaping () throws -> Subject, selector: @escaping (Observable) throws -> Observable) + -> Observable where Subject.Observer.Element == Element { + return Multicast( + source: self.asObservable(), + subjectSelector: subjectSelector, + selector: selector + ) + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence. + + This operator is a specialization of `multicast` using a `PublishSubject`. + + - seealso: [publish operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func publish() -> ConnectableObservable { + self.multicast { PublishSubject() } + } +} + +extension ObservableType { + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying bufferSize elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - parameter bufferSize: Maximum element count of the replay buffer. + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replay(_ bufferSize: Int) + -> ConnectableObservable { + self.multicast { ReplaySubject.create(bufferSize: bufferSize) } + } + + /** + Returns a connectable observable sequence that shares a single subscription to the underlying sequence replaying all elements. + + This operator is a specialization of `multicast` using a `ReplaySubject`. + + - seealso: [replay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: A connectable observable sequence that shares a single subscription to the underlying sequence. + */ + public func replayAll() + -> ConnectableObservable { + self.multicast { ReplaySubject.createUnbounded() } + } +} + +extension ConnectableObservableType { + + /** + Returns an observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + + - seealso: [refCount operator on reactivex.io](http://reactivex.io/documentation/operators/refcount.html) + + - returns: An observable sequence that stays connected to the source as long as there is at least one subscription to the observable sequence. + */ + public func refCount() -> Observable { + RefCount(source: self) + } +} + +extension ObservableType { + + /** + Multicasts the source sequence notifications through the specified subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + For specializations with fixed subject types, see `publish` and `replay`. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter subject: Subject to push source elements into. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(_ subject: Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: { subject }) + } + + /** + Multicasts the source sequence notifications through an instantiated subject to the resulting connectable observable. + + Upon connection of the connectable observable, the subject is subscribed to the source exactly one, and messages are forwarded to the observers registered with the connectable observable. + + Subject is cleared on connection disposal or in case source sequence produces terminal event. + + - seealso: [multicast operator on reactivex.io](http://reactivex.io/documentation/operators/publish.html) + + - parameter makeSubject: Factory function used to instantiate a subject for each connection. + - returns: A connectable observable sequence that upon connection causes the source sequence to push results into the specified subject. + */ + public func multicast(makeSubject: @escaping () -> Subject) + -> ConnectableObservable where Subject.Observer.Element == Element { + ConnectableObservableAdapter(source: self.asObservable(), makeSubject: makeSubject) + } +} + +final private class Connection: ObserverType, Disposable { + typealias Element = Subject.Observer.Element + + private var lock: RecursiveLock + // state + private var parent: ConnectableObservableAdapter? + private var subscription : Disposable? + private var subjectObserver: Subject.Observer + + private let disposed = AtomicInt(0) + + init(parent: ConnectableObservableAdapter, subjectObserver: Subject.Observer, lock: RecursiveLock, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + self.lock = lock + self.subjectObserver = subjectObserver + } + + func on(_ event: Event) { + if isFlagSet(self.disposed, 1) { + return + } + if event.isStopEvent { + self.dispose() + } + self.subjectObserver.on(event) + } + + func dispose() { + lock.lock(); defer { lock.unlock() } + fetchOr(self.disposed, 1) + guard let parent = self.parent else { + return + } + + if parent.connection === self { + parent.connection = nil + parent.subject = nil + } + self.parent = nil + + self.subscription?.dispose() + self.subscription = nil + } +} + +final private class ConnectableObservableAdapter + : ConnectableObservable { + typealias ConnectionType = Connection + + private let source: Observable + private let makeSubject: () -> Subject + + fileprivate let lock = RecursiveLock() + fileprivate var subject: Subject? + + // state + fileprivate var connection: ConnectionType? + + init(source: Observable, makeSubject: @escaping () -> Subject) { + self.source = source + self.makeSubject = makeSubject + self.subject = nil + self.connection = nil + } + + override func connect() -> Disposable { + return self.lock.performLocked { + if let connection = self.connection { + return connection + } + + let singleAssignmentDisposable = SingleAssignmentDisposable() + let connection = Connection(parent: self, subjectObserver: self.lazySubject.asObserver(), lock: self.lock, subscription: singleAssignmentDisposable) + self.connection = connection + let subscription = self.source.subscribe(connection) + singleAssignmentDisposable.setDisposable(subscription) + return connection + } + } + + private var lazySubject: Subject { + if let subject = self.subject { + return subject + } + + let subject = self.makeSubject() + self.subject = subject + return subject + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Subject.Element { + self.lazySubject.subscribe(observer) + } +} + +final private class RefCountSink + : Sink + , ObserverType where ConnectableSource.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RefCount + + private let parent: Parent + + private var connectionIdSnapshot: Int64 = -1 + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + + self.connectionIdSnapshot = self.parent.connectionId + + if self.isDisposed { + return Disposables.create() + } + + if self.parent.count == 0 { + self.parent.count = 1 + self.parent.connectableSubscription = self.parent.source.connect() + } + else { + self.parent.count += 1 + } + + return Disposables.create { + subscription.dispose() + self.parent.lock.lock(); defer { self.parent.lock.unlock() } + if self.parent.connectionId != self.connectionIdSnapshot { + return + } + if self.parent.count == 1 { + self.parent.count = 0 + guard let connectableSubscription = self.parent.connectableSubscription else { + return + } + + connectableSubscription.dispose() + self.parent.connectableSubscription = nil + } + else if self.parent.count > 1 { + self.parent.count -= 1 + } + else { + rxFatalError("Something went wrong with RefCount disposing mechanism") + } + } + } + + func on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error, .completed: + self.parent.lock.lock() + if self.parent.connectionId == self.connectionIdSnapshot { + let connection = self.parent.connectableSubscription + defer { connection?.dispose() } + self.parent.count = 0 + self.parent.connectionId = self.parent.connectionId &+ 1 + self.parent.connectableSubscription = nil + } + self.parent.lock.unlock() + self.forwardOn(event) + self.dispose() + } + } +} + +final private class RefCount: Producer { + fileprivate let lock = RecursiveLock() + + // state + fileprivate var count = 0 + fileprivate var connectionId: Int64 = 0 + fileprivate var connectableSubscription = nil as Disposable? + + fileprivate let source: ConnectableSource + + init(source: ConnectableSource) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) + where Observer.Element == ConnectableSource.Element { + let sink = RefCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class MulticastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias ResultType = Element + typealias MutlicastType = Multicast + + private let parent: MutlicastType + + init(parent: MutlicastType, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + do { + let subject = try self.parent.subjectSelector() + let connectable = ConnectableObservableAdapter(source: self.parent.source, makeSubject: { subject }) + + let observable = try self.parent.selector(connectable) + + let subscription = observable.subscribe(self) + let connection = connectable.connect() + + return Disposables.create(subscription, connection) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + return Disposables.create() + } + } + + func on(_ event: Event) { + self.forwardOn(event) + switch event { + case .next: break + case .error, .completed: + self.dispose() + } + } +} + +final private class Multicast: Producer { + typealias SubjectSelectorType = () throws -> Subject + typealias SelectorType = (Observable) throws -> Observable + + fileprivate let source: Observable + fileprivate let subjectSelector: SubjectSelectorType + fileprivate let selector: SelectorType + + init(source: Observable, subjectSelector: @escaping SubjectSelectorType, selector: @escaping SelectorType) { + self.source = source + self.subjectSelector = subjectSelector + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = MulticastSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Never.swift b/Pods/RxSwift/RxSwift/Observables/Never.swift new file mode 100644 index 0000000..7b456ee --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Never.swift @@ -0,0 +1,27 @@ +// +// Never.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a non-terminating observable sequence, which can be used to denote an infinite duration. + + - seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html) + + - returns: An observable sequence whose observers will never get called. + */ + public static func never() -> Observable { + NeverProducer() + } +} + +final private class NeverProducer: Producer { + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift b/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift new file mode 100644 index 0000000..6b8689e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ObserveOn.swift @@ -0,0 +1,243 @@ +// +// ObserveOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + public func observe(on scheduler: ImmediateSchedulerType) + -> Observable { + guard let serialScheduler = scheduler as? SerialDispatchQueueScheduler else { + return ObserveOn(source: self.asObservable(), scheduler: scheduler) + } + + return ObserveOnSerialDispatchQueue(source: self.asObservable(), + scheduler: serialScheduler) + } + + /** + Wraps the source sequence in order to run its observer callbacks on the specified scheduler. + + This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription + actions have side-effects that require to be run on a scheduler, use `subscribeOn`. + + - seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html) + + - parameter scheduler: Scheduler to notify observers on. + - returns: The source sequence whose observations happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "observe(on:)") + public func observeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + observe(on: scheduler) + } +} + +final private class ObserveOn: Producer { + let scheduler: ImmediateSchedulerType + let source: Observable + + init(source: Observable, scheduler: ImmediateSchedulerType) { + self.scheduler = scheduler + self.source = source + +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +enum ObserveOnState : Int32 { + // pump is not running + case stopped = 0 + // pump is running + case running = 1 +} + +final private class ObserveOnSink: ObserverBase { + typealias Element = Observer.Element + + let scheduler: ImmediateSchedulerType + + var lock = SpinLock() + let observer: Observer + + // state + var state = ObserveOnState.stopped + var queue = Queue>(capacity: 10) + + let scheduleDisposable = SerialDisposable() + let cancel: Cancelable + + init(scheduler: ImmediateSchedulerType, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + } + + override func onCore(_ event: Event) { + let shouldStart = self.lock.performLocked { () -> Bool in + self.queue.enqueue(event) + + switch self.state { + case .stopped: + self.state = .running + return true + case .running: + return false + } + } + + if shouldStart { + self.scheduleDisposable.disposable = self.scheduler.scheduleRecursive((), action: self.run) + } + } + + func run(_ state: (), _ recurse: (()) -> Void) { + let (nextEvent, observer) = self.lock.performLocked { () -> (Event?, Observer) in + if !self.queue.isEmpty { + return (self.queue.dequeue(), self.observer) + } + else { + self.state = .stopped + return (nil, self.observer) + } + } + + if let nextEvent = nextEvent, !self.cancel.isDisposed { + observer.on(nextEvent) + if nextEvent.isStopEvent { + self.dispose() + } + } + else { + return + } + + let shouldContinue = self.shouldContinue_synchronized() + + if shouldContinue { + recurse(()) + } + } + + func shouldContinue_synchronized() -> Bool { + self.lock.performLocked { + let isEmpty = self.queue.isEmpty + if isEmpty { self.state = .stopped } + return !isEmpty + } + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + self.scheduleDisposable.dispose() + } +} + +#if TRACE_RESOURCES + private let numberOfSerialDispatchObservables = AtomicInt(0) + extension Resources { + /** + Counts number of `SerialDispatchQueueObservables`. + + Purposed for unit tests. + */ + public static var numberOfSerialDispatchQueueObservables: Int32 { + return load(numberOfSerialDispatchObservables) + } + } +#endif + +final private class ObserveOnSerialDispatchQueueSink: ObserverBase { + let scheduler: SerialDispatchQueueScheduler + let observer: Observer + + let cancel: Cancelable + + var cachedScheduleLambda: (((sink: ObserveOnSerialDispatchQueueSink, event: Event)) -> Disposable)! + + init(scheduler: SerialDispatchQueueScheduler, observer: Observer, cancel: Cancelable) { + self.scheduler = scheduler + self.observer = observer + self.cancel = cancel + super.init() + + self.cachedScheduleLambda = { pair in + guard !cancel.isDisposed else { return Disposables.create() } + + pair.sink.observer.on(pair.event) + + if pair.event.isStopEvent { + pair.sink.dispose() + } + + return Disposables.create() + } + } + + override func onCore(_ event: Event) { + _ = self.scheduler.schedule((self, event), action: self.cachedScheduleLambda!) + } + + override func dispose() { + super.dispose() + + self.cancel.dispose() + } +} + +final private class ObserveOnSerialDispatchQueue: Producer { + let scheduler: SerialDispatchQueueScheduler + let source: Observable + + init(source: Observable, scheduler: SerialDispatchQueueScheduler) { + self.scheduler = scheduler + self.source = source + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + _ = increment(numberOfSerialDispatchObservables) + #endif + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObserveOnSerialDispatchQueueSink(scheduler: self.scheduler, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + _ = decrement(numberOfSerialDispatchObservables) + } + #endif +} diff --git a/Pods/RxSwift/RxSwift/Observables/Optional.swift b/Pods/RxSwift/RxSwift/Observables/Optional.swift new file mode 100644 index 0000000..64f8f1f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Optional.swift @@ -0,0 +1,95 @@ +// +// Optional.swift +// RxSwift +// +// Created by tarunon on 2016/12/13. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?) -> Observable { + ObservableOptional(optional: optional) + } + + /** + Converts a optional to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter optional: Optional element in the resulting observable sequence. + - parameter scheduler: Scheduler to send the optional element on. + - returns: An observable sequence containing the wrapped value or not from given optional. + */ + public static func from(optional: Element?, scheduler: ImmediateSchedulerType) -> Observable { + ObservableOptionalScheduled(optional: optional, scheduler: scheduler) + } +} + +final private class ObservableOptionalScheduledSink: Sink { + typealias Element = Observer.Element + typealias Parent = ObservableOptionalScheduled + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedule(self.parent.optional) { (optional: Element?) -> Disposable in + if let next = optional { + self.forwardOn(.next(next)) + return self.parent.scheduler.schedule(()) { _ in + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } else { + self.forwardOn(.completed) + self.dispose() + return Disposables.create() + } + } + } +} + +final private class ObservableOptionalScheduled: Producer { + fileprivate let optional: Element? + fileprivate let scheduler: ImmediateSchedulerType + + init(optional: Element?, scheduler: ImmediateSchedulerType) { + self.optional = optional + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class ObservableOptional: Producer { + private let optional: Element? + + init(optional: Element?) { + self.optional = optional + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if let element = self.optional { + observer.on(.next(element)) + } + observer.on(.completed) + return Disposables.create() + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Producer.swift b/Pods/RxSwift/RxSwift/Observables/Producer.swift new file mode 100644 index 0000000..e611930 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Producer.swift @@ -0,0 +1,92 @@ +// +// Producer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/20/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Producer: Observable { + override init() { + super.init() + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + if !CurrentThreadScheduler.isScheduleRequired { + // The returned disposable needs to release all references once it was disposed. + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + else { + return CurrentThreadScheduler.instance.schedule(()) { _ in + let disposer = SinkDisposer() + let sinkAndSubscription = self.run(observer, cancel: disposer) + disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription) + + return disposer + } + } + } + + func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + rxAbstractMethod() + } +} + +private final class SinkDisposer: Cancelable { + private enum DisposeState: Int32 { + case disposed = 1 + case sinkAndSubscriptionSet = 2 + } + + private let state = AtomicInt(0) + private var sink: Disposable? + private var subscription: Disposable? + + var isDisposed: Bool { + isFlagSet(self.state, DisposeState.disposed.rawValue) + } + + func setSinkAndSubscription(sink: Disposable, subscription: Disposable) { + self.sink = sink + self.subscription = subscription + + let previousState = fetchOr(self.state, DisposeState.sinkAndSubscriptionSet.rawValue) + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + rxFatalError("Sink and subscription were already set") + } + + if (previousState & DisposeState.disposed.rawValue) != 0 { + sink.dispose() + subscription.dispose() + self.sink = nil + self.subscription = nil + } + } + + func dispose() { + let previousState = fetchOr(self.state, DisposeState.disposed.rawValue) + + if (previousState & DisposeState.disposed.rawValue) != 0 { + return + } + + if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 { + guard let sink = self.sink else { + rxFatalError("Sink not set") + } + guard let subscription = self.subscription else { + rxFatalError("Subscription not set") + } + + sink.dispose() + subscription.dispose() + + self.sink = nil + self.subscription = nil + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Range.swift b/Pods/RxSwift/RxSwift/Observables/Range.swift new file mode 100644 index 0000000..2453532 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Range.swift @@ -0,0 +1,73 @@ +// +// Range.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages. + + - seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html) + + - parameter start: The value of the first integer in the sequence. + - parameter count: The number of sequential integers to generate. + - parameter scheduler: Scheduler to run the generator loop on. + - returns: An observable sequence that contains a range of sequential integral numbers. + */ + public static func range(start: Element, count: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RangeProducer(start: start, count: count, scheduler: scheduler) + } +} + +final private class RangeProducer: Producer { + fileprivate let start: Element + fileprivate let count: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(start: Element, count: Element, scheduler: ImmediateSchedulerType) { + guard count >= 0 else { + rxFatalError("count can't be negative") + } + + guard start &+ (count - 1) >= start || count == 0 else { + rxFatalError("overflow of count") + } + + self.start = start + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RangeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +final private class RangeSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = RangeProducer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(0 as Observer.Element) { i, recurse in + if i < self.parent.count { + self.forwardOn(.next(self.parent.start + i)) + recurse(i + 1) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Reduce.swift b/Pods/RxSwift/RxSwift/Observables/Reduce.swift new file mode 100644 index 0000000..d5fab34 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Reduce.swift @@ -0,0 +1,109 @@ +// +// Reduce.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + +extension ObservableType { + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - parameter mapResult: A function to transform the final accumulator value into the result value. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A, mapResult: @escaping (A) throws -> Result) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: mapResult) + } + + /** + Applies an `accumulator` function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified `seed` value is used as the initial accumulator value. + + For aggregation behavior with incremental intermediate results, see `scan`. + + - seealso: [reduce operator on reactivex.io](http://reactivex.io/documentation/operators/reduce.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: A accumulator function to be invoked on each element. + - returns: An observable sequence containing a single element with the final accumulator value. + */ + public func reduce(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + Reduce(source: self.asObservable(), seed: seed, accumulator: accumulator, mapResult: { $0 }) + } +} + +final private class ReduceSink: Sink, ObserverType { + typealias ResultType = Observer.Element + typealias Parent = Reduce + + private let parent: Parent + private var accumulation: AccumulateType + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulation = parent.seed + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + self.accumulation = try self.parent.accumulator(self.accumulation, value) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + do { + let result = try self.parent.mapResult(self.accumulation) + self.forwardOn(.next(result)) + self.forwardOn(.completed) + self.dispose() + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } +} + +final private class Reduce: Producer { + typealias AccumulatorType = (AccumulateType, SourceType) throws -> AccumulateType + typealias ResultSelectorType = (AccumulateType) throws -> ResultType + + private let source: Observable + fileprivate let seed: AccumulateType + fileprivate let accumulator: AccumulatorType + fileprivate let mapResult: ResultSelectorType + + init(source: Observable, seed: AccumulateType, accumulator: @escaping AccumulatorType, mapResult: @escaping ResultSelectorType) { + self.source = source + self.seed = seed + self.accumulator = accumulator + self.mapResult = mapResult + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = ReduceSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + diff --git a/Pods/RxSwift/RxSwift/Observables/Repeat.swift b/Pods/RxSwift/RxSwift/Observables/Repeat.swift new file mode 100644 index 0000000..69a3ba0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Repeat.swift @@ -0,0 +1,57 @@ +// +// Repeat.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/13/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages. + + - seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html) + + - parameter element: Element to repeat. + - parameter scheduler: Scheduler to run the producer loop on. + - returns: An observable sequence that repeats the given element infinitely. + */ + public static func repeatElement(_ element: Element, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + RepeatElement(element: element, scheduler: scheduler) + } +} + +final private class RepeatElement: Producer { + fileprivate let element: Element + fileprivate let scheduler: ImmediateSchedulerType + + init(element: Element, scheduler: ImmediateSchedulerType) { + self.element = element + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RepeatElementSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + + return (sink: sink, subscription: subscription) + } +} + +final private class RepeatElementSink: Sink { + typealias Parent = RepeatElement + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.element) { e, recurse in + self.forwardOn(.next(e)) + recurse(e) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift b/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift new file mode 100644 index 0000000..52a2709 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/RetryWhen.swift @@ -0,0 +1,211 @@ +// +// RetryWhen.swift +// RxSwift +// +// Created by Junior B. on 06/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + retry(when: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + public func retry(when notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } + + /** + Repeats the source observable sequence on error when the notifier emits a next value. + If the source observable errors and the notifier completes, it will complete the source sequence. + + - seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html) + + - parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable. + - returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete. + */ + @available(*, deprecated, renamed: "retry(when:)") + public func retryWhen(_ notificationHandler: @escaping (Observable) -> TriggerObservable) + -> Observable { + RetryWhenSequence(sources: InfiniteSequence(repeatedValue: self.asObservable()), notificationHandler: notificationHandler) + } +} + +final private class RetryTriggerSink + : ObserverType where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = TriggerObservable.Element + + typealias Parent = RetryWhenSequenceSinkIter + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.parent.lastError = nil + self.parent.parent.schedule(.moveNext) + case .error(let e): + self.parent.parent.forwardOn(.error(e)) + self.parent.parent.dispose() + case .completed: + self.parent.parent.forwardOn(.completed) + self.parent.parent.dispose() + } + } +} + +final private class RetryWhenSequenceSinkIter + : ObserverType + , Disposable where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequenceSink + + fileprivate let parent: Parent + private let errorHandlerSubscription = SingleAssignmentDisposable() + private let subscription: Disposable + + init(parent: Parent, subscription: Disposable) { + self.parent = parent + self.subscription = subscription + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error(let error): + self.parent.lastError = error + + if let failedWith = error as? Error { + // dispose current subscription + self.subscription.dispose() + + let errorHandlerSubscription = self.parent.notifier.subscribe(RetryTriggerSink(parent: self)) + self.errorHandlerSubscription.setDisposable(errorHandlerSubscription) + self.parent.errorSubject.on(.next(failedWith)) + } + else { + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } + + final func dispose() { + self.subscription.dispose() + self.errorHandlerSubscription.dispose() + } +} + +final private class RetryWhenSequenceSink + : TailRecursiveSink where Sequence.Element: ObservableType, Sequence.Element.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = RetryWhenSequence + + let lock = RecursiveLock() + + private let parent: Parent + + fileprivate var lastError: Swift.Error? + fileprivate let errorSubject = PublishSubject() + private let handler: Observable + fileprivate let notifier = PublishSubject() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.handler = parent.notificationHandler(self.errorSubject).asObservable() + super.init(observer: observer, cancel: cancel) + } + + override func done() { + if let lastError = self.lastError { + self.forwardOn(.error(lastError)) + self.lastError = nil + } + else { + self.forwardOn(.completed) + } + + self.dispose() + } + + override func extract(_ observable: Observable) -> SequenceGenerator? { + // It is important to always return `nil` here because there are sideffects in the `run` method + // that are dependant on particular `retryWhen` operator so single operator stack can't be reused in this + // case. + return nil + } + + override func subscribeToNext(_ source: Observable) -> Disposable { + let subscription = SingleAssignmentDisposable() + let iter = RetryWhenSequenceSinkIter(parent: self, subscription: subscription) + subscription.setDisposable(source.subscribe(iter)) + return iter + } + + override func run(_ sources: SequenceGenerator) -> Disposable { + let triggerSubscription = self.handler.subscribe(self.notifier.asObserver()) + let superSubscription = super.run(sources) + return Disposables.create(superSubscription, triggerSubscription) + } +} + +final private class RetryWhenSequence: Producer where Sequence.Element: ObservableType { + typealias Element = Sequence.Element.Element + + private let sources: Sequence + fileprivate let notificationHandler: (Observable) -> TriggerObservable + + init(sources: Sequence, notificationHandler: @escaping (Observable) -> TriggerObservable) { + self.sources = sources + self.notificationHandler = notificationHandler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = RetryWhenSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run((self.sources.makeIterator(), nil)) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sample.swift b/Pods/RxSwift/RxSwift/Observables/Sample.swift new file mode 100644 index 0000000..9301c9a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sample.swift @@ -0,0 +1,139 @@ +// +// Sample.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/1/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Samples the source observable sequence using a sampler observable sequence producing sampling ticks. + + Upon each sampling tick, the latest element (if any) in the source sequence during the last sampling interval is sent to the resulting sequence. + + **In case there were no new elements between sampler ticks, you may provide a default value to be emitted, instead + to the resulting sequence otherwise no element is sent.** + + - seealso: [sample operator on reactivex.io](http://reactivex.io/documentation/operators/sample.html) + + - parameter sampler: Sampling tick sequence. + - parameter defaultValue: a value to return if there are no new elements between sampler ticks + - returns: Sampled observable sequence. + */ + public func sample(_ sampler: Source, defaultValue: Element? = nil) + -> Observable { + return Sample(source: self.asObservable(), sampler: sampler.asObservable(), defaultValue: defaultValue) + } +} + +final private class SamplerSink + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = SampleType + + typealias Parent = SampleSequenceSink + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next, .completed: + if let element = parent.element ?? self.parent.defaultValue { + self.parent.element = nil + self.parent.forwardOn(.next(element)) + } + + if self.parent.atEnd { + self.parent.forwardOn(.completed) + self.parent.dispose() + } + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + } + } +} + +final private class SampleSequenceSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = Sample + + fileprivate let parent: Parent + fileprivate let defaultValue: Element? + + let lock = RecursiveLock() + + // state + fileprivate var element = nil as Element? + fileprivate var atEnd = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable, defaultValue: Element? = nil) { + self.parent = parent + self.defaultValue = defaultValue + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + self.sourceSubscription.setDisposable(self.parent.source.subscribe(self)) + let samplerSubscription = self.parent.sampler.subscribe(SamplerSink(parent: self)) + + return Disposables.create(sourceSubscription, samplerSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + self.element = element + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.atEnd = true + self.sourceSubscription.dispose() + } + } + +} + +final private class Sample: Producer { + fileprivate let source: Observable + fileprivate let sampler: Observable + fileprivate let defaultValue: Element? + + init(source: Observable, sampler: Observable, defaultValue: Element? = nil) { + self.source = source + self.sampler = sampler + self.defaultValue = defaultValue + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SampleSequenceSink(parent: self, observer: observer, cancel: cancel, defaultValue: self.defaultValue) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Scan.swift b/Pods/RxSwift/RxSwift/Observables/Scan.swift new file mode 100644 index 0000000..ecf69c8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Scan.swift @@ -0,0 +1,100 @@ +// +// Scan.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(into seed: A, accumulator: @escaping (inout A, Element) throws -> Void) + -> Observable { + Scan(source: self.asObservable(), seed: seed, accumulator: accumulator) + } + + /** + Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value. + + For aggregation behavior with no intermediate results, see `reduce`. + + - seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html) + + - parameter seed: The initial accumulator value. + - parameter accumulator: An accumulator function to be invoked on each element. + - returns: An observable sequence containing the accumulated values. + */ + public func scan(_ seed: A, accumulator: @escaping (A, Element) throws -> A) + -> Observable { + return Scan(source: self.asObservable(), seed: seed) { acc, element in + let currentAcc = acc + acc = try accumulator(currentAcc, element) + } + } +} + +final private class ScanSink: Sink, ObserverType { + typealias Accumulate = Observer.Element + typealias Parent = Scan + + private let parent: Parent + private var accumulate: Accumulate + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.accumulate = parent.seed + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let element): + do { + try self.parent.accumulator(&self.accumulate, element) + self.forwardOn(.next(self.accumulate)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } + +} + +final private class Scan: Producer { + typealias Accumulator = (inout Accumulate, Element) throws -> Void + + private let source: Observable + fileprivate let seed: Accumulate + fileprivate let accumulator: Accumulator + + init(source: Observable, seed: Accumulate, accumulator: @escaping Accumulator) { + self.source = source + self.seed = seed + self.accumulator = accumulator + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Accumulate { + let sink = ScanSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sequence.swift b/Pods/RxSwift/RxSwift/Observables/Sequence.swift new file mode 100644 index 0000000..c6d1089 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sequence.swift @@ -0,0 +1,89 @@ +// +// Sequence.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + // MARK: of + + /** + This method creates a new Observable instance with a variable number of elements. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - parameter elements: Elements to generate. + - parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediately on subscription. + - returns: The observable sequence whose elements are pulled from the given arguments. + */ + public static func of(_ elements: Element ..., scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: elements, scheduler: scheduler) + } +} + +extension ObservableType { + /** + Converts an array to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ array: [Element], scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable { + ObservableSequence(elements: array, scheduler: scheduler) + } + + /** + Converts a sequence to an observable sequence. + + - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) + + - returns: The observable sequence whose elements are pulled from the given enumerable sequence. + */ + public static func from(_ sequence: Sequence, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable where Sequence.Element == Element { + ObservableSequence(elements: sequence, scheduler: scheduler) + } +} + +final private class ObservableSequenceSink: Sink where Sequence.Element == Observer.Element { + typealias Parent = ObservableSequence + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRecursive(self.parent.elements.makeIterator()) { iterator, recurse in + var mutableIterator = iterator + if let next = mutableIterator.next() { + self.forwardOn(.next(next)) + recurse(mutableIterator) + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class ObservableSequence: Producer { + fileprivate let elements: Sequence + fileprivate let scheduler: ImmediateSchedulerType + + init(elements: Sequence, scheduler: ImmediateSchedulerType) { + self.elements = elements + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ObservableSequenceSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift b/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift new file mode 100644 index 0000000..59d440d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift @@ -0,0 +1,443 @@ +// +// ShareReplayScope.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/28/17. +// Copyright © 2017 Krunoslav Zaher. All rights reserved. +// + +/// Subject lifetime scope +public enum SubjectLifetimeScope { + /** + **Each connection will have it's own subject instance to store replay events.** + **Connections will be isolated from each another.** + + Configures the underlying implementation to behave equivalent to. + + ``` + source.multicast(makeSubject: { MySubject() }).refCount() + ``` + + **This is the recommended default.** + + This has the following consequences: + * `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state. + * Each connection to source observable sequence will use it's own subject. + * When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared. + + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .whileConnected) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + + ``` + + Notice how time interval is different and `Performing work ...` is printed each time) + + ``` + Performing work ... + next 1495998900.82141 + completed + + Performing work ... + next 1495998900.82359 + completed + + Performing work ... + next 1495998900.82444 + completed + + + ``` + + */ + case whileConnected + + /** + **One subject will store replay events for all connections to source.** + **Connections won't be isolated from each another.** + + Configures the underlying implementation behave equivalent to. + + ``` + source.multicast(MySubject()).refCount() + ``` + + This has the following consequences: + * Using `retry` or `concat` operators after this operator usually isn't advised. + * Each connection to source observable sequence will share the same subject. + * After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will + continue holding a reference to the same subject. + If at some later moment a new observer initiates a new connection to source it can potentially receive + some of the stale events received during previous connection. + * After source sequence terminates any new observer will always immediately receive replayed elements and terminal event. + No new subscriptions to source observable sequence will be attempted. + + ``` + let xs = Observable.deferred { () -> Observable in + print("Performing work ...") + return Observable.just(Date().timeIntervalSince1970) + } + .share(replay: 1, scope: .forever) + + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + _ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") }) + ``` + + Notice how time interval is the same, replayed, and `Performing work ...` is printed only once + + ``` + Performing work ... + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + + next 1495999013.76356 + completed + ``` + + */ + case forever +} + +extension ObservableType { + + /** + Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer. + + This operator is equivalent to: + * `.whileConnected` + ``` + // Each connection will have it's own subject instance to store replay events. + // Connections will be isolated from each another. + source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount() + ``` + * `.forever` + ``` + // One subject will store replay events for all connections to source. + // Connections won't be isolated from each another. + source.multicast(Replay.create(bufferSize: replay)).refCount() + ``` + + It uses optimized versions of the operators for most common operations. + + - parameter replay: Maximum element count of the replay buffer. + - parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum. + + - seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html) + + - returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. + */ + public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected) + -> Observable { + switch scope { + case .forever: + switch replay { + case 0: return self.multicast(PublishSubject()).refCount() + default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount() + } + case .whileConnected: + switch replay { + case 0: return ShareWhileConnected(source: self.asObservable()) + case 1: return ShareReplay1WhileConnected(source: self.asObservable()) + default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount() + } + } + } +} + +private final class ShareReplay1WhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareReplay1WhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + private var element: Element? + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next(let element): + self.element = element + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + if let element = self.element { + observer.on(.next(element)) + } + + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareReplay1WhileConnected + : Observable { + + fileprivate typealias Connection = ShareReplay1WhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareReplay1WhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} + +private final class ShareWhileConnectedConnection + : ObserverType + , SynchronizedUnsubscribeType { + typealias Observers = AnyObserver.s + typealias DisposeKey = Observers.KeyType + + typealias Parent = ShareWhileConnected + private let parent: Parent + private let subscription = SingleAssignmentDisposable() + + private let lock: RecursiveLock + private var disposed: Bool = false + fileprivate var observers = Observers() + + init(parent: Parent, lock: RecursiveLock) { + self.parent = parent + self.lock = lock + + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + final func on(_ event: Event) { + let observers = self.lock.performLocked { self.synchronized_on(event) } + dispatch(observers, event) + } + + final private func synchronized_on(_ event: Event) -> Observers { + if self.disposed { + return Observers() + } + + switch event { + case .next: + return self.observers + case .error, .completed: + let observers = self.observers + self.synchronized_dispose() + return observers + } + } + + final func connect() { + self.subscription.setDisposable(self.parent.source.subscribe(self)) + } + + final func synchronized_subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.performLocked { + let disposeKey = self.observers.insert(observer.on) + + return SubscriptionDisposable(owner: self, key: disposeKey) + } + } + + final private func synchronized_dispose() { + self.disposed = true + if self.parent.connection === self { + self.parent.connection = nil + } + self.observers = Observers() + } + + final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) { + if self.lock.performLocked({ self.synchronized_unsubscribe(disposeKey) }) { + self.subscription.dispose() + } + } + + @inline(__always) + final private func synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool { + // if already unsubscribed, just return + if self.observers.removeKey(disposeKey) == nil { + return false + } + + if self.observers.count == 0 { + self.synchronized_dispose() + return true + } + + return false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// optimized version of share replay for most common case +final private class ShareWhileConnected + : Observable { + + fileprivate typealias Connection = ShareWhileConnectedConnection + + fileprivate let source: Observable + + private let lock = RecursiveLock() + + fileprivate var connection: Connection? + + init(source: Observable) { + self.source = source + } + + override func subscribe(_ observer: Observer) -> Disposable where Observer.Element == Element { + self.lock.lock() + let connection = self.synchronized_subscribe(observer) + let count = connection.observers.count + + let disposable = connection.synchronized_subscribe(observer) + self.lock.unlock() + + if count == 0 { + connection.connect() + } + + return disposable + } + + @inline(__always) + private func synchronized_subscribe(_ observer: Observer) -> Connection where Observer.Element == Element { + let connection: Connection + + if let existingConnection = self.connection { + connection = existingConnection + } + else { + connection = ShareWhileConnectedConnection( + parent: self, + lock: self.lock) + self.connection = connection + } + + return connection + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift b/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift new file mode 100644 index 0000000..04e2217 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SingleAsync.swift @@ -0,0 +1,104 @@ +// +// SingleAsync.swift +// RxSwift +// +// Created by Junior B. on 09/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + The single operator is similar to first, but throws a `RxError.noElements` or `RxError.moreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single() + -> Observable { + SingleAsync(source: self.asObservable()) + } + + /** + The single operator is similar to first, but throws a `RxError.NoElements` or `RxError.MoreThanOneElement` + if the source Observable does not emit exactly one element before successfully completing. + + - seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html) + + - parameter predicate: A function to test each source element for a condition. + - returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted. + */ + public func single(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + SingleAsync(source: self.asObservable(), predicate: predicate) + } +} + +private final class SingleAsyncSink : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SingleAsync + + private let parent: Parent + private var seenValue: Bool = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + do { + let forward = try self.parent.predicate?(value) ?? true + if !forward { + return + } + } + catch let error { + self.forwardOn(.error(error as Swift.Error)) + self.dispose() + return + } + + if self.seenValue { + self.forwardOn(.error(RxError.moreThanOneElement)) + self.dispose() + return + } + + self.seenValue = true + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.seenValue { + self.forwardOn(.completed) + } else { + self.forwardOn(.error(RxError.noElements)) + } + self.dispose() + } + } +} + +final class SingleAsync: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate? + + init(source: Observable, predicate: Predicate? = nil) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SingleAsyncSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Sink.swift b/Pods/RxSwift/RxSwift/Observables/Sink.swift new file mode 100644 index 0000000..ed4fec0 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Sink.swift @@ -0,0 +1,75 @@ +// +// Sink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class Sink: Disposable { + fileprivate let observer: Observer + fileprivate let cancel: Cancelable + private let disposed = AtomicInt(0) + + #if DEBUG + private let synchronizationTracker = SynchronizationTracker() + #endif + + init(observer: Observer, cancel: Cancelable) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.observer = observer + self.cancel = cancel + } + + final func forwardOn(_ event: Event) { + #if DEBUG + self.synchronizationTracker.register(synchronizationErrorMessage: .default) + defer { self.synchronizationTracker.unregister() } + #endif + if isFlagSet(self.disposed, 1) { + return + } + self.observer.on(event) + } + + final func forwarder() -> SinkForward { + SinkForward(forward: self) + } + + final var isDisposed: Bool { + isFlagSet(self.disposed, 1) + } + + func dispose() { + fetchOr(self.disposed, 1) + self.cancel.dispose() + } + + deinit { +#if TRACE_RESOURCES + _ = Resources.decrementTotal() +#endif + } +} + +final class SinkForward: ObserverType { + typealias Element = Observer.Element + + private let forward: Sink + + init(forward: Sink) { + self.forward = forward + } + + final func on(_ event: Event) { + switch event { + case .next: + self.forward.observer.on(event) + case .error, .completed: + self.forward.observer.on(event) + self.forward.cancel.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Skip.swift b/Pods/RxSwift/RxSwift/Observables/Skip.swift new file mode 100644 index 0000000..5856f37 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Skip.swift @@ -0,0 +1,158 @@ +// +// Skip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/25/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter count: The number of elements to skip before returning the remaining elements. + - returns: An observable sequence that contains the elements that occur after the specified index in the input sequence. + */ + public func skip(_ count: Int) + -> Observable { + SkipCount(source: self.asObservable(), count: count) + } +} + +extension ObservableType { + + /** + Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html) + + - parameter duration: Duration for skipping elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence. + */ + public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } +} + +// count version + +final private class SkipCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipCount + + let parent: Parent + + var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining <= 0 { + self.forwardOn(.next(value)) + } + else { + self.remaining -= 1 + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class SkipCount: Producer { + let source: Observable + let count: Int + + init(source: Observable, count: Int) { + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class SkipTimeSink: Sink, ObserverType where Observer.Element == Element { + typealias Parent = SkipTime + + let parent: Parent + + // state + var open = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if self.open { + self.forwardOn(.next(value)) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.open = true + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class SkipTime: Producer { + let source: Observable + let duration: RxTimeInterval + let scheduler: SchedulerType + + init(source: Observable, duration: RxTimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift b/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift new file mode 100644 index 0000000..c8fe193 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SkipUntil.swift @@ -0,0 +1,152 @@ +// +// SkipUntil.swift +// RxSwift +// +// Created by Yury Korolev on 10/3/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + public func skip(until other: Source) + -> Observable { + SkipUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns the elements from the source observable sequence that are emitted after the other observable sequence produces an element. + + - seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html) + + - parameter other: Observable sequence that starts propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence that are emitted after the other sequence emits an item. + */ + @available(*, deprecated, renamed: "skip(until:)") + public func skipUntil(_ other: Source) + -> Observable { + skip(until: other) + } +} + +final private class SkipUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = SkipUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardElements = true + self.subscription.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif + +} + + +final private class SkipUntilSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = SkipUntil + + let lock = RecursiveLock() + private let parent: Parent + fileprivate var forwardElements = false + + private let sourceSubscription = SingleAssignmentDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + if self.forwardElements { + self.forwardOn(event) + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + if self.forwardElements { + self.forwardOn(event) + } + self.dispose() + } + } + + func run() -> Disposable { + let sourceSubscription = self.parent.source.subscribe(self) + let otherObserver = SkipUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + self.sourceSubscription.setDisposable(sourceSubscription) + otherObserver.subscription.setDisposable(otherSubscription) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class SkipUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift b/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift new file mode 100644 index 0000000..a62f88d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SkipWhile.swift @@ -0,0 +1,87 @@ +// +// SkipWhile.swift +// RxSwift +// +// Created by Yury Korolev on 10/9/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + public func skip(while predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } + + /** + Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. + + - seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. + */ + @available(*, deprecated, renamed: "skip(while:)") + public func skipWhile(_ predicate: @escaping (Element) throws -> Bool) -> Observable { + SkipWhile(source: self.asObservable(), predicate: predicate) + } +} + +final private class SkipWhileSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = SkipWhile + + private let parent: Parent + private var running = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + } + + if self.running { + self.forwardOn(.next(value)) + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } +} + +final private class SkipWhile: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + + init(source: Observable, predicate: @escaping Predicate) { + self.source = source + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SkipWhileSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/StartWith.swift b/Pods/RxSwift/RxSwift/Observables/StartWith.swift new file mode 100644 index 0000000..13fb31d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/StartWith.swift @@ -0,0 +1,42 @@ +// +// StartWith.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Prepends a sequence of values to an observable sequence. + + - seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html) + + - parameter elements: Elements to prepend to the specified sequence. + - returns: The source sequence prepended with the specified values. + */ + public func startWith(_ elements: Element ...) + -> Observable { + return StartWith(source: self.asObservable(), elements: elements) + } +} + +final private class StartWith: Producer { + let elements: [Element] + let source: Observable + + init(source: Observable, elements: [Element]) { + self.source = source + self.elements = elements + super.init() + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + for e in self.elements { + observer.on(.next(e)) + } + + return (sink: Disposables.create(), subscription: self.source.subscribe(observer)) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift b/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift new file mode 100644 index 0000000..e8e41d9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SubscribeOn.swift @@ -0,0 +1,103 @@ +// +// SubscribeOn.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + public func subscribe(on scheduler: ImmediateSchedulerType) + -> Observable { + SubscribeOn(source: self, scheduler: scheduler) + } + + /** + Wraps the source sequence in order to run its subscription and unsubscription logic on the specified + scheduler. + + This operation is not commonly used. + + This only performs the side-effects of subscription and unsubscription on the specified scheduler. + + In order to invoke observer callbacks on a `scheduler`, use `observeOn`. + + - seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html) + + - parameter scheduler: Scheduler to perform subscription and unsubscription actions on. + - returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. + */ + @available(*, deprecated, renamed: "subscribe(on:)") + public func subscribeOn(_ scheduler: ImmediateSchedulerType) + -> Observable { + subscribe(on: scheduler) + } +} + +final private class SubscribeOnSink: Sink, ObserverType where Ob.Element == Observer.Element { + typealias Element = Observer.Element + typealias Parent = SubscribeOn + + let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.forwardOn(event) + + if event.isStopEvent { + self.dispose() + } + } + + func run() -> Disposable { + let disposeEverything = SerialDisposable() + let cancelSchedule = SingleAssignmentDisposable() + + disposeEverything.disposable = cancelSchedule + + let disposeSchedule = self.parent.scheduler.schedule(()) { _ -> Disposable in + let subscription = self.parent.source.subscribe(self) + disposeEverything.disposable = ScheduledDisposable(scheduler: self.parent.scheduler, disposable: subscription) + return Disposables.create() + } + + cancelSchedule.setDisposable(disposeSchedule) + + return disposeEverything + } +} + +final private class SubscribeOn: Producer { + let source: Ob + let scheduler: ImmediateSchedulerType + + init(source: Ob, scheduler: ImmediateSchedulerType) { + self.source = source + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Ob.Element { + let sink = SubscribeOnSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Switch.swift b/Pods/RxSwift/RxSwift/Observables/Switch.swift new file mode 100644 index 0000000..5aa60b9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Switch.swift @@ -0,0 +1,251 @@ +// +// Switch.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Observable { + return FlatMapLatest(source: self.asObservable(), selector: selector) + } + + /** + Projects each element of an observable sequence into a new sequence of observable sequences and then + transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. + + It is a combination of `map` + `switchLatest` operator + + - seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html) + + - parameter selector: A transform function to apply to each element. + - returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an + Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func flatMapLatest(_ selector: @escaping (Element) throws -> Source) + -> Infallible { + return Infallible(flatMapLatest(selector)) + } +} + +extension ObservableType where Element: ObservableConvertibleType { + + /** + Transforms an observable sequence of observable sequences into an observable sequence + producing values only from the most recent observable sequence. + + Each time a new inner observable sequence is received, unsubscribe from the + previous inner observable sequence. + + - seealso: [switch operator on reactivex.io](http://reactivex.io/documentation/operators/switch.html) + + - returns: The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. + */ + public func switchLatest() -> Observable { + Switch(source: self.asObservable()) + } +} + +private class SwitchSink + : Sink + , ObserverType where Source.Element == Observer.Element { + typealias Element = SourceType + + private let subscriptions: SingleAssignmentDisposable = SingleAssignmentDisposable() + private let innerSubscription: SerialDisposable = SerialDisposable() + + let lock = RecursiveLock() + + // state + fileprivate var stopped = false + fileprivate var latest = 0 + fileprivate var hasLatest = false + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + self.subscriptions.setDisposable(subscription) + return Disposables.create(subscriptions, innerSubscription) + } + + func performMap(_ element: SourceType) throws -> Source { + rxAbstractMethod() + } + + @inline(__always) + final private func nextElementArrived(element: Element) -> (Int, Observable)? { + self.lock.lock(); defer { self.lock.unlock() } + + do { + let observable = try self.performMap(element).asObservable() + self.hasLatest = true + self.latest = self.latest &+ 1 + return (self.latest, observable) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + return nil + } + + func on(_ event: Event) { + switch event { + case .next(let element): + if let (latest, observable) = self.nextElementArrived(element: element) { + let d = SingleAssignmentDisposable() + self.innerSubscription.disposable = d + + let observer = SwitchSinkIter(parent: self, id: latest, this: d) + let disposable = observable.subscribe(observer) + d.setDisposable(disposable) + } + case .error(let error): + self.lock.lock(); defer { self.lock.unlock() } + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.lock.lock(); defer { self.lock.unlock() } + self.stopped = true + + self.subscriptions.dispose() + + if !self.hasLatest { + self.forwardOn(.completed) + self.dispose() + } + } + } +} + +final private class SwitchSinkIter + : ObserverType + , LockOwnerType + , SynchronizedOnType where Source.Element == Observer.Element { + typealias Element = Source.Element + typealias Parent = SwitchSink + + private let parent: Parent + private let id: Int + private let this: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, id: Int, this: Disposable) { + self.parent = parent + self.id = id + self.this = this + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: break + case .error, .completed: + self.this.dispose() + } + + if self.parent.latest != self.id { + return + } + + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.hasLatest = false + if self.parent.stopped { + self.parent.forwardOn(event) + self.parent.dispose() + } + } + } +} + +// MARK: Specializations + +final private class SwitchIdentitySink: SwitchSink + where Observer.Element == Source.Element { + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: Source) throws -> Source { + element + } +} + +final private class MapSwitchSink: SwitchSink where Observer.Element == Source.Element { + typealias Selector = (SourceType) throws -> Source + + private let selector: Selector + + init(selector: @escaping Selector, observer: Observer, cancel: Cancelable) { + self.selector = selector + super.init(observer: observer, cancel: cancel) + } + + override func performMap(_ element: SourceType) throws -> Source { + try self.selector(element) + } +} + +// MARK: Producers + +final private class Switch: Producer { + private let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = SwitchIdentitySink(observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} + +final private class FlatMapLatest: Producer { + typealias Selector = (SourceType) throws -> Source + + private let source: Observable + private let selector: Selector + + init(source: Observable, selector: @escaping Selector) { + self.source = source + self.selector = selector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Source.Element { + let sink = MapSwitchSink(selector: self.selector, observer: observer, cancel: cancel) + let subscription = sink.run(self.source) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift b/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift new file mode 100644 index 0000000..a8827c4 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/SwitchIfEmpty.swift @@ -0,0 +1,104 @@ +// +// SwitchIfEmpty.swift +// RxSwift +// +// Created by sergdort on 23/12/2016. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements of the specified sequence or `switchTo` sequence if the sequence is empty. + + - seealso: [DefaultIfEmpty operator on reactivex.io](http://reactivex.io/documentation/operators/defaultifempty.html) + + - parameter switchTo: Observable sequence being returned when source sequence is empty. + - returns: Observable sequence that contains elements from switchTo sequence if source is empty, otherwise returns source sequence elements. + */ + public func ifEmpty(switchTo other: Observable) -> Observable { + SwitchIfEmpty(source: self.asObservable(), ifEmpty: other) + } +} + +final private class SwitchIfEmpty: Producer { + + private let source: Observable + private let ifEmpty: Observable + + init(source: Observable, ifEmpty: Observable) { + self.source = source + self.ifEmpty = ifEmpty + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = SwitchIfEmptySink(ifEmpty: self.ifEmpty, + observer: observer, + cancel: cancel) + let subscription = sink.run(self.source.asObservable()) + + return (sink: sink, subscription: subscription) + } +} + +final private class SwitchIfEmptySink: Sink + , ObserverType { + typealias Element = Observer.Element + + private let ifEmpty: Observable + private var isEmpty = true + private let ifEmptySubscription = SingleAssignmentDisposable() + + init(ifEmpty: Observable, observer: Observer, cancel: Cancelable) { + self.ifEmpty = ifEmpty + super.init(observer: observer, cancel: cancel) + } + + func run(_ source: Observable) -> Disposable { + let subscription = source.subscribe(self) + return Disposables.create(subscription, ifEmptySubscription) + } + + func on(_ event: Event) { + switch event { + case .next: + self.isEmpty = false + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + guard self.isEmpty else { + self.forwardOn(.completed) + self.dispose() + return + } + let ifEmptySink = SwitchIfEmptySinkIter(parent: self) + self.ifEmptySubscription.setDisposable(self.ifEmpty.subscribe(ifEmptySink)) + } + } +} + +final private class SwitchIfEmptySinkIter + : ObserverType { + typealias Element = Observer.Element + typealias Parent = SwitchIfEmptySink + + private let parent: Parent + + init(parent: Parent) { + self.parent = parent + } + + func on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(event) + case .error: + self.parent.forwardOn(event) + self.parent.dispose() + case .completed: + self.parent.forwardOn(event) + self.parent.dispose() + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Take.swift b/Pods/RxSwift/RxSwift/Observables/Take.swift new file mode 100644 index 0000000..e574688 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Take.swift @@ -0,0 +1,193 @@ +// +// Take.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/12/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the start of an observable sequence. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter count: The number of elements to return. + - returns: An observable sequence that contains the specified number of elements from the start of the input sequence. + */ + public func take(_ count: Int) + -> Observable { + if count == 0 { + return Observable.empty() + } + else { + return TakeCount(source: self.asObservable(), count: count) + } + } +} + +extension ObservableType { + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + public func take(for duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + TakeTime(source: self.asObservable(), duration: duration, scheduler: scheduler) + } + + /** + Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. + + - seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html) + + - parameter duration: Duration for taking elements from the start of the sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence with the elements taken during the specified duration from the start of the source sequence. + */ + @available(*, deprecated, renamed: "take(for:scheduler:)") + public func take(_ duration: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + take(for: duration, scheduler: scheduler) + } +} + +// count version + +final private class TakeCountSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeCount + + private let parent: Parent + + private var remaining: Int + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.remaining = parent.count + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + + if self.remaining > 0 { + self.remaining -= 1 + + self.forwardOn(.next(value)) + + if self.remaining == 0 { + self.forwardOn(.completed) + self.dispose() + } + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeCount: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} + +// time version + +final private class TakeTimeSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType where Observer.Element == Element { + typealias Parent = TakeTime + + private let parent: Parent + + let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let value): + self.forwardOn(.next(value)) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func tick() { + self.lock.performLocked { + self.forwardOn(.completed) + self.dispose() + } + } + + func run() -> Disposable { + let disposeTimer = self.parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in + self.tick() + return Disposables.create() + } + + let disposeSubscription = self.parent.source.subscribe(self) + + return Disposables.create(disposeTimer, disposeSubscription) + } +} + +final private class TakeTime: Producer { + typealias TimeInterval = RxTimeInterval + + fileprivate let source: Observable + fileprivate let duration: TimeInterval + fileprivate let scheduler: SchedulerType + + init(source: Observable, duration: TimeInterval, scheduler: SchedulerType) { + self.source = source + self.scheduler = scheduler + self.duration = duration + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeTimeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/TakeLast.swift b/Pods/RxSwift/RxSwift/Observables/TakeLast.swift new file mode 100644 index 0000000..9183387 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/TakeLast.swift @@ -0,0 +1,78 @@ +// +// TakeLast.swift +// RxSwift +// +// Created by Tomi Koskinen on 25/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Returns a specified number of contiguous elements from the end of an observable sequence. + + This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. + + - seealso: [takeLast operator on reactivex.io](http://reactivex.io/documentation/operators/takelast.html) + + - parameter count: Number of elements to take from the end of the source sequence. + - returns: An observable sequence containing the specified number of elements from the end of the source sequence. + */ + public func takeLast(_ count: Int) + -> Observable { + TakeLast(source: self.asObservable(), count: count) + } +} + +final private class TakeLastSink: Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeLast + + private let parent: Parent + + private var elements: Queue + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.elements = Queue(capacity: parent.count + 1) + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.elements.enqueue(value) + if self.elements.count > self.parent.count { + _ = self.elements.dequeue() + } + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + for e in self.elements { + self.forwardOn(.next(e)) + } + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class TakeLast: Producer { + private let source: Observable + fileprivate let count: Int + + init(source: Observable, count: Int) { + if count < 0 { + rxFatalError("count can't be negative") + } + self.source = source + self.count = count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeLastSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift b/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift new file mode 100644 index 0000000..6c28d19 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/TakeWithPredicate.swift @@ -0,0 +1,285 @@ +// +// TakeWithPredicate.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + public func take(until other: Source) + -> Observable { + TakeUntil(source: self.asObservable(), other: other.asObservable()) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter predicate: A function to test each element for a condition. + - parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`. + + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + public func take(until predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + TakeUntilPredicate(source: self.asObservable(), + behavior: behavior, + predicate: predicate) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + public func take(while predicate: @escaping (Element) throws -> Bool, + behavior: TakeBehavior = .exclusive) + -> Observable { + take(until: { try !predicate($0) }, behavior: behavior) + } + + /** + Returns the elements from the source observable sequence until the other observable sequence produces an element. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter other: Observable sequence that terminates propagation of elements of the source sequence. + - returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. + */ + @available(*, deprecated, renamed: "take(until:)") + public func takeUntil(_ other: Source) + -> Observable { + take(until: other) + } + + /** + Returns elements from an observable sequence until the specified condition is true. + + - seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html) + + - parameter behavior: Whether or not to include the last element matching the predicate. + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes. + */ + @available(*, deprecated, renamed: "take(until:behavior:)") + public func takeUntil(_ behavior: TakeBehavior, + predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: predicate, behavior: behavior) + } + + /** + Returns elements from an observable sequence as long as a specified condition is true. + + - seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html) + + - parameter predicate: A function to test each element for a condition. + - returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. + */ + @available(*, deprecated, renamed: "take(while:)") + public func takeWhile(_ predicate: @escaping (Element) throws -> Bool) + -> Observable { + take(until: { try !predicate($0) }, behavior: .exclusive) + } +} + +/// Behaviors for the take operator family. +public enum TakeBehavior { + /// Include the last element matching the predicate. + case inclusive + + /// Exclude the last element matching the predicate. + case exclusive +} + +// MARK: - TakeUntil Observable +final private class TakeUntilSinkOther + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Parent = TakeUntilSink + typealias Element = Other + + private let parent: Parent + + var lock: RecursiveLock { + self.parent.lock + } + + fileprivate let subscription = SingleAssignmentDisposable() + + init(parent: Parent) { + self.parent = parent +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.parent.forwardOn(.completed) + self.parent.dispose() + case .error(let e): + self.parent.forwardOn(.error(e)) + self.parent.dispose() + case .completed: + self.subscription.dispose() + } + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} + +final private class TakeUntilSink + : Sink + , LockOwnerType + , ObserverType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias Parent = TakeUntil + + private let parent: Parent + + let lock = RecursiveLock() + + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next: + self.forwardOn(event) + case .error: + self.forwardOn(event) + self.dispose() + case .completed: + self.forwardOn(event) + self.dispose() + } + } + + func run() -> Disposable { + let otherObserver = TakeUntilSinkOther(parent: self) + let otherSubscription = self.parent.other.subscribe(otherObserver) + otherObserver.subscription.setDisposable(otherSubscription) + let sourceSubscription = self.parent.source.subscribe(self) + + return Disposables.create(sourceSubscription, otherObserver.subscription) + } +} + +final private class TakeUntil: Producer { + + fileprivate let source: Observable + fileprivate let other: Observable + + init(source: Observable, other: Observable) { + self.source = source + self.other = other + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + +// MARK: - TakeUntil Predicate +final private class TakeUntilPredicateSink + : Sink, ObserverType { + typealias Element = Observer.Element + typealias Parent = TakeUntilPredicate + + private let parent: Parent + private var running = true + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + if !self.running { + return + } + + do { + self.running = try !self.parent.predicate(value) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + return + } + + if self.running { + self.forwardOn(.next(value)) + } else { + if self.parent.behavior == .inclusive { + self.forwardOn(.next(value)) + } + + self.forwardOn(.completed) + self.dispose() + } + case .error, .completed: + self.forwardOn(event) + self.dispose() + } + } + +} + +final private class TakeUntilPredicate: Producer { + typealias Predicate = (Element) throws -> Bool + + private let source: Observable + fileprivate let predicate: Predicate + fileprivate let behavior: TakeBehavior + + init(source: Observable, + behavior: TakeBehavior, + predicate: @escaping Predicate) { + self.source = source + self.behavior = behavior + self.predicate = predicate + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TakeUntilPredicateSink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Throttle.swift b/Pods/RxSwift/RxSwift/Observables/Throttle.swift new file mode 100644 index 0000000..86152a8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Throttle.swift @@ -0,0 +1,160 @@ +// +// Throttle.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +extension ObservableType { + + /** + Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration. + + This operator makes sure that no two elements are emitted in less then dueTime. + + - seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html) + + - parameter dueTime: Throttling duration for each element. + - parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted. + - parameter scheduler: Scheduler to run the throttle timers on. + - returns: The throttled sequence. + */ + public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType) + -> Observable { + Throttle(source: self.asObservable(), dueTime: dueTime, latest: latest, scheduler: scheduler) + } +} + +final private class ThrottleSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias Element = Observer.Element + typealias ParentType = Throttle + + private let parent: ParentType + + let lock = RecursiveLock() + + // state + private var lastUnsentElement: Element? + private var lastSentTime: Date? + private var completed: Bool = false + + let cancellable = SerialDisposable() + + init(parent: ParentType, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let subscription = self.parent.source.subscribe(self) + + return Disposables.create(subscription, cancellable) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case .next(let element): + let now = self.parent.scheduler.now + + let reducedScheduledTime: RxTimeInterval + + if let lastSendingTime = self.lastSentTime { + reducedScheduledTime = self.parent.dueTime.reduceWithSpanBetween(earlierDate: lastSendingTime, laterDate: now) + } + else { + reducedScheduledTime = .nanoseconds(0) + } + + if reducedScheduledTime.isNow { + self.sendNow(element: element) + return + } + + if !self.parent.latest { + return + } + + let isThereAlreadyInFlightRequest = self.lastUnsentElement != nil + + self.lastUnsentElement = element + + if isThereAlreadyInFlightRequest { + return + } + + let scheduler = self.parent.scheduler + + let d = SingleAssignmentDisposable() + self.cancellable.disposable = d + + d.setDisposable(scheduler.scheduleRelative(0, dueTime: reducedScheduledTime, action: self.propagate)) + case .error: + self.lastUnsentElement = nil + self.forwardOn(event) + self.dispose() + case .completed: + if self.lastUnsentElement != nil { + self.completed = true + } + else { + self.forwardOn(.completed) + self.dispose() + } + } + } + + private func sendNow(element: Element) { + self.lastUnsentElement = nil + self.forwardOn(.next(element)) + // in case element processing takes a while, this should give some more room + self.lastSentTime = self.parent.scheduler.now + } + + func propagate(_: Int) -> Disposable { + self.lock.performLocked { + if let lastUnsentElement = self.lastUnsentElement { + self.sendNow(element: lastUnsentElement) + } + + if self.completed { + self.forwardOn(.completed) + self.dispose() + } + } + + return Disposables.create() + } +} + +final private class Throttle: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let latest: Bool + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, latest: Bool, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.latest = latest + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = ThrottleSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + +} diff --git a/Pods/RxSwift/RxSwift/Observables/Timeout.swift b/Pods/RxSwift/RxSwift/Observables/Timeout.swift new file mode 100644 index 0000000..efcc791 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Timeout.swift @@ -0,0 +1,151 @@ +// +// Timeout.swift +// RxSwift +// +// Created by Tomi Koskinen on 13/11/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Applies a timeout policy for each element in the observable sequence. If the next element isn't received within the specified timeout duration starting from its predecessor, a TimeoutError is propagated to the observer. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: An observable sequence with a `RxError.timeout` in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: Observable.error(RxError.timeout), scheduler: scheduler) + } + + /** + Applies a timeout policy for each element in the observable sequence, using the specified scheduler to run timeout timers. If the next element isn't received within the specified timeout duration starting from its predecessor, the other observable sequence is used to produce future messages from that point on. + + - seealso: [timeout operator on reactivex.io](http://reactivex.io/documentation/operators/timeout.html) + + - parameter dueTime: Maximum duration between values before a timeout occurs. + - parameter other: Sequence to return in case of a timeout. + - parameter scheduler: Scheduler to run the timeout timer on. + - returns: The source sequence switching to the other sequence in case of a timeout. + */ + public func timeout(_ dueTime: RxTimeInterval, other: Source, scheduler: SchedulerType) + -> Observable where Element == Source.Element { + return Timeout(source: self.asObservable(), dueTime: dueTime, other: other.asObservable(), scheduler: scheduler) + } +} + +final private class TimeoutSink: Sink, LockOwnerType, ObserverType { + typealias Element = Observer.Element + typealias Parent = Timeout + + private let parent: Parent + + let lock = RecursiveLock() + + private let timerD = SerialDisposable() + private let subscription = SerialDisposable() + + private var id = 0 + private var switched = false + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let original = SingleAssignmentDisposable() + self.subscription.disposable = original + + self.createTimeoutTimer() + + original.setDisposable(self.parent.source.subscribe(self)) + + return Disposables.create(subscription, timerD) + } + + func on(_ event: Event) { + switch event { + case .next: + var onNextWins = false + + self.lock.performLocked { + onNextWins = !self.switched + if onNextWins { + self.id = self.id &+ 1 + } + } + + if onNextWins { + self.forwardOn(event) + self.createTimeoutTimer() + } + case .error, .completed: + var onEventWins = false + + self.lock.performLocked { + onEventWins = !self.switched + if onEventWins { + self.id = self.id &+ 1 + } + } + + if onEventWins { + self.forwardOn(event) + self.dispose() + } + } + } + + private func createTimeoutTimer() { + if self.timerD.isDisposed { + return + } + + let nextTimer = SingleAssignmentDisposable() + self.timerD.disposable = nextTimer + + let disposeSchedule = self.parent.scheduler.scheduleRelative(self.id, dueTime: self.parent.dueTime) { state in + + var timerWins = false + + self.lock.performLocked { + self.switched = (state == self.id) + timerWins = self.switched + } + + if timerWins { + self.subscription.disposable = self.parent.other.subscribe(self.forwarder()) + } + + return Disposables.create() + } + + nextTimer.setDisposable(disposeSchedule) + } +} + + +final private class Timeout: Producer { + fileprivate let source: Observable + fileprivate let dueTime: RxTimeInterval + fileprivate let other: Observable + fileprivate let scheduler: SchedulerType + + init(source: Observable, dueTime: RxTimeInterval, other: Observable, scheduler: SchedulerType) { + self.source = source + self.dueTime = dueTime + self.other = other + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = TimeoutSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Timer.swift b/Pods/RxSwift/RxSwift/Observables/Timer.swift new file mode 100644 index 0000000..30bbdf6 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Timer.swift @@ -0,0 +1,117 @@ +// +// Timer.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. + + - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) + + - parameter period: Period for producing the values in the resulting sequence. + - parameter scheduler: Scheduler to run the timer on. + - returns: An observable sequence that produces a value after each period. + */ + public static func interval(_ period: RxTimeInterval, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: period, + period: period, + scheduler: scheduler + ) + } +} + +extension ObservableType where Element: RxAbstractInteger { + /** + Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. + + - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) + + - parameter dueTime: Relative time at which to produce the first value. + - parameter period: Period to produce subsequent values. + - parameter scheduler: Scheduler to run timers on. + - returns: An observable sequence that produces a value after due time has elapsed and then each period. + */ + public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval? = nil, scheduler: SchedulerType) + -> Observable { + return Timer( + dueTime: dueTime, + period: period, + scheduler: scheduler + ) + } +} + +import Foundation + +final private class TimerSink : Sink where Observer.Element : RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + private let lock = RecursiveLock() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.schedulePeriodic(0 as Observer.Element, startAfter: self.parent.dueTime, period: self.parent.period!) { state in + self.lock.performLocked { + self.forwardOn(.next(state)) + return state &+ 1 + } + } + } +} + +final private class TimerOneOffSink: Sink where Observer.Element: RxAbstractInteger { + typealias Parent = Timer + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + return self.parent.scheduler.scheduleRelative(self, dueTime: self.parent.dueTime) { [unowned self] _ -> Disposable in + self.forwardOn(.next(0)) + self.forwardOn(.completed) + self.dispose() + + return Disposables.create() + } + } +} + +final private class Timer: Producer { + fileprivate let scheduler: SchedulerType + fileprivate let dueTime: RxTimeInterval + fileprivate let period: RxTimeInterval? + + init(dueTime: RxTimeInterval, period: RxTimeInterval?, scheduler: SchedulerType) { + self.scheduler = scheduler + self.dueTime = dueTime + self.period = period + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + if self.period != nil { + let sink = TimerSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + else { + let sink = TimerOneOffSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/ToArray.swift b/Pods/RxSwift/RxSwift/Observables/ToArray.swift new file mode 100644 index 0000000..76c7370 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/ToArray.swift @@ -0,0 +1,64 @@ +// +// ToArray.swift +// RxSwift +// +// Created by Junior B. on 20/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Converts an Observable into a Single that emits the whole sequence as a single array and then terminates. + + For aggregation behavior see `reduce`. + + - seealso: [toArray operator on reactivex.io](http://reactivex.io/documentation/operators/to.html) + + - returns: A Single sequence containing all the emitted elements as array. + */ + public func toArray() + -> Single<[Element]> { + PrimitiveSequence(raw: ToArray(source: self.asObservable())) + } +} + +final private class ToArraySink: Sink, ObserverType where Observer.Element == [SourceType] { + typealias Parent = ToArray + + let parent: Parent + var list = [SourceType]() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event) { + switch event { + case .next(let value): + self.list.append(value) + case .error(let e): + self.forwardOn(.error(e)) + self.dispose() + case .completed: + self.forwardOn(.next(self.list)) + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class ToArray: Producer<[SourceType]> { + let source: Observable + + init(source: Observable) { + self.source = source + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == [SourceType] { + let sink = ToArraySink(parent: self, observer: observer, cancel: cancel) + let subscription = self.source.subscribe(sink) + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Using.swift b/Pods/RxSwift/RxSwift/Observables/Using.swift new file mode 100644 index 0000000..ca48d2f --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Using.swift @@ -0,0 +1,90 @@ +// +// Using.swift +// RxSwift +// +// Created by Yury Korolev on 10/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. + + - seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html) + + - parameter resourceFactory: Factory function to obtain a resource object. + - parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource. + - returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object. + */ + public static func using(_ resourceFactory: @escaping () throws -> Resource, observableFactory: @escaping (Resource) throws -> Observable) -> Observable { + Using(resourceFactory: resourceFactory, observableFactory: observableFactory) + } +} + +final private class UsingSink: Sink, ObserverType { + typealias SourceType = Observer.Element + typealias Parent = Using + + private let parent: Parent + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + var disposable = Disposables.create() + + do { + let resource = try self.parent.resourceFactory() + disposable = resource + let source = try self.parent.observableFactory(resource) + + return Disposables.create( + source.subscribe(self), + disposable + ) + } catch let error { + return Disposables.create( + Observable.error(error).subscribe(self), + disposable + ) + } + } + + func on(_ event: Event) { + switch event { + case let .next(value): + self.forwardOn(.next(value)) + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.forwardOn(.completed) + self.dispose() + } + } +} + +final private class Using: Producer { + + typealias Element = SourceType + + typealias ResourceFactory = () throws -> ResourceType + typealias ObservableFactory = (ResourceType) throws -> Observable + + fileprivate let resourceFactory: ResourceFactory + fileprivate let observableFactory: ObservableFactory + + + init(resourceFactory: @escaping ResourceFactory, observableFactory: @escaping ObservableFactory) { + self.resourceFactory = resourceFactory + self.observableFactory = observableFactory + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element { + let sink = UsingSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Window.swift b/Pods/RxSwift/RxSwift/Observables/Window.swift new file mode 100644 index 0000000..b2a37a5 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Window.swift @@ -0,0 +1,168 @@ +// +// Window.swift +// RxSwift +// +// Created by Junior B. on 29/10/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Projects each element of an observable sequence into a window that is completed when either it’s full or a given amount of time has elapsed. + + - seealso: [window operator on reactivex.io](http://reactivex.io/documentation/operators/window.html) + + - parameter timeSpan: Maximum time length of a window. + - parameter count: Maximum element count of a window. + - parameter scheduler: Scheduler to run windowing timers on. + - returns: An observable sequence of windows (instances of `Observable`). + */ + public func window(timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) + -> Observable> { + return WindowTimeCount(source: self.asObservable(), timeSpan: timeSpan, count: count, scheduler: scheduler) + } +} + +final private class WindowTimeCountSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType where Observer.Element == Observable { + typealias Parent = WindowTimeCount + + private let parent: Parent + + let lock = RecursiveLock() + + private var subject = PublishSubject() + private var count = 0 + private var windowId = 0 + + private let timerD = SerialDisposable() + private let refCountDisposable: RefCountDisposable + private let groupDisposable = CompositeDisposable() + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + _ = self.groupDisposable.insert(self.timerD) + + self.refCountDisposable = RefCountDisposable(disposable: self.groupDisposable) + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + self.createTimer(self.windowId) + + _ = self.groupDisposable.insert(self.parent.source.subscribe(self)) + return self.refCountDisposable + } + + func startNewWindowAndCompleteCurrentOne() { + self.subject.on(.completed) + self.subject = PublishSubject() + + self.forwardOn(.next(AddRef(source: self.subject, refCount: self.refCountDisposable).asObservable())) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + var newWindow = false + var newId = 0 + + switch event { + case .next(let element): + self.subject.on(.next(element)) + + do { + _ = try incrementChecked(&self.count) + } catch let e { + self.subject.on(.error(e as Swift.Error)) + self.dispose() + } + + if self.count == self.parent.count { + newWindow = true + self.count = 0 + self.windowId += 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + case .error(let error): + self.subject.on(.error(error)) + self.forwardOn(.error(error)) + self.dispose() + case .completed: + self.subject.on(.completed) + self.forwardOn(.completed) + self.dispose() + } + + if newWindow { + self.createTimer(newId) + } + } + + func createTimer(_ windowId: Int) { + if self.timerD.isDisposed { + return + } + + if self.windowId != windowId { + return + } + + let nextTimer = SingleAssignmentDisposable() + + self.timerD.disposable = nextTimer + + let scheduledRelative = self.parent.scheduler.scheduleRelative(windowId, dueTime: self.parent.timeSpan) { previousWindowId in + + var newId = 0 + + self.lock.performLocked { + if previousWindowId != self.windowId { + return + } + + self.count = 0 + self.windowId = self.windowId &+ 1 + newId = self.windowId + self.startNewWindowAndCompleteCurrentOne() + } + + self.createTimer(newId) + + return Disposables.create() + } + + nextTimer.setDisposable(scheduledRelative) + } +} + +final private class WindowTimeCount: Producer> { + fileprivate let timeSpan: RxTimeInterval + fileprivate let count: Int + fileprivate let scheduler: SchedulerType + fileprivate let source: Observable + + init(source: Observable, timeSpan: RxTimeInterval, count: Int, scheduler: SchedulerType) { + self.source = source + self.timeSpan = timeSpan + self.count = count + self.scheduler = scheduler + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Observable { + let sink = WindowTimeCountSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift b/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift new file mode 100644 index 0000000..d286812 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/WithLatestFrom.swift @@ -0,0 +1,151 @@ +// +// WithLatestFrom.swift +// RxSwift +// +// Created by Yury Korolev on 10/19/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + + /** + Merges two observable sequences into one observable sequence by combining each element from self with the latest element from the second source, if any. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - parameter resultSelector: Function to invoke for each element from the self combined with the latest element from the second source, if any. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source, resultSelector: @escaping (Element, Source.Element) throws -> ResultType) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: resultSelector) + } + + /** + Merges two observable sequences into one observable sequence by using latest element from the second sequence every time when `self` emits an element. + + - seealso: [combineLatest operator on reactivex.io](http://reactivex.io/documentation/operators/combinelatest.html) + - note: Elements emitted by self before the second source has emitted any values will be omitted. + + - parameter second: Second observable source. + - returns: An observable sequence containing the result of combining each element of the self with the latest element from the second source, if any, using the specified result selector function. + */ + public func withLatestFrom(_ second: Source) -> Observable { + WithLatestFrom(first: self.asObservable(), second: second.asObservable(), resultSelector: { $1 }) + } +} + +final private class WithLatestFromSink + : Sink + , ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ResultType = Observer.Element + typealias Parent = WithLatestFrom + typealias Element = FirstType + + private let parent: Parent + + fileprivate var lock = RecursiveLock() + fileprivate var latest: SecondType? + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + + super.init(observer: observer, cancel: cancel) + } + + func run() -> Disposable { + let sndSubscription = SingleAssignmentDisposable() + let sndO = WithLatestFromSecond(parent: self, disposable: sndSubscription) + + sndSubscription.setDisposable(self.parent.second.subscribe(sndO)) + let fstSubscription = self.parent.first.subscribe(self) + + return Disposables.create(fstSubscription, sndSubscription) + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + guard let latest = self.latest else { return } + do { + let res = try self.parent.resultSelector(value, latest) + + self.forwardOn(.next(res)) + } catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + case .completed: + self.forwardOn(.completed) + self.dispose() + case let .error(error): + self.forwardOn(.error(error)) + self.dispose() + } + } +} + +final private class WithLatestFromSecond + : ObserverType + , LockOwnerType + , SynchronizedOnType { + + typealias ResultType = Observer.Element + typealias Parent = WithLatestFromSink + typealias Element = SecondType + + private let parent: Parent + private let disposable: Disposable + + var lock: RecursiveLock { + self.parent.lock + } + + init(parent: Parent, disposable: Disposable) { + self.parent = parent + self.disposable = disposable + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + switch event { + case let .next(value): + self.parent.latest = value + case .completed: + self.disposable.dispose() + case let .error(error): + self.parent.forwardOn(.error(error)) + self.parent.dispose() + } + } +} + +final private class WithLatestFrom: Producer { + typealias ResultSelector = (FirstType, SecondType) throws -> ResultType + + fileprivate let first: Observable + fileprivate let second: Observable + fileprivate let resultSelector: ResultSelector + + init(first: Observable, second: Observable, resultSelector: @escaping ResultSelector) { + self.first = first + self.second = second + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == ResultType { + let sink = WithLatestFromSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift b/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift new file mode 100644 index 0000000..4dc2ead --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/WithUnretained.swift @@ -0,0 +1,58 @@ +// +// WithUnretained.swift +// RxSwift +// +// Created by Vincent Pradeilles on 01/01/2021. +// Copyright © 2020 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the seqeunce will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - parameter resultSelector: A function to combine the unretained referenced on `obj` and the value of the observable sequence. + - returns: An observable sequence that contains the result of `resultSelector` being called with an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained( + _ obj: Object, + resultSelector: @escaping (Object, Element) -> Out + ) -> Observable { + map { [weak obj] element -> Out in + guard let obj = obj else { throw UnretainedError.failedRetaining } + + return resultSelector(obj, element) + } + .catch{ error -> Observable in + guard let unretainedError = error as? UnretainedError, + unretainedError == .failedRetaining else { + return .error(error) + } + + return .empty() + } + } + + + /** + Provides an unretained, safe to use (i.e. not implicitly unwrapped), reference to an object along with the events emitted by the sequence. + + In the case the provided object cannot be retained successfully, the seqeunce will complete. + + - note: Be careful when using this operator in a sequence that has a buffer or replay, for example `share(replay: 1)`, as the sharing buffer will also include the provided object, which could potentially cause a retain cycle. + + - parameter obj: The object to provide an unretained reference on. + - returns: An observable sequence of tuples that contains both an unretained reference on `obj` and the values of the original sequence. + */ + public func withUnretained(_ obj: Object) -> Observable<(Object, Element)> { + return withUnretained(obj) { ($0, $1) } + } +} + +private enum UnretainedError: Swift.Error { + case failedRetaining +} diff --git a/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift b/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift new file mode 100644 index 0000000..2d7f887 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift @@ -0,0 +1,168 @@ +// +// Zip+Collection.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable + where Collection.Element: ObservableType { + ZipCollectionType(sources: collection, resultSelector: resultSelector) + } + + /** + Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip(_ collection: Collection) -> Observable<[Element]> + where Collection.Element: ObservableType, Collection.Element.Element == Element { + ZipCollectionType(sources: collection, resultSelector: { $0 }) + } + +} + +final private class ZipCollectionTypeSink + : Sink where Collection.Element: ObservableConvertibleType { + typealias Result = Observer.Element + typealias Parent = ZipCollectionType + typealias SourceElement = Collection.Element.Element + + private let parent: Parent + + private let lock = RecursiveLock() + + // state + private var numberOfValues = 0 + private var values: [Queue] + private var isDone: [Bool] + private var numberOfDone = 0 + private var subscriptions: [SingleAssignmentDisposable] + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + self.values = [Queue](repeating: Queue(capacity: 4), count: parent.count) + self.isDone = [Bool](repeating: false, count: parent.count) + self.subscriptions = [SingleAssignmentDisposable]() + self.subscriptions.reserveCapacity(parent.count) + + for _ in 0 ..< parent.count { + self.subscriptions.append(SingleAssignmentDisposable()) + } + + super.init(observer: observer, cancel: cancel) + } + + func on(_ event: Event, atIndex: Int) { + self.lock.lock(); defer { self.lock.unlock() } + switch event { + case .next(let element): + self.values[atIndex].enqueue(element) + + if self.values[atIndex].count == 1 { + self.numberOfValues += 1 + } + + if self.numberOfValues < self.parent.count { + if self.numberOfDone == self.parent.count - 1 { + self.forwardOn(.completed) + self.dispose() + } + return + } + + do { + var arguments = [SourceElement]() + arguments.reserveCapacity(self.parent.count) + + // recalculate number of values + self.numberOfValues = 0 + + for i in 0 ..< self.values.count { + arguments.append(self.values[i].dequeue()!) + if !self.values[i].isEmpty { + self.numberOfValues += 1 + } + } + + let result = try self.parent.resultSelector(arguments) + self.forwardOn(.next(result)) + } + catch let error { + self.forwardOn(.error(error)) + self.dispose() + } + + case .error(let error): + self.forwardOn(.error(error)) + self.dispose() + case .completed: + if self.isDone[atIndex] { + return + } + + self.isDone[atIndex] = true + self.numberOfDone += 1 + + if self.numberOfDone == self.parent.count { + self.forwardOn(.completed) + self.dispose() + } + else { + self.subscriptions[atIndex].dispose() + } + } + } + + func run() -> Disposable { + var j = 0 + for i in self.parent.sources { + let index = j + let source = i.asObservable() + + let disposable = source.subscribe(AnyObserver { event in + self.on(event, atIndex: index) + }) + self.subscriptions[j].setDisposable(disposable) + j += 1 + } + + if self.parent.sources.isEmpty { + self.forwardOn(.completed) + } + + return Disposables.create(subscriptions) + } +} + +final private class ZipCollectionType: Producer where Collection.Element: ObservableConvertibleType { + typealias ResultSelector = ([Collection.Element.Element]) throws -> Result + + let sources: Collection + let resultSelector: ResultSelector + let count: Int + + init(sources: Collection, resultSelector: @escaping ResultSelector) { + self.sources = sources + self.resultSelector = resultSelector + self.count = self.sources.count + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} diff --git a/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift b/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift new file mode 100644 index 0000000..b6d876d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip+arity.swift @@ -0,0 +1,934 @@ +// This file is autogenerated. Take a look at `Preprocessor` target in RxSwift project +// +// Zip+arity.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + + + +// 2 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, resultSelector: @escaping (O1.Element, O2.Element) throws -> Element) + -> Observable { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2) + -> Observable<(O1.Element, O2.Element)> { + return Zip2( + source1: source1.asObservable(), source2: source2.asObservable(), + resultSelector: { ($0, $1) } + ) + } +} + +final class ZipSink2_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip2 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 2, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + + return Disposables.create([ + subscription1, + subscription2 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!) + } +} + +final class Zip2 : Producer { + typealias ResultSelector = (E1, E2) throws -> Result + + let source1: Observable + let source2: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink2_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 3 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, resultSelector: @escaping (O1.Element, O2.Element, O3.Element) throws -> Element) + -> Observable { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3) + -> Observable<(O1.Element, O2.Element, O3.Element)> { + return Zip3( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), + resultSelector: { ($0, $1, $2) } + ) + } +} + +final class ZipSink3_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip3 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 3, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!) + } +} + +final class Zip3 : Producer { + typealias ResultSelector = (E1, E2, E3) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink3_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 4 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element) throws -> Element) + -> Observable { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element)> { + return Zip4( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), + resultSelector: { ($0, $1, $2, $3) } + ) + } +} + +final class ZipSink4_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip4 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 4, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!) + } +} + +final class Zip4 : Producer { + typealias ResultSelector = (E1, E2, E3, E4) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink4_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 5 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element) throws -> Element) + -> Observable { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element)> { + return Zip5( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4) } + ) + } +} + +final class ZipSink5_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip5 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 5, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!) + } +} + +final class Zip5 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink5_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 6 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element) throws -> Element) + -> Observable { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element)> { + return Zip6( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5) } + ) + } +} + +final class ZipSink6_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip6 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 6, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!) + } +} + +final class Zip6 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink6_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 7 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element) throws -> Element) + -> Observable { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element)> { + return Zip7( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6) } + ) + } +} + +final class ZipSink7_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip7 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 7, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!) + } +} + +final class Zip7 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink7_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + + +// 8 + +extension ObservableType { + /** + Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources. + - returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8, resultSelector: @escaping (O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element) throws -> Element) + -> Observable { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: resultSelector + ) + } +} + +extension ObservableType where Element == Any { + /** + Merges the specified observable sequences into one observable sequence of tuples whenever all of the observable sequences have produced an element at a corresponding index. + + - seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html) + + - returns: An observable sequence containing the result of combining elements of the sources. + */ + public static func zip + (_ source1: O1, _ source2: O2, _ source3: O3, _ source4: O4, _ source5: O5, _ source6: O6, _ source7: O7, _ source8: O8) + -> Observable<(O1.Element, O2.Element, O3.Element, O4.Element, O5.Element, O6.Element, O7.Element, O8.Element)> { + return Zip8( + source1: source1.asObservable(), source2: source2.asObservable(), source3: source3.asObservable(), source4: source4.asObservable(), source5: source5.asObservable(), source6: source6.asObservable(), source7: source7.asObservable(), source8: source8.asObservable(), + resultSelector: { ($0, $1, $2, $3, $4, $5, $6, $7) } + ) + } +} + +final class ZipSink8_ : ZipSink { + typealias Result = Observer.Element + typealias Parent = Zip8 + + let parent: Parent + + var values1: Queue = Queue(capacity: 2) + var values2: Queue = Queue(capacity: 2) + var values3: Queue = Queue(capacity: 2) + var values4: Queue = Queue(capacity: 2) + var values5: Queue = Queue(capacity: 2) + var values6: Queue = Queue(capacity: 2) + var values7: Queue = Queue(capacity: 2) + var values8: Queue = Queue(capacity: 2) + + init(parent: Parent, observer: Observer, cancel: Cancelable) { + self.parent = parent + super.init(arity: 8, observer: observer, cancel: cancel) + } + + override func hasElements(_ index: Int) -> Bool { + switch index { + case 0: return !self.values1.isEmpty + case 1: return !self.values2.isEmpty + case 2: return !self.values3.isEmpty + case 3: return !self.values4.isEmpty + case 4: return !self.values5.isEmpty + case 5: return !self.values6.isEmpty + case 6: return !self.values7.isEmpty + case 7: return !self.values8.isEmpty + + default: + rxFatalError("Unhandled case (Function)") + } + } + + func run() -> Disposable { + let subscription1 = SingleAssignmentDisposable() + let subscription2 = SingleAssignmentDisposable() + let subscription3 = SingleAssignmentDisposable() + let subscription4 = SingleAssignmentDisposable() + let subscription5 = SingleAssignmentDisposable() + let subscription6 = SingleAssignmentDisposable() + let subscription7 = SingleAssignmentDisposable() + let subscription8 = SingleAssignmentDisposable() + + let observer1 = ZipObserver(lock: self.lock, parent: self, index: 0, setNextValue: { self.values1.enqueue($0) }, this: subscription1) + let observer2 = ZipObserver(lock: self.lock, parent: self, index: 1, setNextValue: { self.values2.enqueue($0) }, this: subscription2) + let observer3 = ZipObserver(lock: self.lock, parent: self, index: 2, setNextValue: { self.values3.enqueue($0) }, this: subscription3) + let observer4 = ZipObserver(lock: self.lock, parent: self, index: 3, setNextValue: { self.values4.enqueue($0) }, this: subscription4) + let observer5 = ZipObserver(lock: self.lock, parent: self, index: 4, setNextValue: { self.values5.enqueue($0) }, this: subscription5) + let observer6 = ZipObserver(lock: self.lock, parent: self, index: 5, setNextValue: { self.values6.enqueue($0) }, this: subscription6) + let observer7 = ZipObserver(lock: self.lock, parent: self, index: 6, setNextValue: { self.values7.enqueue($0) }, this: subscription7) + let observer8 = ZipObserver(lock: self.lock, parent: self, index: 7, setNextValue: { self.values8.enqueue($0) }, this: subscription8) + + subscription1.setDisposable(self.parent.source1.subscribe(observer1)) + subscription2.setDisposable(self.parent.source2.subscribe(observer2)) + subscription3.setDisposable(self.parent.source3.subscribe(observer3)) + subscription4.setDisposable(self.parent.source4.subscribe(observer4)) + subscription5.setDisposable(self.parent.source5.subscribe(observer5)) + subscription6.setDisposable(self.parent.source6.subscribe(observer6)) + subscription7.setDisposable(self.parent.source7.subscribe(observer7)) + subscription8.setDisposable(self.parent.source8.subscribe(observer8)) + + return Disposables.create([ + subscription1, + subscription2, + subscription3, + subscription4, + subscription5, + subscription6, + subscription7, + subscription8 + ]) + } + + override func getResult() throws -> Result { + try self.parent.resultSelector(self.values1.dequeue()!, self.values2.dequeue()!, self.values3.dequeue()!, self.values4.dequeue()!, self.values5.dequeue()!, self.values6.dequeue()!, self.values7.dequeue()!, self.values8.dequeue()!) + } +} + +final class Zip8 : Producer { + typealias ResultSelector = (E1, E2, E3, E4, E5, E6, E7, E8) throws -> Result + + let source1: Observable + let source2: Observable + let source3: Observable + let source4: Observable + let source5: Observable + let source6: Observable + let source7: Observable + let source8: Observable + + let resultSelector: ResultSelector + + init(source1: Observable, source2: Observable, source3: Observable, source4: Observable, source5: Observable, source6: Observable, source7: Observable, source8: Observable, resultSelector: @escaping ResultSelector) { + self.source1 = source1 + self.source2 = source2 + self.source3 = source3 + self.source4 = source4 + self.source5 = source5 + self.source6 = source6 + self.source7 = source7 + self.source8 = source8 + + self.resultSelector = resultSelector + } + + override func run(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result { + let sink = ZipSink8_(parent: self, observer: observer, cancel: cancel) + let subscription = sink.run() + return (sink: sink, subscription: subscription) + } +} + + diff --git a/Pods/RxSwift/RxSwift/Observables/Zip.swift b/Pods/RxSwift/RxSwift/Observables/Zip.swift new file mode 100644 index 0000000..328a40e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observables/Zip.swift @@ -0,0 +1,135 @@ +// +// Zip.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ZipSinkProtocol: AnyObject { + func next(_ index: Int) + func fail(_ error: Swift.Error) + func done(_ index: Int) +} + +class ZipSink : Sink, ZipSinkProtocol { + typealias Element = Observer.Element + + let arity: Int + + let lock = RecursiveLock() + + // state + private var isDone: [Bool] + + init(arity: Int, observer: Observer, cancel: Cancelable) { + self.isDone = [Bool](repeating: false, count: arity) + self.arity = arity + + super.init(observer: observer, cancel: cancel) + } + + func getResult() throws -> Element { + rxAbstractMethod() + } + + func hasElements(_ index: Int) -> Bool { + rxAbstractMethod() + } + + func next(_ index: Int) { + var hasValueAll = true + + for i in 0 ..< self.arity { + if !self.hasElements(i) { + hasValueAll = false + break + } + } + + if hasValueAll { + do { + let result = try self.getResult() + self.forwardOn(.next(result)) + } + catch let e { + self.forwardOn(.error(e)) + self.dispose() + } + } + } + + func fail(_ error: Swift.Error) { + self.forwardOn(.error(error)) + self.dispose() + } + + func done(_ index: Int) { + self.isDone[index] = true + + var allDone = true + + for done in self.isDone where !done { + allDone = false + break + } + + if allDone { + self.forwardOn(.completed) + self.dispose() + } + } +} + +final class ZipObserver + : ObserverType + , LockOwnerType + , SynchronizedOnType { + typealias ValueSetter = (Element) -> Void + + private var parent: ZipSinkProtocol? + + let lock: RecursiveLock + + // state + private let index: Int + private let this: Disposable + private let setNextValue: ValueSetter + + init(lock: RecursiveLock, parent: ZipSinkProtocol, index: Int, setNextValue: @escaping ValueSetter, this: Disposable) { + self.lock = lock + self.parent = parent + self.index = index + self.this = this + self.setNextValue = setNextValue + } + + func on(_ event: Event) { + self.synchronizedOn(event) + } + + func synchronized_on(_ event: Event) { + if self.parent != nil { + switch event { + case .next: + break + case .error: + self.this.dispose() + case .completed: + self.this.dispose() + } + } + + if let parent = self.parent { + switch event { + case .next(let value): + self.setNextValue(value) + parent.next(self.index) + case .error(let error): + parent.fail(error) + case .completed: + parent.done(self.index) + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/ObserverType.swift b/Pods/RxSwift/RxSwift/ObserverType.swift new file mode 100644 index 0000000..b7a6648 --- /dev/null +++ b/Pods/RxSwift/RxSwift/ObserverType.swift @@ -0,0 +1,40 @@ +// +// ObserverType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Supports push-style iteration over an observable sequence. +public protocol ObserverType { + /// The type of elements in sequence that observer can observe. + associatedtype Element + + /// Notify observer about sequence event. + /// + /// - parameter event: Event that occurred. + func on(_ event: Event) +} + +/// Convenience API extensions to provide alternate next, error, completed events +extension ObserverType { + + /// Convenience method equivalent to `on(.next(element: Element))` + /// + /// - parameter element: Next element to send to observer(s) + public func onNext(_ element: Element) { + self.on(.next(element)) + } + + /// Convenience method equivalent to `on(.completed)` + public func onCompleted() { + self.on(.completed) + } + + /// Convenience method equivalent to `on(.error(Swift.Error))` + /// - parameter error: Swift.Error to send to observer(s) + public func onError(_ error: Swift.Error) { + self.on(.error(error)) + } +} diff --git a/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift b/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift new file mode 100644 index 0000000..cbb42dc --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/AnonymousObserver.swift @@ -0,0 +1,30 @@ +// +// AnonymousObserver.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +final class AnonymousObserver: ObserverBase { + typealias EventHandler = (Event) -> Void + + private let eventHandler : EventHandler + + init(_ eventHandler: @escaping EventHandler) { +#if TRACE_RESOURCES + _ = Resources.incrementTotal() +#endif + self.eventHandler = eventHandler + } + + override func onCore(_ event: Event) { + self.eventHandler(event) + } + +#if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } +#endif +} diff --git a/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift b/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift new file mode 100644 index 0000000..48e0986 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/ObserverBase.swift @@ -0,0 +1,32 @@ +// +// ObserverBase.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/15/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +class ObserverBase : Disposable, ObserverType { + private let isStopped = AtomicInt(0) + + func on(_ event: Event) { + switch event { + case .next: + if load(self.isStopped) == 0 { + self.onCore(event) + } + case .error, .completed: + if fetchOr(self.isStopped, 1) == 0 { + self.onCore(event) + } + } + } + + func onCore(_ event: Event) { + rxAbstractMethod() + } + + func dispose() { + fetchOr(self.isStopped, 1) + } +} diff --git a/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift b/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift new file mode 100644 index 0000000..fd52700 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift @@ -0,0 +1,151 @@ +// +// TailRecursiveSink.swift +// RxSwift +// +// Created by Krunoslav Zaher on 3/21/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum TailRecursiveSinkCommand { + case moveNext + case dispose +} + +#if DEBUG || TRACE_RESOURCES + public var maxTailRecursiveSinkStackSize = 0 +#endif + +/// This class is usually used with `Generator` version of the operators. +class TailRecursiveSink + : Sink + , InvocableWithValueType where Sequence.Element: ObservableConvertibleType, Sequence.Element.Element == Observer.Element { + typealias Value = TailRecursiveSinkCommand + typealias Element = Observer.Element + typealias SequenceGenerator = (generator: Sequence.Iterator, remaining: IntMax?) + + var generators: [SequenceGenerator] = [] + var disposed = false + var subscription = SerialDisposable() + + // this is thread safe object + var gate = AsyncLock>>() + + override init(observer: Observer, cancel: Cancelable) { + super.init(observer: observer, cancel: cancel) + } + + func run(_ sources: SequenceGenerator) -> Disposable { + self.generators.append(sources) + + self.schedule(.moveNext) + + return self.subscription + } + + func invoke(_ command: TailRecursiveSinkCommand) { + switch command { + case .dispose: + self.disposeCommand() + case .moveNext: + self.moveNextCommand() + } + } + + // simple implementation for now + func schedule(_ command: TailRecursiveSinkCommand) { + self.gate.invoke(InvocableScheduledItem(invocable: self, state: command)) + } + + func done() { + self.forwardOn(.completed) + self.dispose() + } + + func extract(_ observable: Observable) -> SequenceGenerator? { + rxAbstractMethod() + } + + // should be done on gate locked + + private func moveNextCommand() { + var next: Observable? + + repeat { + guard let (g, left) = self.generators.last else { + break + } + + if self.isDisposed { + return + } + + self.generators.removeLast() + + var e = g + + guard let nextCandidate = e.next()?.asObservable() else { + continue + } + + // `left` is a hint of how many elements are left in generator. + // In case this is the last element, then there is no need to push + // that generator on stack. + // + // This is an optimization used to make sure in tail recursive case + // there is no memory leak in case this operator is used to generate non terminating + // sequence. + + if let knownOriginalLeft = left { + // `- 1` because generator.next() has just been called + if knownOriginalLeft - 1 >= 1 { + self.generators.append((e, knownOriginalLeft - 1)) + } + } + else { + self.generators.append((e, nil)) + } + + let nextGenerator = self.extract(nextCandidate) + + if let nextGenerator = nextGenerator { + self.generators.append(nextGenerator) + #if DEBUG || TRACE_RESOURCES + if maxTailRecursiveSinkStackSize < self.generators.count { + maxTailRecursiveSinkStackSize = self.generators.count + } + #endif + } + else { + next = nextCandidate + } + } while next == nil + + guard let existingNext = next else { + self.done() + return + } + + let disposable = SingleAssignmentDisposable() + self.subscription.disposable = disposable + disposable.setDisposable(self.subscribeToNext(existingNext)) + } + + func subscribeToNext(_ source: Observable) -> Disposable { + rxAbstractMethod() + } + + func disposeCommand() { + self.disposed = true + self.generators.removeAll(keepingCapacity: false) + } + + override func dispose() { + super.dispose() + + self.subscription.dispose() + self.gate.dispose() + + self.schedule(.dispose) + } +} + diff --git a/Pods/RxSwift/RxSwift/Reactive.swift b/Pods/RxSwift/RxSwift/Reactive.swift new file mode 100644 index 0000000..1bf390d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Reactive.swift @@ -0,0 +1,80 @@ +// +// Reactive.swift +// RxSwift +// +// Created by Yury Korolev on 5/2/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +/** + Use `Reactive` proxy as customization point for constrained protocol extensions. + + General pattern would be: + + // 1. Extend Reactive protocol with constrain on Base + // Read as: Reactive Extension where Base is a SomeType + extension Reactive where Base: SomeType { + // 2. Put any specific reactive extension for SomeType here + } + + With this approach we can have more specialized methods and properties using + `Base` and not just specialized on common base type. + + `Binder`s are also automatically synthesized using `@dynamicMemberLookup` for writable reference properties of the reactive base. + */ + +@dynamicMemberLookup +public struct Reactive { + /// Base object to extend. + public let base: Base + + /// Creates extensions with base object. + /// + /// - parameter base: Base object. + public init(_ base: Base) { + self.base = base + } + + /// Automatically synthesized binder for a key path between the reactive + /// base and one of its properties + public subscript(dynamicMember keyPath: ReferenceWritableKeyPath) -> Binder where Base: AnyObject { + Binder(self.base) { base, value in + base[keyPath: keyPath] = value + } + } +} + +/// A type that has reactive extensions. +public protocol ReactiveCompatible { + /// Extended type + associatedtype ReactiveBase + + /// Reactive extensions. + static var rx: Reactive.Type { get set } + + /// Reactive extensions. + var rx: Reactive { get set } +} + +extension ReactiveCompatible { + /// Reactive extensions. + public static var rx: Reactive.Type { + get { Reactive.self } + // this enables using Reactive to "mutate" base type + // swiftlint:disable:next unused_setter_value + set { } + } + + /// Reactive extensions. + public var rx: Reactive { + get { Reactive(self) } + // this enables using Reactive to "mutate" base object + // swiftlint:disable:next unused_setter_value + set { } + } +} + +import Foundation + +/// Extend NSObject with `rx` proxy. +extension NSObject: ReactiveCompatible { } diff --git a/Pods/RxSwift/RxSwift/Rx.swift b/Pods/RxSwift/RxSwift/Rx.swift new file mode 100644 index 0000000..bcdd279 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Rx.swift @@ -0,0 +1,142 @@ +// +// Rx.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if TRACE_RESOURCES + private let resourceCount = AtomicInt(0) + + /// Resource utilization information + public struct Resources { + /// Counts internal Rx resource allocations (Observables, Observers, Disposables, etc.). This provides a simple way to detect leaks during development. + public static var total: Int32 { + load(resourceCount) + } + + /// Increments `Resources.total` resource count. + /// + /// - returns: New resource count + public static func incrementTotal() -> Int32 { + increment(resourceCount) + } + + /// Decrements `Resources.total` resource count + /// + /// - returns: New resource count + public static func decrementTotal() -> Int32 { + decrement(resourceCount) + } + } +#endif + +/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass. +func rxAbstractMethod(file: StaticString = #file, line: UInt = #line) -> Swift.Never { + rxFatalError("Abstract method", file: file, line: line) +} + +func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never { + fatalError(lastMessage(), file: file, line: line) +} + +func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) { + #if DEBUG + fatalError(lastMessage(), file: file, line: line) + #else + print("\(file):\(line): \(lastMessage())") + #endif +} + +func incrementChecked(_ i: inout Int) throws -> Int { + if i == Int.max { + throw RxError.overflow + } + defer { i += 1 } + return i +} + +func decrementChecked(_ i: inout Int) throws -> Int { + if i == Int.min { + throw RxError.overflow + } + defer { i -= 1 } + return i +} + +#if DEBUG + import Foundation + final class SynchronizationTracker { + private let lock = RecursiveLock() + + public enum SynchronizationErrorMessages: String { + case variable = "Two different threads are trying to assign the same `Variable.value` unsynchronized.\n This is undefined behavior because the end result (variable value) is nondeterministic and depends on the \n operating system thread scheduler. This will cause random behavior of your program.\n" + case `default` = "Two different unsynchronized threads are trying to send some event simultaneously.\n This is undefined behavior because the ordering of the effects caused by these events is nondeterministic and depends on the \n operating system thread scheduler. This will result in a random behavior of your program.\n" + } + + private var threads = [UnsafeMutableRawPointer: Int]() + + private func synchronizationError(_ message: String) { + #if FATAL_SYNCHRONIZATION + rxFatalError(message) + #else + print(message) + #endif + } + + func register(synchronizationErrorMessage: SynchronizationErrorMessages) { + self.lock.lock(); defer { self.lock.unlock() } + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + let count = (self.threads[pointer] ?? 0) + 1 + + if count > 1 { + self.synchronizationError( + "⚠️ Reentrancy anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: This could mean that there is some kind of unexpected cyclic dependency in your code,\n" + + " or that the system is not behaving in the expected way.\n" + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by enqueuing sequence events in some other way.\n" + ) + } + + self.threads[pointer] = count + + if self.threads.count > 1 { + self.synchronizationError( + "⚠️ Synchronization anomaly was detected.\n" + + " > Debugging: To debug this issue you can set a breakpoint in \(#file):\(#line) and observe the call stack.\n" + + " > Problem: This behavior is breaking the observable sequence grammar. `next (error | completed)?`\n" + + " This behavior breaks the grammar because there is overlapping between sequence events.\n" + + " Observable sequence is trying to send an event before sending of previous event has finished.\n" + + " > Interpretation: " + synchronizationErrorMessage.rawValue + + " > Remedy: If this is the expected behavior this message can be suppressed by adding `.observe(on:MainScheduler.asyncInstance)`\n" + + " or by synchronizing sequence events in some other way.\n" + ) + } + } + + func unregister() { + self.lock.performLocked { + let pointer = Unmanaged.passUnretained(Thread.current).toOpaque() + self.threads[pointer] = (self.threads[pointer] ?? 1) - 1 + if self.threads[pointer] == 0 { + self.threads[pointer] = nil + } + } + } + } + +#endif + +/// RxSwift global hooks +public enum Hooks { + + // Should capture call stack + public static var recordCallStackOnError: Bool = false + +} diff --git a/Pods/RxSwift/RxSwift/RxMutableBox.swift b/Pods/RxSwift/RxSwift/RxMutableBox.swift new file mode 100644 index 0000000..73476c3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/RxMutableBox.swift @@ -0,0 +1,53 @@ +// +// RxMutableBox.swift +// RxSwift +// +// Created by Krunoslav Zaher on 5/22/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +#if os(Linux) +/// As Swift 5 was released, A patch to `Thread` for Linux +/// changed `threadDictionary` to a `NSMutableDictionary` instead of +/// a `Dictionary`: https://github.com/apple/swift-corelibs-foundation/pull/1762/files +/// +/// This means that on Linux specifically, `RxMutableBox` must be a `NSObject` +/// or it won't be possible to store it in `Thread.threadDictionary`. +/// +/// For more information, read the discussion at: +/// https://github.com/ReactiveX/RxSwift/issues/1911#issuecomment-479723298 +import Foundation + +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: NSObject { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} +#else +/// Creates mutable reference wrapper for any type. +final class RxMutableBox: CustomDebugStringConvertible { + /// Wrapped value + var value: T + + /// Creates reference wrapper for `value`. + /// + /// - parameter value: Value to wrap. + init (_ value: T) { + self.value = value + } +} + +extension RxMutableBox { + /// - returns: Box description. + var debugDescription: String { + "MutatingBox(\(self.value))" + } +} +#endif diff --git a/Pods/RxSwift/RxSwift/SchedulerType.swift b/Pods/RxSwift/RxSwift/SchedulerType.swift new file mode 100644 index 0000000..6c8fe4a --- /dev/null +++ b/Pods/RxSwift/RxSwift/SchedulerType.swift @@ -0,0 +1,71 @@ +// +// SchedulerType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +// Type that represents time interval in the context of RxSwift. +public typealias RxTimeInterval = DispatchTimeInterval + +/// Type that represents absolute time in the context of RxSwift. +public typealias RxTime = Date + +/// Represents an object that schedules units of work. +public protocol SchedulerType: ImmediateSchedulerType { + + /// - returns: Current time. + var now : RxTime { + get + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable +} + +extension SchedulerType { + + /** + Periodic task will be emulated using recursive scheduling. + + - parameter state: Initial state passed to the action upon the first iteration. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - returns: The disposable object used to cancel the scheduled recurring action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let schedule = SchedulePeriodicRecursive(scheduler: self, startAfter: startAfter, period: period, action: action, state: state) + + return schedule.start() + } + + func scheduleRecursive(_ state: State, dueTime: RxTimeInterval, action: @escaping (State, AnyRecursiveScheduler) -> Void) -> Disposable { + let scheduler = AnyRecursiveScheduler(scheduler: self, action: action) + + scheduler.schedule(state, dueTime: dueTime) + + return Disposables.create(with: scheduler.dispose) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift new file mode 100644 index 0000000..02c47c9 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentDispatchQueueScheduler.swift @@ -0,0 +1,82 @@ +// +// ConcurrentDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/5/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. You can also pass a serial dispatch queue, it shouldn't cause any problems. +/// +/// This scheduler is suitable when some work needs to be performed in background. +public class ConcurrentDispatchQueueScheduler: SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /// Constructs new `ConcurrentDispatchQueueScheduler` that wraps `queue`. + /// + /// - parameter queue: Target dispatch queue. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public init(queue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: queue, leeway: leeway) + } + + /// Convenience init for scheduler that wraps one of the global concurrent dispatch queues. + /// + /// - parameter qos: Target global dispatch queue, by quality of service class. + /// - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + public convenience init(qos: DispatchQoS, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue( + label: "rxswift.queue.\(qos)", + qos: qos, + attributes: [DispatchQueue.Attributes.concurrent], + target: nil), + leeway: leeway + ) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift new file mode 100644 index 0000000..c438d7d --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/ConcurrentMainScheduler.swift @@ -0,0 +1,87 @@ +// +// ConcurrentMainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 10/17/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts work that needs to be performed on `MainThread`. In case `schedule` methods are called from main thread, it will perform action immediately without scheduling. + +This scheduler is optimized for `subscribeOn` operator. If you want to observe observable sequence elements on main thread using `observeOn` operator, +`MainScheduler` is more suitable for that purpose. +*/ +public final class ConcurrentMainScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + private let mainScheduler: MainScheduler + private let mainQueue: DispatchQueue + + /// - returns: Current time. + public var now: Date { + self.mainScheduler.now as Date + } + + private init(mainScheduler: MainScheduler) { + self.mainQueue = DispatchQueue.main + self.mainScheduler = mainScheduler + } + + /// Singleton instance of `ConcurrentMainScheduler` + public static let instance = ConcurrentMainScheduler(mainScheduler: MainScheduler.instance) + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if DispatchQueue.isMain { + return action(state) + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if cancel.isDisposed { + return + } + + cancel.setDisposable(action(state)) + } + + return cancel + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.mainScheduler.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.mainScheduler.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift new file mode 100644 index 0000000..16a7dd3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift @@ -0,0 +1,131 @@ +// +// CurrentThreadScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 8/30/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +#if os(Linux) + fileprivate enum CurrentThreadSchedulerQueueKey { + fileprivate static let instance = "RxSwift.CurrentThreadScheduler.Queue" + } +#else + private class CurrentThreadSchedulerQueueKey: NSObject, NSCopying { + static let instance = CurrentThreadSchedulerQueueKey() + private override init() { + super.init() + } + + override var hash: Int { + return 0 + } + + public func copy(with zone: NSZone? = nil) -> Any { + return self + } + } +#endif + +/// Represents an object that schedules units of work on the current thread. +/// +/// This is the default scheduler for operators that generate elements. +/// +/// This scheduler is also sometimes called `trampoline scheduler`. +public class CurrentThreadScheduler : ImmediateSchedulerType { + typealias ScheduleQueue = RxMutableBox> + + /// The singleton instance of the current thread scheduler. + public static let instance = CurrentThreadScheduler() + + private static var isScheduleRequiredKey: pthread_key_t = { () -> pthread_key_t in + let key = UnsafeMutablePointer.allocate(capacity: 1) + defer { key.deallocate() } + + guard pthread_key_create(key, nil) == 0 else { + rxFatalError("isScheduleRequired key creation failed") + } + + return key.pointee + }() + + private static var scheduleInProgressSentinel: UnsafeRawPointer = { () -> UnsafeRawPointer in + return UnsafeRawPointer(UnsafeMutablePointer.allocate(capacity: 1)) + }() + + static var queue : ScheduleQueue? { + get { + return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKey.instance) + } + set { + Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKey.instance) + } + } + + /// Gets a value that indicates whether the caller must call a `schedule` method. + public static private(set) var isScheduleRequired: Bool { + get { + return pthread_getspecific(CurrentThreadScheduler.isScheduleRequiredKey) == nil + } + set(isScheduleRequired) { + if pthread_setspecific(CurrentThreadScheduler.isScheduleRequiredKey, isScheduleRequired ? nil : scheduleInProgressSentinel) != 0 { + rxFatalError("pthread_setspecific failed") + } + } + } + + /** + Schedules an action to be executed as soon as possible on current thread. + + If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be + automatically installed and uninstalled after all work is performed. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + if CurrentThreadScheduler.isScheduleRequired { + CurrentThreadScheduler.isScheduleRequired = false + + let disposable = action(state) + + defer { + CurrentThreadScheduler.isScheduleRequired = true + CurrentThreadScheduler.queue = nil + } + + guard let queue = CurrentThreadScheduler.queue else { + return disposable + } + + while let latest = queue.value.dequeue() { + if latest.isDisposed { + continue + } + latest.invoke() + } + + return disposable + } + + let existingQueue = CurrentThreadScheduler.queue + + let queue: RxMutableBox> + if let existingQueue = existingQueue { + queue = existingQueue + } + else { + queue = RxMutableBox(Queue(capacity: 1)) + CurrentThreadScheduler.queue = queue + } + + let scheduledItem = ScheduledItem(action: action, state: state) + queue.value.enqueue(scheduledItem) + + return scheduledItem + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift new file mode 100644 index 0000000..fede60e --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/HistoricalScheduler.swift @@ -0,0 +1,22 @@ +// +// HistoricalScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Provides a virtual time scheduler that uses `Date` for absolute time and `NSTimeInterval` for relative time. +public class HistoricalScheduler : VirtualTimeScheduler { + + /** + Creates a new historical scheduler with initial clock value. + + - parameter initialClock: Initial value for virtual clock. + */ + public init(initialClock: RxTime = Date(timeIntervalSince1970: 0)) { + super.init(initialClock: initialClock, converter: HistoricalSchedulerTimeConverter()) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift b/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift new file mode 100644 index 0000000..a8fae8a --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/HistoricalSchedulerTimeConverter.swift @@ -0,0 +1,67 @@ +// +// HistoricalSchedulerTimeConverter.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/27/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Converts historical virtual time into real time. +/// +/// Since historical virtual time is also measured in `Date`, this converter is identity function. +public struct HistoricalSchedulerTimeConverter : VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + public typealias VirtualTimeUnit = RxTime + + /// Virtual time unit used to represent differences of virtual times. + public typealias VirtualTimeIntervalUnit = TimeInterval + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime { + virtualTime + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit { + time + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval { + virtualTimeInterval + } + + /// Returns identical value of argument passed because historical virtual time is equal to real time, just + /// decoupled from local machine clock. + public func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit { + timeInterval + } + + /** + Offsets `Date` by time interval. + + - parameter time: Time. + - parameter timeInterval: Time interval offset. + - returns: Time offsetted by time interval. + */ + public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit { + time.addingTimeInterval(offset) + } + + /// Compares two `Date`s. + public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison { + switch lhs.compare(rhs as Date) { + case .orderedAscending: + return .lessThan + case .orderedSame: + return .equal + case .orderedDescending: + return .greaterThan + } + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift new file mode 100644 index 0000000..f313c0b --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/DispatchQueueConfiguration.swift @@ -0,0 +1,97 @@ +// +// DispatchQueueConfiguration.swift +// RxSwift +// +// Created by Krunoslav Zaher on 7/23/16. +// Copyright © 2016 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +struct DispatchQueueConfiguration { + let queue: DispatchQueue + let leeway: DispatchTimeInterval +} + +extension DispatchQueueConfiguration { + func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + self.queue.async { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + return cancel + } + + func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let deadline = DispatchTime.now() + dueTime + + let compositeDisposable = CompositeDisposable() + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: deadline, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if compositeDisposable.isDisposed { + return + } + _ = compositeDisposable.insert(action(state)) + cancelTimer.dispose() + }) + timer.resume() + + _ = compositeDisposable.insert(cancelTimer) + + return compositeDisposable + } + + func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + let initial = DispatchTime.now() + startAfter + + var timerState = state + + let timer = DispatchSource.makeTimerSource(queue: self.queue) + timer.schedule(deadline: initial, repeating: period, leeway: self.leeway) + + // TODO: + // This looks horrible, and yes, it is. + // It looks like Apple has made a conceputal change here, and I'm unsure why. + // Need more info on this. + // It looks like just setting timer to fire and not holding a reference to it + // until deadline causes timer cancellation. + var timerReference: DispatchSourceTimer? = timer + let cancelTimer = Disposables.create { + timerReference?.cancel() + timerReference = nil + } + + timer.setEventHandler(handler: { + if cancelTimer.isDisposed { + return + } + timerState = action(timerState) + }) + timer.resume() + + return cancelTimer + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift new file mode 100644 index 0000000..0e15056 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableScheduledItem.swift @@ -0,0 +1,22 @@ +// +// InvocableScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct InvocableScheduledItem : InvocableType { + + let invocable: I + let state: I.Value + + init(invocable: I, state: I.Value) { + self.invocable = invocable + self.state = state + } + + func invoke() { + self.invocable.invoke(self.state) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift new file mode 100644 index 0000000..0dba433 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/InvocableType.swift @@ -0,0 +1,17 @@ +// +// InvocableType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol InvocableType { + func invoke() +} + +protocol InvocableWithValueType { + associatedtype Value + + func invoke(_ value: Value) +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift new file mode 100644 index 0000000..3d790d7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItem.swift @@ -0,0 +1,35 @@ +// +// ScheduledItem.swift +// RxSwift +// +// Created by Krunoslav Zaher on 9/2/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +struct ScheduledItem + : ScheduledItemType + , InvocableType { + typealias Action = (T) -> Disposable + + private let action: Action + private let state: T + + private let disposable = SingleAssignmentDisposable() + + var isDisposed: Bool { + self.disposable.isDisposed + } + + init(action: @escaping Action, state: T) { + self.action = action + self.state = state + } + + func invoke() { + self.disposable.setDisposable(self.action(self.state)) + } + + func dispose() { + self.disposable.dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift new file mode 100644 index 0000000..d2b16ca --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/Internal/ScheduledItemType.swift @@ -0,0 +1,13 @@ +// +// ScheduledItemType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 11/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +protocol ScheduledItemType + : Cancelable + , InvocableType { + func invoke() +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift new file mode 100644 index 0000000..703ab44 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/MainScheduler.swift @@ -0,0 +1,80 @@ +// +// MainScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +#if !os(Linux) + import Foundation +#endif + +/** +Abstracts work that needs to be performed on `DispatchQueue.main`. In case `schedule` methods are called from `DispatchQueue.main`, it will perform action immediately without scheduling. + +This scheduler is usually used to perform UI work. + +Main scheduler is a specialization of `SerialDispatchQueueScheduler`. + +This scheduler is optimized for `observeOn` operator. To ensure observable sequence is subscribed on main thread using `subscribeOn` +operator please use `ConcurrentMainScheduler` because it is more optimized for that purpose. +*/ +public final class MainScheduler : SerialDispatchQueueScheduler { + + private let mainQueue: DispatchQueue + + let numberEnqueued = AtomicInt(0) + + /// Initializes new instance of `MainScheduler`. + public init() { + self.mainQueue = DispatchQueue.main + super.init(serialQueue: self.mainQueue) + } + + /// Singleton instance of `MainScheduler` + public static let instance = MainScheduler() + + /// Singleton instance of `MainScheduler` that always schedules work asynchronously + /// and doesn't perform optimizations for calls scheduled from main queue. + public static let asyncInstance = SerialDispatchQueueScheduler(serialQueue: DispatchQueue.main) + + /// In case this method is called on a background thread it will throw an exception. + public class func ensureExecutingOnScheduler(errorMessage: String? = nil) { + if !DispatchQueue.isMain { + rxFatalError(errorMessage ?? "Executing on background thread. Please use `MainScheduler.instance.schedule` to schedule work on main thread.") + } + } + + /// In case this method is running on a background thread it will throw an exception. + public class func ensureRunningOnMainThread(errorMessage: String? = nil) { + #if !os(Linux) // isMainThread is not implemented in Linux Foundation + guard Thread.isMainThread else { + rxFatalError(errorMessage ?? "Running on background thread.") + } + #endif + } + + override func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let previousNumberEnqueued = increment(self.numberEnqueued) + + if DispatchQueue.isMain && previousNumberEnqueued == 0 { + let disposable = action(state) + decrement(self.numberEnqueued) + return disposable + } + + let cancel = SingleAssignmentDisposable() + + self.mainQueue.async { + if !cancel.isDisposed { + cancel.setDisposable(action(state)) + } + + decrement(self.numberEnqueued) + } + + return cancel + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift new file mode 100644 index 0000000..f0ad3d3 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/OperationQueueScheduler.swift @@ -0,0 +1,54 @@ +// +// OperationQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 4/4/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/// Abstracts the work that needs to be performed on a specific `NSOperationQueue`. +/// +/// This scheduler is suitable for cases when there is some bigger chunk of work that needs to be performed in background and you want to fine tune concurrent processing using `maxConcurrentOperationCount`. +public class OperationQueueScheduler: ImmediateSchedulerType { + public let operationQueue: OperationQueue + public let queuePriority: Operation.QueuePriority + + /// Constructs new instance of `OperationQueueScheduler` that performs work on `operationQueue`. + /// + /// - parameter operationQueue: Operation queue targeted to perform work on. + /// - parameter queuePriority: Queue priority which will be assigned to new operations. + public init(operationQueue: OperationQueue, queuePriority: Operation.QueuePriority = .normal) { + self.operationQueue = operationQueue + self.queuePriority = queuePriority + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + let cancel = SingleAssignmentDisposable() + + let operation = BlockOperation { + if cancel.isDisposed { + return + } + + + cancel.setDisposable(action(state)) + } + + operation.queuePriority = self.queuePriority + + self.operationQueue.addOperation(operation) + + return cancel + } + +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift new file mode 100644 index 0000000..0ee78cd --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/RecursiveScheduler.swift @@ -0,0 +1,220 @@ +// +// RecursiveScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/7/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +private enum ScheduleState { + case initial + case added(CompositeDisposable.DisposeKey) + case done +} + +/// Type erased recursive scheduler. +final class AnyRecursiveScheduler { + + typealias Action = (State, AnyRecursiveScheduler) -> Void + + private let lock = RecursiveLock() + + // state + private let group = CompositeDisposable() + + private var scheduler: SchedulerType + private var action: Action? + + init(scheduler: SchedulerType, action: @escaping Action) { + self.action = action + self.scheduler = scheduler + } + + /** + Schedules an action to be executed recursively. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the recursive action. + */ + func schedule(_ state: State, dueTime: RxTimeInterval) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.scheduleRelative(state, dueTime: dueTime) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} + +/// Type erased recursive scheduler. +final class RecursiveImmediateScheduler { + typealias Action = (_ state: State, _ recurse: (State) -> Void) -> Void + + private var lock = SpinLock() + private let group = CompositeDisposable() + + private var action: Action? + private let scheduler: ImmediateSchedulerType + + init(action: @escaping Action, scheduler: ImmediateSchedulerType) { + self.action = action + self.scheduler = scheduler + } + + // immediate scheduling + + /// Schedules an action to be executed recursively. + /// + /// - parameter state: State passed to the action to be executed. + func schedule(_ state: State) { + var scheduleState: ScheduleState = .initial + + let d = self.scheduler.schedule(state) { state -> Disposable in + // best effort + if self.group.isDisposed { + return Disposables.create() + } + + let action = self.lock.performLocked { () -> Action? in + switch scheduleState { + case let .added(removeKey): + self.group.remove(for: removeKey) + case .initial: + break + case .done: + break + } + + scheduleState = .done + + return self.action + } + + if let action = action { + action(state, self.schedule) + } + + return Disposables.create() + } + + self.lock.performLocked { + switch scheduleState { + case .added: + rxFatalError("Invalid state") + case .initial: + if let removeKey = self.group.insert(d) { + scheduleState = .added(removeKey) + } + else { + scheduleState = .done + } + case .done: + break + } + } + } + + func dispose() { + self.lock.performLocked { + self.action = nil + } + self.group.dispose() + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift b/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift new file mode 100644 index 0000000..cab2bc8 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/SchedulerServices+Emulation.swift @@ -0,0 +1,61 @@ +// +// SchedulerServices+Emulation.swift +// RxSwift +// +// Created by Krunoslav Zaher on 6/6/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +enum SchedulePeriodicRecursiveCommand { + case tick + case dispatchStart +} + +final class SchedulePeriodicRecursive { + typealias RecursiveAction = (State) -> State + typealias RecursiveScheduler = AnyRecursiveScheduler + + private let scheduler: SchedulerType + private let startAfter: RxTimeInterval + private let period: RxTimeInterval + private let action: RecursiveAction + + private var state: State + private let pendingTickCount = AtomicInt(0) + + init(scheduler: SchedulerType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping RecursiveAction, state: State) { + self.scheduler = scheduler + self.startAfter = startAfter + self.period = period + self.action = action + self.state = state + } + + func start() -> Disposable { + self.scheduler.scheduleRecursive(SchedulePeriodicRecursiveCommand.tick, dueTime: self.startAfter, action: self.tick) + } + + func tick(_ command: SchedulePeriodicRecursiveCommand, scheduler: RecursiveScheduler) { + // Tries to emulate periodic scheduling as best as possible. + // The problem that could arise is if handling periodic ticks take too long, or + // tick interval is short. + switch command { + case .tick: + scheduler.schedule(.tick, dueTime: self.period) + + // The idea is that if on tick there wasn't any item enqueued, schedule to perform work immediately. + // Else work will be scheduled after previous enqueued work completes. + if increment(self.pendingTickCount) == 0 { + self.tick(.dispatchStart, scheduler: scheduler) + } + + case .dispatchStart: + self.state = self.action(self.state) + // Start work and schedule check is this last batch of work + if decrement(self.pendingTickCount) > 1 { + // This gives priority to scheduler emulation, it's not perfect, but helps + scheduler.schedule(SchedulePeriodicRecursiveCommand.dispatchStart) + } + } + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift new file mode 100644 index 0000000..bb0013c --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/SerialDispatchQueueScheduler.swift @@ -0,0 +1,131 @@ +// +// SerialDispatchQueueScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/8/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Dispatch +import Foundation + +/** +Abstracts the work that needs to be performed on a specific `dispatch_queue_t`. It will make sure +that even if concurrent dispatch queue is passed, it's transformed into a serial one. + +It is extremely important that this scheduler is serial, because +certain operator perform optimizations that rely on that property. + +Because there is no way of detecting is passed dispatch queue serial or +concurrent, for every queue that is being passed, worst case (concurrent) +will be assumed, and internal serial proxy dispatch queue will be created. + +This scheduler can also be used with internal serial queue alone. + +In case some customization need to be made on it before usage, +internal serial queue can be customized using `serialQueueConfiguration` +callback. +*/ +public class SerialDispatchQueueScheduler : SchedulerType { + public typealias TimeInterval = Foundation.TimeInterval + public typealias Time = Date + + /// - returns: Current time. + public var now : Date { + Date() + } + + let configuration: DispatchQueueConfiguration + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps `serialQueue`. + + - parameter serialQueue: Target dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + init(serialQueue: DispatchQueue, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.configuration = DispatchQueueConfiguration(queue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` with internal serial queue named `internalSerialQueueName`. + + Additional dispatch queue properties can be set after dispatch queue is created using `serialQueueConfiguration`. + + - parameter internalSerialQueueName: Name of internal serial dispatch queue. + - parameter serialQueueConfiguration: Additional configuration of internal serial dispatch queue. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(internalSerialQueueName: String, serialQueueConfiguration: ((DispatchQueue) -> Void)? = nil, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + let queue = DispatchQueue(label: internalSerialQueueName, attributes: []) + serialQueueConfiguration?(queue) + self.init(serialQueue: queue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` named `internalSerialQueueName` that wraps `queue`. + + - parameter queue: Possibly concurrent dispatch queue used to perform work. + - parameter internalSerialQueueName: Name of internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + public convenience init(queue: DispatchQueue, internalSerialQueueName: String, leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + // Swift 3.0 IUO + let serialQueue = DispatchQueue(label: internalSerialQueueName, + attributes: [], + target: queue) + self.init(serialQueue: serialQueue, leeway: leeway) + } + + /** + Constructs new `SerialDispatchQueueScheduler` that wraps one of the global concurrent dispatch queues. + + - parameter qos: Identifier for global dispatch queue with specified quality of service class. + - parameter internalSerialQueueName: Custom name for internal serial dispatch queue proxy. + - parameter leeway: The amount of time, in nanoseconds, that the system will defer the timer. + */ + @available(macOS 10.10, *) + public convenience init(qos: DispatchQoS, internalSerialQueueName: String = "rx.global_dispatch_queue.serial", leeway: DispatchTimeInterval = DispatchTimeInterval.nanoseconds(0)) { + self.init(queue: DispatchQueue.global(qos: qos.qosClass), internalSerialQueueName: internalSerialQueueName, leeway: leeway) + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.scheduleInternal(state, action: action) + } + + func scheduleInternal(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.schedule(state, action: action) + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public final func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + self.configuration.scheduleRelative(state, dueTime: dueTime, action: action) + } + + /** + Schedules a periodic piece of work. + + - parameter state: State passed to the action to be executed. + - parameter startAfter: Period after which initial work should be run. + - parameter period: Period for running the work periodically. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedulePeriodic(_ state: StateType, startAfter: RxTimeInterval, period: RxTimeInterval, action: @escaping (StateType) -> StateType) -> Disposable { + self.configuration.schedulePeriodic(state, startAfter: startAfter, period: period, action: action) + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift new file mode 100644 index 0000000..34151f7 --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift @@ -0,0 +1,97 @@ +// +// VirtualTimeConverterType.swift +// RxSwift +// +// Created by Krunoslav Zaher on 12/23/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +import Foundation + +/// Parametrization for virtual time used by `VirtualTimeScheduler`s. +public protocol VirtualTimeConverterType { + /// Virtual time unit used that represents ticks of virtual clock. + associatedtype VirtualTimeUnit + + /// Virtual time unit used to represent differences of virtual times. + associatedtype VirtualTimeIntervalUnit + + /** + Converts virtual time to real time. + + - parameter virtualTime: Virtual time to convert to `Date`. + - returns: `Date` corresponding to virtual time. + */ + func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime + + /** + Converts real time to virtual time. + + - parameter time: `Date` to convert to virtual time. + - returns: Virtual time corresponding to `Date`. + */ + func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit + + /** + Converts from virtual time interval to `NSTimeInterval`. + + - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. + - returns: `NSTimeInterval` corresponding to virtual time interval. + */ + func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> TimeInterval + + /** + Converts from `NSTimeInterval` to virtual time interval. + + - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. + - returns: Virtual time interval corresponding to time interval. + */ + func convertToVirtualTimeInterval(_ timeInterval: TimeInterval) -> VirtualTimeIntervalUnit + + /** + Offsets virtual time by virtual time interval. + + - parameter time: Virtual time. + - parameter offset: Virtual time interval. + - returns: Time corresponding to time offsetted by virtual time interval. + */ + func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit + + /** + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. + */ + func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison +} + +/** + Virtual time comparison result. + + This is additional abstraction because `Date` is unfortunately not comparable. + Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. +*/ +public enum VirtualTimeComparison { + /// lhs < rhs. + case lessThan + /// lhs == rhs. + case equal + /// lhs > rhs. + case greaterThan +} + +extension VirtualTimeComparison { + /// lhs < rhs. + var lessThen: Bool { + self == .lessThan + } + + /// lhs > rhs + var greaterThan: Bool { + self == .greaterThan + } + + /// lhs == rhs + var equal: Bool { + self == .equal + } +} diff --git a/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift new file mode 100644 index 0000000..e74d5be --- /dev/null +++ b/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeScheduler.swift @@ -0,0 +1,267 @@ +// +// VirtualTimeScheduler.swift +// RxSwift +// +// Created by Krunoslav Zaher on 2/14/15. +// Copyright © 2015 Krunoslav Zaher. All rights reserved. +// + +/// Base class for virtual time schedulers using a priority queue for scheduled items. +open class VirtualTimeScheduler + : SchedulerType { + + public typealias VirtualTime = Converter.VirtualTimeUnit + public typealias VirtualTimeInterval = Converter.VirtualTimeIntervalUnit + + private var running : Bool + + private var currentClock: VirtualTime + + private var schedulerQueue : PriorityQueue> + private var converter: Converter + + private var nextId = 0 + + /// - returns: Current time. + public var now: RxTime { + self.converter.convertFromVirtualTime(self.clock) + } + + /// - returns: Scheduler's absolute time clock value. + public var clock: VirtualTime { + self.currentClock + } + + /// Creates a new virtual time scheduler. + /// + /// - parameter initialClock: Initial value for the clock. + public init(initialClock: VirtualTime, converter: Converter) { + self.currentClock = initialClock + self.running = false + self.converter = converter + self.schedulerQueue = PriorityQueue(hasHigherPriority: { + switch converter.compareVirtualTime($0.time, $1.time) { + case .lessThan: + return true + case .equal: + return $0.id < $1.id + case .greaterThan: + return false + } + }, isEqual: { $0 === $1 }) + #if TRACE_RESOURCES + _ = Resources.incrementTotal() + #endif + } + + /** + Schedules an action to be executed immediately. + + - parameter state: State passed to the action to be executed. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func schedule(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable { + return self.scheduleRelative(state, dueTime: .microseconds(0)) { a in + return action(a) + } + } + + /** + Schedules an action to be executed. + + - parameter state: State passed to the action to be executed. + - parameter dueTime: Relative time after which to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelative(_ state: StateType, dueTime: RxTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.now.addingDispatchInterval(dueTime) + let absoluteTime = self.converter.convertToVirtualTime(time) + let adjustedTime = self.adjustScheduledTime(absoluteTime) + return self.scheduleAbsoluteVirtual(state, time: adjustedTime, action: action) + } + + /** + Schedules an action to be executed after relative time has passed. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. If this is less or equal then `now`, `now + 1` will be used. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleRelativeVirtual(_ state: StateType, dueTime: VirtualTimeInterval, action: @escaping (StateType) -> Disposable) -> Disposable { + let time = self.converter.offsetVirtualTime(self.clock, offset: dueTime) + return self.scheduleAbsoluteVirtual(state, time: time, action: action) + } + + /** + Schedules an action to be executed at absolute virtual time. + + - parameter state: State passed to the action to be executed. + - parameter time: Absolute time when to execute the action. + - parameter action: Action to be executed. + - returns: The disposable object used to cancel the scheduled action (best effort). + */ + public func scheduleAbsoluteVirtual(_ state: StateType, time: VirtualTime, action: @escaping (StateType) -> Disposable) -> Disposable { + MainScheduler.ensureExecutingOnScheduler() + + let compositeDisposable = CompositeDisposable() + + let item = VirtualSchedulerItem(action: { + return action(state) + }, time: time, id: self.nextId) + + self.nextId += 1 + + self.schedulerQueue.enqueue(item) + + _ = compositeDisposable.insert(item) + + return compositeDisposable + } + + /// Adjusts time of scheduling before adding item to schedule queue. + open func adjustScheduledTime(_ time: VirtualTime) -> VirtualTime { + time + } + + /// Starts the virtual time scheduler. + public func start() { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + return + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.running = false + } + + func findNext() -> VirtualSchedulerItem? { + while let front = self.schedulerQueue.peek() { + if front.isDisposed { + self.schedulerQueue.remove(front) + continue + } + + return front + } + + return nil + } + + /// Advances the scheduler's clock to the specified time, running all work till that point. + /// + /// - parameter virtualTime: Absolute time to advance the scheduler's clock to. + public func advanceTo(_ virtualTime: VirtualTime) { + MainScheduler.ensureExecutingOnScheduler() + + if self.running { + fatalError("Scheduler is already running") + } + + self.running = true + repeat { + guard let next = self.findNext() else { + break + } + + if self.converter.compareVirtualTime(next.time, virtualTime).greaterThan { + break + } + + if self.converter.compareVirtualTime(next.time, self.clock).greaterThan { + self.currentClock = next.time + } + next.invoke() + self.schedulerQueue.remove(next) + } while self.running + + self.currentClock = virtualTime + self.running = false + } + + /// Advances the scheduler's clock by the specified relative time. + public func sleep(_ virtualInterval: VirtualTimeInterval) { + MainScheduler.ensureExecutingOnScheduler() + + let sleepTo = self.converter.offsetVirtualTime(self.clock, offset: virtualInterval) + if self.converter.compareVirtualTime(sleepTo, self.clock).lessThen { + fatalError("Can't sleep to past.") + } + + self.currentClock = sleepTo + } + + /// Stops the virtual time scheduler. + public func stop() { + MainScheduler.ensureExecutingOnScheduler() + + self.running = false + } + + #if TRACE_RESOURCES + deinit { + _ = Resources.decrementTotal() + } + #endif +} + +// MARK: description + +extension VirtualTimeScheduler: CustomDebugStringConvertible { + /// A textual representation of `self`, suitable for debugging. + public var debugDescription: String { + self.schedulerQueue.debugDescription + } +} + +final class VirtualSchedulerItem